file_path
stringlengths 21
202
| content
stringlengths 13
1.02M
| size
int64 13
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 5.43
98.5
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.91
|
---|---|---|---|---|---|---|
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/appController.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
# Qt Components
from .qt import QtCore, QtGui, QtWidgets
# Stdlib components
import re, sys, os, cProfile, pstats, traceback
from itertools import groupby
from time import time, sleep
from collections import deque, OrderedDict
from functools import cmp_to_key
# Usd Library Components
from pxr import Usd, UsdGeom, UsdShade, UsdUtils, UsdImagingGL, Glf, Sdf, Tf, Ar
from pxr import UsdAppUtils
from pxr.UsdAppUtils.complexityArgs import RefinementComplexities
# UI Components
from ._usdviewq import Utils
from .stageView import StageView
from .mainWindowUI import Ui_MainWindow
from .primContextMenu import PrimContextMenu
from .headerContextMenu import HeaderContextMenu
from .layerStackContextMenu import LayerStackContextMenu
from .attributeViewContextMenu import AttributeViewContextMenu
from .customAttributes import (_GetCustomAttributes, CustomAttribute,
BoundingBoxAttribute, LocalToWorldXformAttribute,
ResolvedBoundMaterial)
from .primTreeWidget import PrimTreeWidget, PrimViewColumnIndex
from .primViewItem import PrimViewItem
from .variantComboBox import VariantComboBox
from .legendUtil import ToggleLegendWithBrowser
from . import prettyPrint, adjustClipping, adjustDefaultMaterial, preferences, settings
from .constantGroup import ConstantGroup
from .selectionDataModel import ALL_INSTANCES, SelectionDataModel
# Common Utilities
from .common import (UIBaseColors, UIPropertyValueSourceColors, UIFonts,
GetPropertyColor, GetPropertyTextFont,
Timer, Drange, BusyContext, DumpMallocTags,
GetValueAndDisplayString, ResetSessionVisibility,
InvisRootPrims, GetAssetCreationTime,
PropertyViewIndex, PropertyViewIcons, PropertyViewDataRoles,
RenderModes, ColorCorrectionModes, ShadedRenderModes,
PickModes, SelectionHighlightModes, CameraMaskModes,
PropTreeWidgetTypeIsRel, PrimNotFoundException,
GetRootLayerStackInfo, HasSessionVis, GetEnclosingModelPrim,
GetPrimsLoadability, ClearColors,
HighlightColors, KeyboardShortcuts)
from . import settings2
from .settings2 import StateSource
from .usdviewApi import UsdviewApi
from .rootDataModel import RootDataModel, ChangeNotice
from .viewSettingsDataModel import ViewSettingsDataModel
from . import plugin
from .pythonInterpreter import Myconsole
SETTINGS_VERSION = "1"
class HUDEntries(ConstantGroup):
# Upper HUD entries (declared in variables for abstraction)
PRIM = "Prims"
CV = "CVs"
VERT = "Verts"
FACE = "Faces"
# Lower HUD entries
PLAYBACK = "Playback"
RENDER = "Render"
GETBOUNDS = "BBox"
# Name for prims that have no type
NOTYPE = "Typeless"
class PropertyIndex(ConstantGroup):
VALUE, METADATA, LAYERSTACK, COMPOSITION = range(4)
class UIDefaults(ConstantGroup):
STAGE_VIEW_WIDTH = 604
PRIM_VIEW_WIDTH = 521
ATTRIBUTE_VIEW_WIDTH = 682
ATTRIBUTE_INSPECTOR_WIDTH = 443
TOP_HEIGHT = 538
BOTTOM_HEIGHT = 306
# Name of the Qt binding being used
QT_BINDING = QtCore.__name__.split('.')[0]
class UsdviewDataModel(RootDataModel):
def __init__(self, printTiming, settings2):
super(UsdviewDataModel, self).__init__(printTiming)
self._selectionDataModel = SelectionDataModel(self)
self._viewSettingsDataModel = ViewSettingsDataModel(self, settings2)
@property
def selection(self):
return self._selectionDataModel
@property
def viewSettings(self):
return self._viewSettingsDataModel
def _emitPrimsChanged(self, primChange, propertyChange):
# Override from base class: before alerting listening controllers,
# ensure our owned selectionDataModel is updated
if primChange == ChangeNotice.RESYNC:
self.selection.removeUnpopulatedPrims()
super(UsdviewDataModel, self)._emitPrimsChanged(primChange,
propertyChange)
class UIStateProxySource(StateSource):
"""XXX Temporary class which allows AppController to serve as two state sources.
All fields here will be moved back into AppController in the future.
"""
def __init__(self, mainWindow, parent, name):
StateSource.__init__(self, parent, name)
self._mainWindow = mainWindow
primViewColumnVisibility = self.stateProperty("primViewColumnVisibility",
default=[True, True, True, False], validator=lambda value:
len(value) == 4)
propertyViewColumnVisibility = self.stateProperty("propertyViewColumnVisibility",
default=[True, True, True], validator=lambda value: len(value) == 3)
attributeInspectorCurrentTab = self.stateProperty("attributeInspectorCurrentTab", default=PropertyIndex.VALUE)
# UI is different when --norender is used so just save the default splitter sizes.
# TODO Save the loaded state so it doesn't disappear after using --norender.
if not self._mainWindow._noRender:
stageViewWidth = self.stateProperty("stageViewWidth", default=UIDefaults.STAGE_VIEW_WIDTH)
primViewWidth = self.stateProperty("primViewWidth", default=UIDefaults.PRIM_VIEW_WIDTH)
attributeViewWidth = self.stateProperty("attributeViewWidth", default=UIDefaults.ATTRIBUTE_VIEW_WIDTH)
attributeInspectorWidth = self.stateProperty("attributeInspectorWidth", default=UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH)
topHeight = self.stateProperty("topHeight", default=UIDefaults.TOP_HEIGHT)
bottomHeight = self.stateProperty("bottomHeight", default=UIDefaults.BOTTOM_HEIGHT)
viewerMode = self.stateProperty("viewerMode", default=False)
if viewerMode:
self._mainWindow._ui.primStageSplitter.setSizes([0, 1])
self._mainWindow._ui.topBottomSplitter.setSizes([1, 0])
else:
self._mainWindow._ui.primStageSplitter.setSizes(
[primViewWidth, stageViewWidth])
self._mainWindow._ui.topBottomSplitter.setSizes(
[topHeight, bottomHeight])
self._mainWindow._ui.attribBrowserInspectorSplitter.setSizes(
[attributeViewWidth, attributeInspectorWidth])
self._mainWindow._viewerModeEscapeSizes = topHeight, bottomHeight, primViewWidth, stageViewWidth
else:
self._mainWindow._ui.primStageSplitter.setSizes(
[UIDefaults.PRIM_VIEW_WIDTH, UIDefaults.STAGE_VIEW_WIDTH])
self._mainWindow._ui.attribBrowserInspectorSplitter.setSizes(
[UIDefaults.ATTRIBUTE_VIEW_WIDTH, UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH])
self._mainWindow._ui.topBottomSplitter.setSizes(
[UIDefaults.TOP_HEIGHT, UIDefaults.BOTTOM_HEIGHT])
for i, visible in enumerate(primViewColumnVisibility):
self._mainWindow._ui.primView.setColumnHidden(i, not visible)
for i, visible in enumerate(propertyViewColumnVisibility):
self._mainWindow._ui.propertyView.setColumnHidden(i, not visible)
propertyIndex = attributeInspectorCurrentTab
if propertyIndex not in PropertyIndex:
propertyIndex = PropertyIndex.VALUE
self._mainWindow._ui.propertyInspector.setCurrentIndex(propertyIndex)
def onSaveState(self, state):
# UI is different when --norender is used so don't load the splitter sizes.
if not self._mainWindow._noRender:
primViewWidth, stageViewWidth = self._mainWindow._ui.primStageSplitter.sizes()
attributeViewWidth, attributeInspectorWidth = self._mainWindow._ui.attribBrowserInspectorSplitter.sizes()
topHeight, bottomHeight = self._mainWindow._ui.topBottomSplitter.sizes()
viewerMode = (bottomHeight == 0 and primViewWidth == 0)
# If viewer mode is active, save the escape sizes instead of the
# actual sizes. If there are no escape sizes, just save the defaults.
if viewerMode:
if self._mainWindow._viewerModeEscapeSizes is not None:
topHeight, bottomHeight, primViewWidth, stageViewWidth = self._mainWindow._viewerModeEscapeSizes
else:
primViewWidth = UIDefaults.STAGE_VIEW_WIDTH
stageViewWidth = UIDefaults.PRIM_VIEW_WIDTH
attributeViewWidth = UIDefaults.ATTRIBUTE_VIEW_WIDTH
attributeInspectorWidth = UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH
topHeight = UIDefaults.TOP_HEIGHT
bottomHeight = UIDefaults.BOTTOM_HEIGHT
state["primViewWidth"] = primViewWidth
state["stageViewWidth"] = stageViewWidth
state["attributeViewWidth"] = attributeViewWidth
state["attributeInspectorWidth"] = attributeInspectorWidth
state["topHeight"] = topHeight
state["bottomHeight"] = bottomHeight
state["viewerMode"] = viewerMode
state["primViewColumnVisibility"] = [
not self._mainWindow._ui.primView.isColumnHidden(c)
for c in range(self._mainWindow._ui.primView.columnCount())]
state["propertyViewColumnVisibility"] = [
not self._mainWindow._ui.propertyView.isColumnHidden(c)
for c in range(self._mainWindow._ui.propertyView.columnCount())]
state["attributeInspectorCurrentTab"] = self._mainWindow._ui.propertyInspector.currentIndex()
class Blocker:
"""Object which can be used to temporarily block the execution of a body of
code. This object is a context manager, and enters a 'blocked' state when
used in a 'with' statement. The 'blocked()' method can be used to find if
the Blocker is in this 'blocked' state.
For example, this is used to prevent UI code from handling signals from the
selection data model while the UI code itself modifies selection.
"""
def __init__(self):
# A count is used rather than a 'blocked' flag to allow for nested
# blocking.
self._count = 0
def __enter__(self):
"""Enter the 'blocked' state until the context is exited."""
self._count += 1
def __exit__(self, *args):
"""Exit the 'blocked' state."""
self._count -= 1
def blocked(self):
"""Returns True if in the 'blocked' state, and False otherwise."""
return self._count > 0
class MainWindow(QtWidgets.QMainWindow):
"This class exists to simplify and streamline the shutdown process."
"The application may be closed via the File menu, or by closing the main"
"window, both of which result in the same behavior."
def __init__(self, closeFunc):
super(MainWindow, self).__init__(None) # no parent widget
self._closeFunc = closeFunc
def closeEvent(self, event):
self._closeFunc()
class AppController(QtCore.QObject):
HYDRA_DISABLED_OPTION_STRING = "HydraDisabled"
###########
# Signals #
###########
@classmethod
def clearSettings(cls):
settingsPath = cls._outputBaseDirectory()
if settingsPath is None:
return None
else:
settingsPath = os.path.join(settingsPath, 'state')
if not os.path.exists(settingsPath):
print('INFO: ClearSettings requested, but there '
'were no settings currently stored.')
return None
if not os.access(settingsPath, os.W_OK):
print('ERROR: Could not remove settings file.')
return None
else:
os.remove(settingsPath)
print('INFO: Settings restored to default.')
def _configurePlugins(self):
with Timer() as t:
self._plugRegistry = plugin.loadPlugins(
self._usdviewApi, self._mainWindow)
if self._printTiming:
t.PrintTime("configure and load plugins.")
def _openSettings2(self, defaultSettings):
settingsPathDir = self._outputBaseDirectory()
if (settingsPathDir is None) or defaultSettings:
# Create an ephemeral settings object by withholding the file path.
self._settings2 = settings2.Settings(SETTINGS_VERSION)
else:
settings2Path = os.path.join(settingsPathDir, "state.json")
self._settings2 = settings2.Settings(SETTINGS_VERSION, settings2Path)
def _setStyleSheetUsingState(self):
# We use a style file that is actually a template, which we fill
# in from state, and is how we change app font sizes, for example.
# Find the resource directory
resourceDir = os.path.dirname(os.path.realpath(__file__)) + "/"
# Qt style sheet accepts only forward slashes as path separators
resourceDir = resourceDir.replace("\\", "/")
fontSize = self._dataModel.viewSettings.fontSize
baseFontSizeStr = "%spt" % str(fontSize)
# The choice of 8 for smallest smallSize is for performance reasons,
# based on the "Gotham Rounded" font used by usdviewstyle.qss . If we
# allow it to float, we get a 2-3 hundred millisecond hit in startup
# time as Qt (apparently) manufactures a suitably sized font.
# Mysteriously, we don't see this cost for larger font sizes.
smallSize = 8 if fontSize < 12 else int(round(fontSize * 0.8))
smallFontSizeStr = "%spt" % str(smallSize)
# Apply the style sheet to it
sheet = open(os.path.join(resourceDir, 'usdviewstyle.qss'), 'r')
sheetString = sheet.read() % {
'RESOURCE_DIR' : resourceDir,
'BASE_FONT_SZ' : baseFontSizeStr,
'SMALL_FONT_SZ' : smallFontSizeStr }
app = QtWidgets.QApplication.instance()
app.setStyleSheet(sheetString)
def __del__(self):
# This is needed to free Qt items before exit; Qt hits failed GTK
# assertions without it.
self._primToItemMap.clear()
def __init__(self, parserData, resolverContextFn):
QtCore.QObject.__init__(self)
with Timer() as uiOpenTimer:
self._primToItemMap = {}
self._itemsToPush = []
self._currentSpec = None
self._currentLayer = None
self._console = None
self._debugFlagsWindow = None
self._interpreter = None
self._parserData = parserData
self._noRender = parserData.noRender
self._noPlugins = parserData.noPlugins
self._unloaded = parserData.unloaded
self._resolverContextFn = resolverContextFn
self._debug = os.getenv('USDVIEW_DEBUG', False)
self._printTiming = parserData.timing or self._debug
self._lastViewContext = {}
self._paused = False
self._stopped = False
if QT_BINDING == 'PySide':
self._statusFileName = 'state'
self._deprecatedStatusFileNames = ('.usdviewrc')
else:
self._statusFileName = 'state.%s'%QT_BINDING
self._deprecatedStatusFileNames = ('state', '.usdviewrc')
self._mallocTags = parserData.mallocTagStats
self._allowViewUpdates = True
# When viewer mode is active, the panel sizes are cached so they can
# be restored later.
self._viewerModeEscapeSizes = None
self._rendererNameOpt = parserData.renderer
if self._rendererNameOpt:
if self._rendererNameOpt == \
AppController.HYDRA_DISABLED_OPTION_STRING:
os.environ['HD_ENABLED'] = '0'
else:
os.environ['HD_DEFAULT_RENDERER'] = self._rendererNameOpt
self._openSettings2(parserData.defaultSettings)
self._dataModel = UsdviewDataModel(
self._printTiming, self._settings2)
# Now that we've read in our state and applied parserData
# overrides, we can process our styleSheet... *before* we
# start listening for style-related changes.
self._setStyleSheetUsingState()
self._mainWindow = MainWindow(lambda: self._cleanAndClose())
self._ui = Ui_MainWindow()
self._ui.setupUi(self._mainWindow)
self._mainWindow.setWindowTitle(parserData.usdFile)
self._statusBar = QtWidgets.QStatusBar(self._mainWindow)
self._mainWindow.setStatusBar(self._statusBar)
# Waiting to show the mainWindow till after setting the
# statusBar saves considerable GUI configuration time.
self._mainWindow.show()
self._mainWindow.setFocus()
# Install our custom event filter. The member assignment of the
# filter is just for lifetime management
from .appEventFilter import AppEventFilter
self._filterObj = AppEventFilter(self)
QtWidgets.QApplication.instance().installEventFilter(self._filterObj)
# Setup Usdview API and optionally load plugins. We do this before
# loading the stage in case a plugin wants to modify global settings
# that affect stage loading.
self._plugRegistry = None
self._usdviewApi = UsdviewApi(self)
if not self._noPlugins:
self._configurePlugins()
# read the stage here
stage = self._openStage(
self._parserData.usdFile, self._parserData.sessionLayer,
self._parserData.populationMask)
if not stage:
sys.exit(0)
if not stage.GetPseudoRoot():
print(parserData.usdFile, 'has no prims; exiting.')
sys.exit(0)
# We instantiate a UIStateProxySource only for its side-effects
uiProxy = UIStateProxySource(self, self._settings2, "ui")
self._dataModel.stage = stage
self._primViewSelectionBlocker = Blocker()
self._propertyViewSelectionBlocker = Blocker()
self._dataModel.selection.signalPrimSelectionChanged.connect(
self._primSelectionChanged)
self._dataModel.selection.signalPropSelectionChanged.connect(
self._propSelectionChanged)
self._dataModel.selection.signalComputedPropSelectionChanged.connect(
self._propSelectionChanged)
self._initialSelectPrim = self._dataModel.stage.GetPrimAtPath(
parserData.primPath)
if not self._initialSelectPrim:
print('Could not find prim at path <%s> to select. '\
'Ignoring...' % parserData.primPath)
self._initialSelectPrim = None
try:
self._dataModel.viewSettings.complexity = parserData.complexity
except ValueError:
fallback = RefinementComplexities.LOW
sys.stderr.write(("Error: Invalid complexity '{}'. "
"Using fallback '{}' instead.\n").format(
parserData.complexity, fallback.id))
self._dataModel.viewSettings.complexity = fallback
self._hasPrimResync = False
self._timeSamples = None
self._stageView = None
self._startingPrimCamera = None
if (parserData.camera.IsAbsolutePath() or
parserData.camera.pathElementCount > 1):
self._startingPrimCameraName = None
self._startingPrimCameraPath = parserData.camera
else:
self._startingPrimCameraName = parserData.camera.pathString
self._startingPrimCameraPath = None
settingsPathDir = self._outputBaseDirectory()
if settingsPathDir is None or parserData.defaultSettings:
# Create an ephemeral settings object with a non existent filepath
self._settings = settings.Settings('', seq=None, ephemeral=True)
else:
settingsPath = os.path.join(settingsPathDir, self._statusFileName)
for deprecatedName in self._deprecatedStatusFileNames:
deprecatedSettingsPath = \
os.path.join(settingsPathDir, deprecatedName)
if (os.path.isfile(deprecatedSettingsPath) and
not os.path.isfile(settingsPath)):
warning = ('\nWARNING: The settings file at: '
+ str(deprecatedSettingsPath) + ' is deprecated.\n'
+ 'These settings are not being used, the new '
+ 'settings file will be located at: '
+ str(settingsPath) + '.\n')
print(warning)
break
self._settings = settings.Settings(settingsPath)
try:
self._settings.load()
except IOError:
# try to force out a new settings file
try:
self._settings.save()
except:
settings.EmitWarning(settingsPath)
except EOFError:
# try to force out a new settings file
try:
self._settings.save()
except:
settings.EmitWarning(settingsPath)
except:
settings.EmitWarning(settingsPath)
self._dataModel.viewSettings.signalStyleSettingsChanged.connect(
self._setStyleSheetUsingState)
self._dataModel.signalPrimsChanged.connect(
self._onPrimsChanged)
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
self._timer = QtCore.QTimer(self)
# Timeout interval in ms. We set it to 0 so it runs as fast as
# possible. In advanceFrameForPlayback we use the sleep() call
# to slow down rendering to self.framesPerSecond fps.
self._timer.setInterval(0)
self._lastFrameTime = time()
# Initialize the upper HUD info
self._upperHUDInfo = dict()
# declare dictionary keys for the fps info too
self._fpsHUDKeys = (HUDEntries.RENDER, HUDEntries.PLAYBACK)
# Initialize fps HUD with empty strings
self._fpsHUDInfo = dict(zip(self._fpsHUDKeys,
["N/A", "N/A"]))
self._startTime = self._endTime = time()
# This timer is used to coalesce the primView resizes
# in certain cases. e.g. When you
# deactivate/activate a prim.
self._primViewResizeTimer = QtCore.QTimer(self)
self._primViewResizeTimer.setInterval(0)
self._primViewResizeTimer.setSingleShot(True)
self._primViewResizeTimer.timeout.connect(self._resizePrimView)
# This timer coalesces GUI resets when the USD stage is modified or
# reloaded.
self._guiResetTimer = QtCore.QTimer(self)
self._guiResetTimer.setInterval(0)
self._guiResetTimer.setSingleShot(True)
self._guiResetTimer.timeout.connect(self._resetGUI)
# Idle timer to push off-screen data to the UI.
self._primViewUpdateTimer = QtCore.QTimer(self)
self._primViewUpdateTimer.setInterval(0)
self._primViewUpdateTimer.timeout.connect(self._updatePrimView)
# This creates the _stageView and restores state from settings file
self._resetSettings()
# This is for validating frame values input on the "Frame" line edit
validator = QtGui.QDoubleValidator(self)
self._ui.frameField.setValidator(validator)
self._ui.rangeEnd.setValidator(validator)
self._ui.rangeBegin.setValidator(validator)
stepValidator = QtGui.QDoubleValidator(self)
stepValidator.setRange(0.01, 1e7, 2)
self._ui.stepSize.setValidator(stepValidator)
# This causes the last column of the attribute view (the value)
# to be stretched to fill the available space
self._ui.propertyView.header().setStretchLastSection(True)
self._ui.propertyView.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self._ui.primView.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
# This allows ctrl and shift clicking for multi-selecting
self._ui.propertyView.setSelectionMode(
QtWidgets.QAbstractItemView.ExtendedSelection)
self._ui.propertyView.setHorizontalScrollMode(
QtWidgets.QAbstractItemView.ScrollPerPixel)
self._ui.frameSlider.setTracking(
self._dataModel.viewSettings.redrawOnScrub)
self._ui.colorGroup = QtWidgets.QActionGroup(self)
self._ui.colorGroup.setExclusive(True)
self._clearColorActions = (
self._ui.actionBlack,
self._ui.actionGrey_Dark,
self._ui.actionGrey_Light,
self._ui.actionWhite)
for action in self._clearColorActions:
self._ui.colorGroup.addAction(action)
self._ui.renderModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.renderModeActionGroup.setExclusive(True)
self._renderModeActions = (
self._ui.actionWireframe,
self._ui.actionWireframeOnSurface,
self._ui.actionSmooth_Shaded,
self._ui.actionFlat_Shaded,
self._ui.actionPoints,
self._ui.actionGeom_Only,
self._ui.actionGeom_Smooth,
self._ui.actionGeom_Flat,
self._ui.actionHidden_Surface_Wireframe)
for action in self._renderModeActions:
self._ui.renderModeActionGroup.addAction(action)
self._ui.colorCorrectionActionGroup = QtWidgets.QActionGroup(self)
self._ui.colorCorrectionActionGroup.setExclusive(True)
self._colorCorrectionActions = (
self._ui.actionNoColorCorrection,
self._ui.actionSRGBColorCorrection,
self._ui.actionOpenColorIO)
for action in self._colorCorrectionActions:
self._ui.colorCorrectionActionGroup.addAction(action)
# XXX This should be a validator in ViewSettingsDataModel.
if self._dataModel.viewSettings.renderMode not in RenderModes:
fallback = str(
self._ui.renderModeActionGroup.actions()[0].text())
print("Warning: Unknown render mode '%s', falling back to '%s'" % (
self._dataModel.viewSettings.renderMode, fallback))
self._dataModel.viewSettings.renderMode = fallback
self._ui.pickModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.pickModeActionGroup.setExclusive(True)
self._pickModeActions = (
self._ui.actionPick_Prims,
self._ui.actionPick_Models,
self._ui.actionPick_Instances,
self._ui.actionPick_Prototypes)
for action in self._pickModeActions:
self._ui.pickModeActionGroup.addAction(action)
# XXX This should be a validator in ViewSettingsDataModel.
if self._dataModel.viewSettings.pickMode not in PickModes:
fallback = str(self._ui.pickModeActionGroup.actions()[0].text())
print("Warning: Unknown pick mode '%s', falling back to '%s'" % (
self._dataModel.viewSettings.pickMode, fallback))
self._dataModel.viewSettings.pickMode = fallback
self._ui.selHighlightModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.selHighlightModeActionGroup.setExclusive(True)
self._selHighlightActions = (
self._ui.actionNever,
self._ui.actionOnly_when_paused,
self._ui.actionAlways)
for action in self._selHighlightActions:
self._ui.selHighlightModeActionGroup.addAction(action)
self._ui.highlightColorActionGroup = QtWidgets.QActionGroup(self)
self._ui.highlightColorActionGroup.setExclusive(True)
self._selHighlightColorActions = (
self._ui.actionSelYellow,
self._ui.actionSelCyan,
self._ui.actionSelWhite)
for action in self._selHighlightColorActions:
self._ui.highlightColorActionGroup.addAction(action)
self._ui.interpolationActionGroup = QtWidgets.QActionGroup(self)
self._ui.interpolationActionGroup.setExclusive(True)
for interpolationType in Usd.InterpolationType.allValues:
action = self._ui.menuInterpolation.addAction(interpolationType.displayName)
action.setCheckable(True)
action.setChecked(
self._dataModel.stage.GetInterpolationType() == interpolationType)
self._ui.interpolationActionGroup.addAction(action)
self._ui.primViewDepthGroup = QtWidgets.QActionGroup(self)
for i in range(1, 9):
action = getattr(self._ui, "actionLevel_" + str(i))
self._ui.primViewDepthGroup.addAction(action)
# setup animation objects for the primView and propertyView
self._propertyLegendAnim = QtCore.QPropertyAnimation(
self._ui.propertyLegendContainer, b"maximumHeight")
self._primLegendAnim = QtCore.QPropertyAnimation(
self._ui.primLegendContainer, b"maximumHeight")
# set the context menu policy for the prim browser and attribute
# inspector headers. This is so we can have a context menu on the
# headers that allows you to select which columns are visible.
self._ui.propertyView.header()\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self._ui.primView.header()\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for attribute browser
self._ui.propertyView\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for layer stack browser
self._ui.layerStackView\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for composition tree browser
self._ui.compositionTreeWidget\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Arc path is the most likely to need stretch.
twh = self._ui.compositionTreeWidget.header()
twh.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
twh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
twh.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
twh.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
# Set the prim view header to have a fixed size type and vis columns
nvh = self._ui.primView.header()
nvh.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
nvh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
nvh.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
nvh.resizeSection(3, 116)
nvh.setSectionResizeMode(3, QtWidgets.QHeaderView.Fixed)
pvh = self._ui.propertyView.header()
pvh.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
pvh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
pvh.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
# XXX:
# To avoid QTBUG-12850 (https://bugreports.qt.io/browse/QTBUG-12850),
# we force the horizontal scrollbar to always be visible for all
# QTableWidget widgets in use.
self._ui.primView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.propertyView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.metadataView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.layerStackView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.attributeValueEditor.setAppController(self)
self._ui.primView.InitControllers(self)
self._ui.currentPathWidget.editingFinished.connect(
self._currentPathChanged)
# XXX:
# To avoid PYSIDE-79 (https://bugreports.qt.io/browse/PYSIDE-79)
# with Qt4/PySide, we must hold the prim view's selectionModel
# in a local variable before connecting its signals.
primViewSelModel = self._ui.primView.selectionModel()
primViewSelModel.selectionChanged.connect(self._selectionChanged)
self._ui.primView.itemClicked.connect(self._itemClicked)
self._ui.primView.itemPressed.connect(self._itemPressed)
self._ui.primView.header().customContextMenuRequested.connect(
self._primViewHeaderContextMenu)
self._timer.timeout.connect(self._advanceFrameForPlayback)
self._ui.primView.customContextMenuRequested.connect(
self._primViewContextMenu)
self._ui.primView.expanded.connect(self._primViewExpanded)
self._ui.frameSlider.valueChanged.connect(self._setFrameIndex)
self._ui.frameSlider.sliderMoved.connect(self._sliderMoved)
self._ui.frameSlider.sliderReleased.connect(self._updateGUIForFrameChange)
self._ui.frameField.editingFinished.connect(self._frameStringChanged)
self._ui.rangeBegin.editingFinished.connect(self._rangeBeginChanged)
self._ui.stepSize.editingFinished.connect(self._stepSizeChanged)
self._ui.rangeEnd.editingFinished.connect(self._rangeEndChanged)
self._ui.actionFrame_Forward.triggered.connect(self._advanceFrame)
self._ui.actionFrame_Backwards.triggered.connect(self._retreatFrame)
self._ui.actionReset_View.triggered.connect(lambda: self._resetView())
self._ui.topBottomSplitter.splitterMoved.connect(self._cacheViewerModeEscapeSizes)
self._ui.primStageSplitter.splitterMoved.connect(self._cacheViewerModeEscapeSizes)
self._ui.actionToggle_Viewer_Mode.triggered.connect(
self._toggleViewerMode)
self._ui.showBBoxes.triggered.connect(self._toggleShowBBoxes)
self._ui.showAABBox.triggered.connect(self._toggleShowAABBox)
self._ui.showOBBox.triggered.connect(self._toggleShowOBBox)
self._ui.showBBoxPlayback.triggered.connect(
self._toggleShowBBoxPlayback)
self._ui.useExtentsHint.triggered.connect(self._setUseExtentsHint)
self._ui.showInterpreter.triggered.connect(self._showInterpreter)
self._ui.showDebugFlags.triggered.connect(self._showDebugFlags)
self._ui.redrawOnScrub.toggled.connect(self._redrawOptionToggled)
if self._stageView:
self._ui.actionAuto_Compute_Clipping_Planes.triggered.connect(
self._toggleAutoComputeClippingPlanes)
self._ui.actionAdjust_Clipping.triggered[bool].connect(
self._adjustClippingPlanes)
self._ui.actionAdjust_Default_Material.triggered[bool].connect(
self._adjustDefaultMaterial)
self._ui.actionPreferences.triggered[bool].connect(
self._togglePreferences)
self._ui.actionOpen.triggered.connect(self._openFile)
self._ui.actionSave_Overrides_As.triggered.connect(
self._saveOverridesAs)
self._ui.actionSave_Flattened_As.triggered.connect(
self._saveFlattenedAs)
self._ui.actionPause.triggered.connect(
self._togglePause)
self._ui.actionStop.triggered.connect(
self._toggleStop)
# Typically, a handler is registered to the 'aboutToQuit' signal
# to handle cleanup. However, with PySide2, stageView's GL context
# is destroyed by then, making it too late in the shutdown process
# to release any GL resources used by the renderer (relevant for
# Storm's GL renderer).
# To work around this, orchestrate shutdown via the main window's
# closeEvent() handler.
self._ui.actionQuit.triggered.connect(QtWidgets.QApplication.instance().closeAllWindows)
# To measure Qt shutdown time, register a handler to stop the timer.
QtWidgets.QApplication.instance().aboutToQuit.connect(self._stopQtShutdownTimer)
self._ui.actionReopen_Stage.triggered.connect(self._reopenStage)
self._ui.actionReload_All_Layers.triggered.connect(self._reloadStage)
self._ui.actionToggle_Framed_View.triggered.connect(self._toggleFramedView)
self._ui.actionAdjust_FOV.triggered.connect(self._adjustFOV)
self._ui.complexityGroup = QtWidgets.QActionGroup(self._mainWindow)
self._ui.complexityGroup.setExclusive(True)
self._complexityActions = (
self._ui.actionLow,
self._ui.actionMedium,
self._ui.actionHigh,
self._ui.actionVery_High)
for action in self._complexityActions:
self._ui.complexityGroup.addAction(action)
self._ui.complexityGroup.triggered.connect(self._changeComplexity)
self._ui.actionDisplay_Guide.triggered.connect(
self._toggleDisplayGuide)
self._ui.actionDisplay_Proxy.triggered.connect(
self._toggleDisplayProxy)
self._ui.actionDisplay_Render.triggered.connect(
self._toggleDisplayRender)
self._ui.actionDisplay_Camera_Oracles.triggered.connect(
self._toggleDisplayCameraOracles)
self._ui.actionDisplay_PrimId.triggered.connect(
self._toggleDisplayPrimId)
self._ui.actionEnable_Scene_Materials.triggered.connect(
self._toggleEnableSceneMaterials)
self._ui.actionCull_Backfaces.triggered.connect(
self._toggleCullBackfaces)
self._ui.propertyInspector.currentChanged.connect(
self._updatePropertyInspector)
self._ui.propertyView.itemSelectionChanged.connect(
self._propertyViewSelectionChanged)
self._ui.propertyView.currentItemChanged.connect(
self._propertyViewCurrentItemChanged)
self._ui.propertyView.header().customContextMenuRequested.\
connect(self._propertyViewHeaderContextMenu)
self._ui.propertyView.customContextMenuRequested.connect(
self._propertyViewContextMenu)
self._ui.layerStackView.customContextMenuRequested.connect(
self._layerStackContextMenu)
self._ui.compositionTreeWidget.customContextMenuRequested.connect(
self._compositionTreeContextMenu)
self._ui.compositionTreeWidget.currentItemChanged.connect(
self._onCompositionSelectionChanged)
self._ui.renderModeActionGroup.triggered.connect(self._changeRenderMode)
self._ui.colorCorrectionActionGroup.triggered.connect(
self._changeColorCorrection)
self._ui.pickModeActionGroup.triggered.connect(self._changePickMode)
self._ui.selHighlightModeActionGroup.triggered.connect(
self._changeSelHighlightMode)
self._ui.highlightColorActionGroup.triggered.connect(
self._changeHighlightColor)
self._ui.interpolationActionGroup.triggered.connect(
self._changeInterpolationType)
self._ui.actionAmbient_Only.triggered[bool].connect(
self._ambientOnlyClicked)
self._ui.actionDomeLight.triggered[bool].connect(self._onDomeLightClicked)
self._ui.colorGroup.triggered.connect(self._changeBgColor)
# Configuring the PrimView's Show menu. In addition to the
# "designed" menu items, we inject a PrimView HeaderContextMenu
self._ui.primViewDepthGroup.triggered.connect(self._changePrimViewDepth)
self._ui.actionExpand_All.triggered.connect(
lambda: self._expandToDepth(1000000))
self._ui.actionCollapse_All.triggered.connect(
self._ui.primView.collapseAll)
self._ui.actionShow_Inactive_Prims.triggered.connect(
self._toggleShowInactivePrims)
self._ui.actionShow_All_Master_Prims.triggered.connect(
self._toggleShowMasterPrims)
self._ui.actionShow_Undefined_Prims.triggered.connect(
self._toggleShowUndefinedPrims)
self._ui.actionShow_Abstract_Prims.triggered.connect(
self._toggleShowAbstractPrims)
# Since setting column visibility is probably not a common
# operation, it's actually good to have Columns at the end.
self._ui.menuShow.addSeparator()
self._ui.menuShow.addMenu(HeaderContextMenu(self._ui.primView))
self._ui.actionRollover_Prim_Info.triggered.connect(
self._toggleRolloverPrimInfo)
self._ui.primViewLineEdit.returnPressed.connect(
self._ui.primViewFindNext.click)
self._ui.primViewFindNext.clicked.connect(self._primViewFindNext)
self._ui.attrViewLineEdit.returnPressed.connect(
self._ui.attrViewFindNext.click)
self._ui.attrViewFindNext.clicked.connect(self._attrViewFindNext)
self._ui.primLegendQButton.clicked.connect(
self._primLegendToggleCollapse)
self._ui.propertyLegendQButton.clicked.connect(
self._propertyLegendToggleCollapse)
self._ui.playButton.clicked.connect(self._playClicked)
self._ui.actionCameraMask_Full.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_Partial.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_None.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_Outline.triggered.connect(
self._updateCameraMaskOutlineMenu)
self._ui.actionCameraMask_Color.triggered.connect(
self._pickCameraMaskColor)
self._ui.actionCameraReticles_Inside.triggered.connect(
self._updateCameraReticlesInsideMenu)
self._ui.actionCameraReticles_Outside.triggered.connect(
self._updateCameraReticlesOutsideMenu)
self._ui.actionCameraReticles_Color.triggered.connect(
self._pickCameraReticlesColor)
self._ui.actionHUD.triggered.connect(self._showHUDChanged)
self._ui.actionHUD_Info.triggered.connect(self._showHUD_InfoChanged)
self._ui.actionHUD_Complexity.triggered.connect(
self._showHUD_ComplexityChanged)
self._ui.actionHUD_Performance.triggered.connect(
self._showHUD_PerformanceChanged)
self._ui.actionHUD_GPUstats.triggered.connect(
self._showHUD_GPUstatsChanged)
self._mainWindow.addAction(self._ui.actionIncrementComplexity1)
self._mainWindow.addAction(self._ui.actionIncrementComplexity2)
self._mainWindow.addAction(self._ui.actionDecrementComplexity)
self._ui.actionIncrementComplexity1.triggered.connect(
self._incrementComplexity)
self._ui.actionIncrementComplexity2.triggered.connect(
self._incrementComplexity)
self._ui.actionDecrementComplexity.triggered.connect(
self._decrementComplexity)
self._ui.attributeValueEditor.editComplete.connect(self.editComplete)
# Edit Prim menu
self._ui.menuEdit.aboutToShow.connect(self._updateEditMenu)
self._ui.menuNavigation.aboutToShow.connect(self._updateNavigationMenu)
self._ui.actionFind_Prims.triggered.connect(
self._ui.primViewLineEdit.setFocus)
self._ui.actionSelect_Stage_Root.triggered.connect(
self.selectPseudoroot)
self._ui.actionSelect_Model_Root.triggered.connect(
self.selectEnclosingModel)
self._ui.actionSelect_Bound_Preview_Material.triggered.connect(
self.selectBoundPreviewMaterial)
self._ui.actionSelect_Bound_Full_Material.triggered.connect(
self.selectBoundFullMaterial)
self._ui.actionSelect_Preview_Binding_Relationship.triggered.connect(
self.selectPreviewBindingRel)
self._ui.actionSelect_Full_Binding_Relationship.triggered.connect(
self.selectFullBindingRel)
self._ui.actionMake_Visible.triggered.connect(self.visSelectedPrims)
# Add extra, Presto-inspired shortcut for Make Visible
self._ui.actionMake_Visible.setShortcuts(["Shift+H", "Ctrl+Shift+H"])
self._ui.actionMake_Invisible.triggered.connect(self.invisSelectedPrims)
self._ui.actionVis_Only.triggered.connect(self.visOnlySelectedPrims)
self._ui.actionRemove_Session_Visibility.triggered.connect(
self.removeVisSelectedPrims)
self._ui.actionReset_All_Session_Visibility.triggered.connect(
self.resetSessionVisibility)
self._ui.actionLoad.triggered.connect(self.loadSelectedPrims)
self._ui.actionUnload.triggered.connect(self.unloadSelectedPrims)
self._ui.actionActivate.triggered.connect(self.activateSelectedPrims)
self._ui.actionDeactivate.triggered.connect(self.deactivateSelectedPrims)
# We refresh as if all view settings changed. In the future, we
# should do more granular refreshes. This first requires more
# granular signals from ViewSettingsDataModel.
self._dataModel.viewSettings.signalSettingChanged.connect(
self._viewSettingChanged)
# Update view menu actions and submenus with initial state.
self._refreshViewMenubar()
# We manually call processEvents() here to make sure that the prim
# browser and other widgetry get drawn before we draw the first image in
# the viewer, which might take a long time.
if self._stageView:
self._stageView.setUpdatesEnabled(False)
self._mainWindow.update()
QtWidgets.QApplication.processEvents()
if self._printTiming:
uiOpenTimer.PrintTime('bring up the UI')
self._drawFirstImage()
QtWidgets.QApplication.restoreOverrideCursor()
def _drawFirstImage(self):
if self._stageView:
self._stageView.setUpdatesEnabled(True)
with BusyContext():
try:
self._resetView(self._initialSelectPrim)
except Exception:
pass
QtWidgets.QApplication.processEvents()
# configure render plugins after stageView initialized its renderer.
self._configureRendererPlugins()
self._configureColorManagement()
if self._mallocTags == 'stageAndImaging':
DumpMallocTags(self._dataModel.stage,
"stage-loading and imaging")
def statusMessage(self, msg, timeout = 0):
self._statusBar.showMessage(msg, timeout * 1000)
def editComplete(self, msg):
title = self._mainWindow.windowTitle()
if title[-1] != '*':
self._mainWindow.setWindowTitle(title + ' *')
self.statusMessage(msg, 12)
with Timer() as t:
if self._stageView:
self._stageView.updateView(resetCam=False, forceComputeBBox=True)
if self._printTiming:
t.PrintTime("'%s'" % msg)
def _openStage(self, usdFilePath, sessionFilePath, populationMaskPaths):
def _GetFormattedError(reasons=None):
err = ("Error: Unable to open stage '{0}'\n".format(usdFilePath))
if reasons:
err += "\n".join(reasons) + "\n"
return err
if not Ar.GetResolver().Resolve(usdFilePath):
sys.stderr.write(_GetFormattedError(["File not found"]))
sys.exit(1)
if self._mallocTags != 'none':
Tf.MallocTag.Initialize()
with Timer() as t:
loadSet = Usd.Stage.LoadNone if self._unloaded else Usd.Stage.LoadAll
popMask = (None if populationMaskPaths is None else
Usd.StagePopulationMask())
# Open as a layer first to make sure its a valid file format
try:
layer = Sdf.Layer.FindOrOpen(usdFilePath)
except Tf.ErrorException as e:
sys.stderr.write(_GetFormattedError(
[err.commentary.strip() for err in e.args]))
sys.exit(1)
if sessionFilePath:
try:
sessionLayer = Sdf.Layer.Find(sessionFilePath)
if sessionLayer:
sessionLayer.Reload()
else:
sessionLayer = Sdf.Layer.FindOrOpen(sessionFilePath)
except Tf.ErrorException as e:
sys.stderr.write(_GetFormattedError(
[err.commentary.strip() for err in e.args]))
sys.exit(1)
else:
sessionLayer = Sdf.Layer.CreateAnonymous()
if popMask:
for p in populationMaskPaths:
popMask.Add(p)
stage = Usd.Stage.OpenMasked(layer,
sessionLayer,
self._resolverContextFn(usdFilePath),
popMask, loadSet)
else:
stage = Usd.Stage.Open(layer,
sessionLayer,
self._resolverContextFn(usdFilePath),
loadSet)
if not stage:
sys.stderr.write(_GetFormattedError())
else:
if self._printTiming:
t.PrintTime('open stage "%s"' % usdFilePath)
stage.SetEditTarget(stage.GetSessionLayer())
if self._mallocTags == 'stage':
DumpMallocTags(stage, "stage-loading")
return stage
def _closeStage(self):
# Close the USD stage.
if self._stageView:
self._stageView.closeRenderer()
self._dataModel.stage = None
def _startQtShutdownTimer(self):
self._qtShutdownTimer = Timer()
self._qtShutdownTimer.__enter__()
def _stopQtShutdownTimer(self):
self._qtShutdownTimer.__exit__()
if self._printTiming:
self._qtShutdownTimer.PrintTime('tear down the UI')
def _setPlayShortcut(self):
self._ui.playButton.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Space))
# Non-topology dependent UI changes
def _reloadFixedUI(self, resetStageDataOnly=False):
# If animation is playing, stop it.
if self._dataModel.playing:
self._ui.playButton.click()
# frame range supplied by user
ff = self._parserData.firstframe
lf = self._parserData.lastframe
# frame range supplied by stage
stageStartTimeCode = self._dataModel.stage.GetStartTimeCode()
stageEndTimeCode = self._dataModel.stage.GetEndTimeCode()
# final range results
self.realStartTimeCode = None
self.realEndTimeCode = None
self.framesPerSecond = self._dataModel.stage.GetFramesPerSecond()
if self.framesPerSecond < 1:
err = ("Error: Invalid value for field framesPerSecond of %.2f. Using default value of 24 \n" % self.framesPerSecond)
sys.stderr.write(err)
self.statusMessage(err)
self.framesPerSecond = 24.0
if not resetStageDataOnly:
self.step = self._dataModel.stage.GetTimeCodesPerSecond() / self.framesPerSecond
self._ui.stepSize.setText(str(self.step))
# if one option is provided(lastframe or firstframe), we utilize it
if ff is not None and lf is not None:
self.realStartTimeCode = ff
self.realEndTimeCode = lf
elif ff is not None:
self.realStartTimeCode = ff
self.realEndTimeCode = stageEndTimeCode
elif lf is not None:
self.realStartTimeCode = stageStartTimeCode
self.realEndTimeCode = lf
elif self._dataModel.stage.HasAuthoredTimeCodeRange():
self.realStartTimeCode = stageStartTimeCode
self.realEndTimeCode = stageEndTimeCode
self._ui.stageBegin.setText(str(stageStartTimeCode))
self._ui.stageEnd.setText(str(stageEndTimeCode))
# Use a valid current frame supplied by user, or allow _UpdateTimeSamples
# to set the current frame.
cf = self._parserData.currentframe
if cf:
if (cf < self.realStartTimeCode or cf > self.realEndTimeCode):
sys.stderr.write('Warning: Invalid current frame specified (%s)\n' % (cf))
else:
self._dataModel.currentFrame = Usd.TimeCode(cf)
self._UpdateTimeSamples(resetStageDataOnly)
def _UpdateTimeSamples(self, resetStageDataOnly=False):
if self.realStartTimeCode is not None and self.realEndTimeCode is not None:
if self.realStartTimeCode > self.realEndTimeCode:
sys.stderr.write('Warning: Invalid frame range (%s, %s)\n'
% (self.realStartTimeCode, self.realEndTimeCode))
self._timeSamples = []
else:
self._timeSamples = Drange(self.realStartTimeCode,
self.realEndTimeCode,
self.step)
else:
self._timeSamples = []
self._geomCounts = dict()
self._hasTimeSamples = (len(self._timeSamples) > 0)
self._setPlaybackAvailability() # this sets self._playbackAvailable
if self._hasTimeSamples:
self._ui.rangeBegin.setText(str(self._timeSamples[0]))
self._ui.rangeEnd.setText(str(self._timeSamples[-1]))
if ( self._dataModel.currentFrame.IsDefault() or
self._dataModel.currentFrame < self._timeSamples[0] ):
self._dataModel.currentFrame = Usd.TimeCode(self._timeSamples[0])
if self._dataModel.currentFrame > self._timeSamples[-1]:
self._dataModel.currentFrame = Usd.TimeCode(self._timeSamples[-1])
else:
self._dataModel.currentFrame = Usd.TimeCode(0.0)
if not resetStageDataOnly:
self._ui.frameField.setText(
str(self._dataModel.currentFrame.GetValue()))
if self._playbackAvailable:
if not resetStageDataOnly:
self._ui.frameSlider.setRange(0, len(self._timeSamples) - 1)
self._ui.frameSlider.setValue(0)
self._setPlayShortcut()
self._ui.playButton.setCheckable(True)
# Ensure the play button state respects the current playback state
self._ui.playButton.setChecked(self._dataModel.playing)
def _clearCaches(self, preserveCamera=False):
"""Clears value and computation caches maintained by the controller.
Does NOT initiate any GUI updates"""
self._geomCounts = dict()
self._dataModel._clearCaches()
self._refreshCameraListAndMenu(preserveCurrCamera = preserveCamera)
@staticmethod
def GetRendererOptionChoices():
ids = UsdImagingGL.Engine.GetRendererPlugins()
choices = []
if ids:
choices = [UsdImagingGL.Engine.GetRendererDisplayName(x)
for x in ids]
choices.append(AppController.HYDRA_DISABLED_OPTION_STRING)
else:
choices = [AppController.HYDRA_DISABLED_OPTION_STRING]
return choices
# Render plugin support
def _rendererPluginChanged(self, plugin):
if self._stageView:
if not self._stageView.SetRendererPlugin(plugin):
# If SetRendererPlugin failed, we need to reset the check mark
# to whatever the currently loaded renderer is.
for action in self._ui.rendererPluginActionGroup.actions():
if action.text() == self._stageView.rendererDisplayName:
action.setChecked(True)
break
# Then display an error message to let the user know something
# went wrong, and disable the menu item so it can't be selected
# again.
for action in self._ui.rendererPluginActionGroup.actions():
if action.pluginType == plugin:
self.statusMessage(
'Renderer not supported: %s' % action.text())
action.setText(action.text() + " (unsupported)")
action.setDisabled(True)
break
else:
# Refresh the AOV menu, settings menu, and pause menu item
self._configureRendererAovs()
self._configureRendererSettings()
self._configurePauseAction()
self._configureStopAction()
def _configureRendererPlugins(self):
if self._stageView:
self._ui.rendererPluginActionGroup = QtWidgets.QActionGroup(self)
self._ui.rendererPluginActionGroup.setExclusive(True)
pluginTypes = self._stageView.GetRendererPlugins()
for pluginType in pluginTypes:
name = self._stageView.GetRendererDisplayName(pluginType)
action = self._ui.menuRendererPlugin.addAction(name)
action.setCheckable(True)
action.pluginType = pluginType
self._ui.rendererPluginActionGroup.addAction(action)
action.triggered[bool].connect(lambda _, pluginType=pluginType:
self._rendererPluginChanged(pluginType))
# Now set the checked box on the current renderer (it should
# have been set by now).
currentRendererId = self._stageView.GetCurrentRendererId()
foundPlugin = False
for action in self._ui.rendererPluginActionGroup.actions():
if action.pluginType == currentRendererId:
action.setChecked(True)
foundPlugin = True
break
# Disable the menu if no plugins were found
self._ui.menuRendererPlugin.setEnabled(foundPlugin)
# Refresh the AOV menu, settings menu, and pause menu item
self._configureRendererAovs()
self._configureRendererSettings()
self._configurePauseAction()
self._configureStopAction()
# Renderer AOV support
def _rendererAovChanged(self, aov):
if self._stageView:
self._stageView.SetRendererAov(aov)
self._ui.aovOtherAction.setText("Other...")
def _configureRendererAovs(self):
if self._stageView:
self._ui.rendererAovActionGroup = QtWidgets.QActionGroup(self)
self._ui.rendererAovActionGroup.setExclusive(True)
self._ui.menuRendererAovs.clear()
aovs = self._stageView.GetRendererAovs()
for aov in aovs:
action = self._ui.menuRendererAovs.addAction(aov)
action.setCheckable(True)
if (aov == "color"):
action.setChecked(True)
action.aov = aov
self._ui.rendererAovActionGroup.addAction(action)
action.triggered[bool].connect(lambda _, aov=aov:
self._rendererAovChanged(aov))
self._ui.menuRendererAovs.addSeparator()
self._ui.aovOtherAction = self._ui.menuRendererAovs.addAction("Other...")
self._ui.aovOtherAction.setCheckable(True)
self._ui.aovOtherAction.aov = "Other"
self._ui.rendererAovActionGroup.addAction(self._ui.aovOtherAction)
self._ui.aovOtherAction.triggered[bool].connect(self._otherAov)
self._ui.menuRendererAovs.setEnabled(len(aovs) != 0)
def _otherAov(self):
# If we've already selected "Other..." as an AOV, populate the current
# AOV name.
initial = ""
if self._ui.aovOtherAction.text() != "Other...":
initial = self._stageView.rendererAovName
aov, ok = QtWidgets.QInputDialog.getText(self._mainWindow, "Other AOVs",
"Enter the aov name. Visualize primvars with \"primvars:name\".",
QtWidgets.QLineEdit.Normal, initial)
if (ok and len(aov) > 0):
self._rendererAovChanged(str(aov))
self._ui.aovOtherAction.setText("Other (%r)..." % str(aov))
else:
for action in self._ui.rendererAovActionGroup.actions():
if action.text() == self._stageView.rendererAovName:
action.setChecked(True)
break
def _rendererSettingsFlagChanged(self, action):
if self._stageView:
self._stageView.SetRendererSetting(action.key, action.isChecked())
def _configureRendererSettings(self):
if self._stageView:
self._ui.menuRendererSettings.clear()
self._ui.settingsFlagActions = []
settings = self._stageView.GetRendererSettingsList()
moreSettings = False
for setting in settings:
if setting.type != UsdImagingGL.RendererSettingType.FLAG:
moreSettings = True
continue
action = self._ui.menuRendererSettings.addAction(setting.name)
action.setCheckable(True)
action.key = str(setting.key)
action.setChecked(self._stageView.GetRendererSetting(setting.key))
action.triggered[bool].connect(lambda _, action=action:
self._rendererSettingsFlagChanged(action))
self._ui.settingsFlagActions.append(action)
if moreSettings:
self._ui.menuRendererSettings.addSeparator()
self._ui.settingsMoreAction = self._ui.menuRendererSettings.addAction("More...")
self._ui.settingsMoreAction.setCheckable(False)
self._ui.settingsMoreAction.triggered[bool].connect(self._moreRendererSettings)
self._ui.menuRendererSettings.setEnabled(len(settings) != 0)
# Close the old "More..." dialog if it's still open
if hasattr(self._ui, 'settingsMoreDialog'):
self._ui.settingsMoreDialog.reject()
def _moreRendererSettings(self):
# Recreate the settings dialog
self._ui.settingsMoreDialog = QtWidgets.QDialog(self._mainWindow)
self._ui.settingsMoreDialog.setWindowTitle("Hydra Settings")
self._ui.settingsMoreWidgets = []
layout = QtWidgets.QVBoxLayout()
# Add settings
groupBox = QtWidgets.QGroupBox()
formLayout = QtWidgets.QFormLayout()
groupBox.setLayout(formLayout)
layout.addWidget(groupBox)
formLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
formLayout.setFormAlignment(QtCore.Qt.AlignRight)
settings = self._stageView.GetRendererSettingsList()
for setting in settings:
if setting.type == UsdImagingGL.RendererSettingType.FLAG:
checkBox = QtWidgets.QCheckBox()
checkBox.setChecked(self._stageView.GetRendererSetting(setting.key))
checkBox.key = str(setting.key)
checkBox.defValue = setting.defValue
formLayout.addRow(setting.name, checkBox)
self._ui.settingsMoreWidgets.append(checkBox)
if setting.type == UsdImagingGL.RendererSettingType.INT:
spinBox = QtWidgets.QSpinBox()
spinBox.setMinimum(-2 ** 31)
spinBox.setMaximum(2 ** 31 - 1)
spinBox.setValue(self._stageView.GetRendererSetting(setting.key))
spinBox.key = str(setting.key)
spinBox.defValue = setting.defValue
formLayout.addRow(setting.name, spinBox)
self._ui.settingsMoreWidgets.append(spinBox)
if setting.type == UsdImagingGL.RendererSettingType.FLOAT:
spinBox = QtWidgets.QDoubleSpinBox()
spinBox.setDecimals(10)
spinBox.setMinimum(-2 ** 31)
spinBox.setMaximum(2 ** 31 - 1)
spinBox.setValue(self._stageView.GetRendererSetting(setting.key))
spinBox.key = str(setting.key)
spinBox.defValue = setting.defValue
formLayout.addRow(setting.name, spinBox)
self._ui.settingsMoreWidgets.append(spinBox)
if setting.type == UsdImagingGL.RendererSettingType.STRING:
lineEdit = QtWidgets.QLineEdit()
lineEdit.setText(self._stageView.GetRendererSetting(setting.key))
lineEdit.key = str(setting.key)
lineEdit.defValue = setting.defValue
formLayout.addRow(setting.name, lineEdit)
self._ui.settingsMoreWidgets.append(lineEdit)
# Add buttons
buttonBox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok |
QtWidgets.QDialogButtonBox.Cancel |
QtWidgets.QDialogButtonBox.RestoreDefaults |
QtWidgets.QDialogButtonBox.Apply)
layout.addWidget(buttonBox)
buttonBox.rejected.connect(self._ui.settingsMoreDialog.reject)
buttonBox.accepted.connect(self._ui.settingsMoreDialog.accept)
self._ui.settingsMoreDialog.accepted.connect(self._applyMoreRendererSettings)
defaultButton = buttonBox.button(QtWidgets.QDialogButtonBox.RestoreDefaults)
defaultButton.clicked.connect(self._resetMoreRendererSettings)
applyButton = buttonBox.button(QtWidgets.QDialogButtonBox.Apply)
applyButton.clicked.connect(self._applyMoreRendererSettings)
self._ui.settingsMoreDialog.setLayout(layout)
self._ui.settingsMoreDialog.show()
def _applyMoreRendererSettings(self):
for widget in self._ui.settingsMoreWidgets:
if isinstance(widget, QtWidgets.QCheckBox):
self._stageView.SetRendererSetting(widget.key, widget.isChecked())
if isinstance(widget, QtWidgets.QSpinBox):
self._stageView.SetRendererSetting(widget.key, widget.value())
if isinstance(widget, QtWidgets.QDoubleSpinBox):
self._stageView.SetRendererSetting(widget.key, widget.value())
if isinstance(widget, QtWidgets.QLineEdit):
self._stageView.SetRendererSetting(widget.key, widget.text())
for action in self._ui.settingsFlagActions:
action.setChecked(self._stageView.GetRendererSetting(action.key))
def _resetMoreRendererSettings(self):
for widget in self._ui.settingsMoreWidgets:
if isinstance(widget, QtWidgets.QCheckBox):
widget.setChecked(widget.defValue)
if isinstance(widget, QtWidgets.QSpinBox):
widget.setValue(widget.defValue)
if isinstance(widget, QtWidgets.QDoubleSpinBox):
widget.setValue(widget.defValue)
if isinstance(widget, QtWidgets.QLineEdit):
widget.setText(widget.defValue)
def _configurePauseAction(self):
if self._stageView:
# This is called when the user picks a new renderer, which
# always starts in an unpaused state.
self._paused = False
self._ui.actionPause.setEnabled(
self._stageView.IsPauseRendererSupported())
self._ui.actionPause.setChecked(self._paused and
self._stageView.IsPauseRendererSupported())
def _configureStopAction(self):
if self._stageView:
# This is called when the user picks a new renderer, which
# always starts in an unstopped state.
self._stopped = False
self._ui.actionStop.setEnabled(
self._stageView.IsStopRendererSupported())
self._ui.actionStop.setChecked(self._stopped and
self._stageView.IsStopRendererSupported())
def _configureColorManagement(self):
enableMenu = (not self._noRender and
UsdImagingGL.Engine.IsColorCorrectionCapable())
self._ui.menuColorCorrection.setEnabled(enableMenu)
# Topology-dependent UI changes
def _reloadVaryingUI(self):
self._clearCaches()
if self._debug:
cProfile.runctx('self._resetPrimView(restoreSelection=False)', globals(), locals(), 'resetPrimView')
p = pstats.Stats('resetPrimView')
p.strip_dirs().sort_stats(-1).print_stats()
else:
self._resetPrimView(restoreSelection=False)
if not self._stageView:
# The second child is self._ui.glFrame, which disappears if
# its size is set to zero.
if self._noRender:
# remove glFrame from the ui
self._ui.glFrame.setParent(None)
# move the attributeBrowser into the primSplitter instead
self._ui.primStageSplitter.addWidget(self._ui.attributeBrowserFrame)
else:
self._stageView = StageView(parent=self._mainWindow,
dataModel=self._dataModel,
printTiming=self._printTiming)
self._stageView.fpsHUDInfo = self._fpsHUDInfo
self._stageView.fpsHUDKeys = self._fpsHUDKeys
self._stageView.signalPrimSelected.connect(self.onPrimSelected)
self._stageView.signalPrimRollover.connect(self.onRollover)
self._stageView.signalMouseDrag.connect(self.onStageViewMouseDrag)
self._stageView.signalErrorMessage.connect(self.statusMessage)
layout = QtWidgets.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self._ui.glFrame.setLayout(layout)
layout.addWidget(self._stageView)
self._primSearchResults = deque([])
self._attrSearchResults = deque([])
self._primSearchString = ""
self._attrSearchString = ""
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
if self._stageView:
self._stageView.setFocus(QtCore.Qt.TabFocusReason)
self._stageView.rolloverPicking = self._dataModel.viewSettings.rolloverPrimInfo
def _scheduleResizePrimView(self):
""" Schedules a resize of the primView widget.
This will call _resizePrimView when the timer expires
(uses timer coalescing to prevent redundant resizes from occurring).
"""
self._primViewResizeTimer.start(0)
def _resizePrimView(self):
""" Used to coalesce excess calls to resizeColumnToContents.
"""
self._ui.primView.resizeColumnToContents(0)
# Retrieve the list of prims currently expanded in the primTreeWidget
def _getExpandedPrimViewPrims(self):
rootItem = self._ui.primView.invisibleRootItem()
expandedItems = list()
# recursive function for adding all expanded items to expandedItems
def findExpanded(item):
if item.isExpanded():
expandedItems.append(item)
for i in range(item.childCount()):
findExpanded(item.child(i))
findExpanded(rootItem)
expandedPrims = [item.prim for item in expandedItems]
return expandedPrims
# This appears to be "reasonably" performant in normal sized pose caches.
# If it turns out to be too slow, or if we want to do a better job of
# preserving the view the user currently has, we could look into ways of
# reconstructing just the prim tree under the "changed" prim(s). The
# (far and away) faster solution would be to implement our own TreeView
# and model in C++.
def _resetPrimView(self, restoreSelection=True):
expandedPrims = self._getExpandedPrimViewPrims()
with Timer() as t, BusyContext():
startingDepth = 3
self._computeDisplayPredicate()
with self._primViewSelectionBlocker:
self._ui.primView.setUpdatesEnabled(False)
self._ui.primView.clear()
self._primToItemMap.clear()
self._itemsToPush = []
# force new search since we are blowing away the primViewItems
# that may be cached in _primSearchResults
self._primSearchResults = []
self._populateRoots()
# it's confusing to see timing for expand followed by reset with
# the times being similar (esp when they are large)
if not expandedPrims:
self._expandToDepth(startingDepth, suppressTiming=True)
if restoreSelection:
self._refreshPrimViewSelection(expandedPrims)
self._ui.primView.setUpdatesEnabled(True)
self._refreshCameraListAndMenu(preserveCurrCamera = True)
if self._printTiming:
t.PrintTime("reset Prim Browser to depth %d" % startingDepth)
def _resetGUI(self):
"""Perform a full refresh/resync of all GUI contents. This should be
called whenever the USD stage is modified, and assumes that all data
previously fetched from the stage is invalid. In the future, more
granular updates will be supported by listening to UsdNotice objects on
the active stage.
If a prim resync is needed then we fully update the prim view,
otherwise can just do a simplified update to the prim view.
"""
with BusyContext():
if self._hasPrimResync:
self._resetPrimView()
self._hasPrimResync = False
else:
self._resetPrimViewVis(selItemsOnly=False)
self._updatePropertyView()
self._populatePropertyInspector()
self._updateMetadataView()
self._updateLayerStackView()
self._updateCompositionView()
if self._stageView:
self._stageView.update()
def updateGUI(self):
"""Will schedule a full refresh/resync of the GUI contents.
Prefer this to calling _resetGUI() directly, since it will
coalesce multiple calls to this method in to a single refresh.
"""
self._guiResetTimer.start()
def _resetPrimViewVis(self, selItemsOnly=True,
authoredVisHasChanged=True):
"""Updates browser rows' Vis columns... can update just selected
items (and their descendants and ancestors), or all items in the
primView. When authoredVisHasChanged is True, we force each item
to discard any value caches it may be holding onto."""
with Timer() as t:
self._ui.primView.setUpdatesEnabled(False)
rootsToProcess = self.getSelectedItems() if selItemsOnly else \
[self._ui.primView.invisibleRootItem()]
for item in rootsToProcess:
PrimViewItem.propagateVis(item, authoredVisHasChanged)
self._ui.primView.setUpdatesEnabled(True)
if self._printTiming:
t.PrintTime("update vis column")
def _updatePrimView(self):
# Process some more prim view items.
n = min(100, len(self._itemsToPush))
if n:
items = self._itemsToPush[-n:]
del self._itemsToPush[-n:]
for item in items:
item.push()
else:
self._primViewUpdateTimer.stop()
# Option windows ==========================================================
def _setComplexity(self, complexity):
"""Set the complexity and update the UI."""
self._dataModel.viewSettings.complexity = complexity
def _incrementComplexity(self):
"""Jump up to the next level of complexity."""
self._setComplexity(RefinementComplexities.next(
self._dataModel.viewSettings.complexity))
def _decrementComplexity(self):
"""Jump back to the previous level of complexity."""
self._setComplexity(RefinementComplexities.prev(
self._dataModel.viewSettings.complexity))
def _changeComplexity(self, action):
"""Update the complexity from a selected QAction."""
self._setComplexity(RefinementComplexities.fromName(action.text()))
def _adjustFOV(self):
fov = QtWidgets.QInputDialog.getDouble(self._mainWindow, "Adjust FOV",
"Enter a value between 0 and 180", self._dataModel.viewSettings.freeCameraFOV, 0, 180)
if (fov[1]):
self._dataModel.viewSettings.freeCameraFOV = fov[0]
def _adjustClippingPlanes(self, checked):
# Eventually, this will not be accessible when _stageView is None.
# Until then, silently ignore.
if self._stageView:
if (checked):
self._adjustClippingDlg = adjustClipping.AdjustClipping(self._mainWindow,
self._stageView)
self._adjustClippingDlg.finished.connect(
lambda status : self._ui.actionAdjust_Clipping.setChecked(False))
self._adjustClippingDlg.show()
else:
self._adjustClippingDlg.close()
def _adjustDefaultMaterial(self, checked):
if (checked):
self._adjustDefaultMaterialDlg = adjustDefaultMaterial.AdjustDefaultMaterial(
self._mainWindow, self._dataModel.viewSettings)
self._adjustDefaultMaterialDlg.finished.connect(lambda status :
self._ui.actionAdjust_Default_Material.setChecked(False))
self._adjustDefaultMaterialDlg.show()
else:
self._adjustDefaultMaterialDlg.close()
def _togglePreferences(self, checked):
if (checked):
self._preferencesDlg = preferences.Preferences(
self._mainWindow, self._dataModel)
self._preferencesDlg.finished.connect(lambda status :
self._ui.actionPreferences.setChecked(False))
self._preferencesDlg.show()
else:
self._preferencesDlg.close()
def _redrawOptionToggled(self, checked):
self._dataModel.viewSettings.redrawOnScrub = checked
self._ui.frameSlider.setTracking(
self._dataModel.viewSettings.redrawOnScrub)
# Frame-by-frame/Playback functionality ===================================
def _setPlaybackAvailability(self, enabled = True):
isEnabled = len(self._timeSamples) > 1 and enabled
self._playbackAvailable = isEnabled
#If playback is disabled, but the animation is playing...
if not isEnabled and self._dataModel.playing:
self._ui.playButton.click()
self._ui.playButton.setEnabled(isEnabled)
self._ui.frameSlider.setEnabled(isEnabled)
self._ui.actionFrame_Forward.setEnabled(isEnabled)
self._ui.actionFrame_Backwards.setEnabled(isEnabled)
self._ui.frameField.setEnabled(isEnabled
if self._hasTimeSamples else False)
self._ui.frameLabel.setEnabled(isEnabled
if self._hasTimeSamples else False)
self._ui.stageBegin.setEnabled(isEnabled)
self._ui.stageEnd.setEnabled(isEnabled)
self._ui.redrawOnScrub.setEnabled(isEnabled)
self._ui.stepSizeLabel.setEnabled(isEnabled)
self._ui.stepSize.setEnabled(isEnabled)
def _playClicked(self):
if self._ui.playButton.isChecked():
# Enable tracking whilst playing
self._ui.frameSlider.setTracking(True)
# Start playback.
self._dataModel.playing = True
self._ui.playButton.setText("Stop")
# setText() causes the shortcut to be reset to whatever
# Qt thinks it should be based on the text. We know better.
self._setPlayShortcut()
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "..."
self._timer.start()
# For performance, don't update the prim tree view while playing.
self._primViewUpdateTimer.stop()
self._playbackIndex = 0
else:
self._ui.frameSlider.setTracking(self._ui.redrawOnScrub.isChecked())
# Stop playback.
self._dataModel.playing = False
self._ui.playButton.setText("Play")
# setText() causes the shortcut to be reset to whatever
# Qt thinks it should be based on the text. We know better.
self._setPlayShortcut()
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "N/A"
self._timer.stop()
self._primViewUpdateTimer.start()
self._updateOnFrameChange()
def _advanceFrameForPlayback(self):
sleep(max(0, 1. / self.framesPerSecond - (time() - self._lastFrameTime)))
self._lastFrameTime = time()
if self._playbackIndex == 0:
self._startTime = time()
if self._playbackIndex == 4:
self._endTime = time()
delta = (self._endTime - self._startTime)/4.
ms = delta * 1000.
fps = 1. / delta
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "%.2f ms (%.2f FPS)" % (ms, fps)
self._playbackIndex = (self._playbackIndex + 1) % 5
self._advanceFrame()
def _advanceFrame(self):
if self._playbackAvailable:
value = self._ui.frameSlider.value() + 1
if value > self._ui.frameSlider.maximum():
value = self._ui.frameSlider.minimum()
self._ui.frameSlider.setValue(value)
def _retreatFrame(self):
if self._playbackAvailable:
value = self._ui.frameSlider.value() - 1
if value < self._ui.frameSlider.minimum():
value = self._ui.frameSlider.maximum()
self._ui.frameSlider.setValue(value)
def _findClosestFrameIndex(self, timeSample):
"""Find the closest frame index for the given `timeSample`.
Args:
timeSample (float): A time sample value.
Returns:
int: The closest matching frame index or 0 if one cannot be
found.
"""
closestIndex = int(round((timeSample - self._timeSamples[0]) / self.step))
# Bounds checking
# 0 <= closestIndex <= number of time samples - 1
closestIndex = max(0, closestIndex)
closestIndex = min(len(self._timeSamples) - 1, closestIndex)
return closestIndex
def _rangeBeginChanged(self):
value = float(self._ui.rangeBegin.text())
if value != self.realStartTimeCode:
self.realStartTimeCode = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _stepSizeChanged(self):
value = float(self._ui.stepSize.text())
if value != self.step:
self.step = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _rangeEndChanged(self):
value = float(self._ui.rangeEnd.text())
if value != self.realEndTimeCode:
self.realEndTimeCode = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _frameStringChanged(self):
value = float(self._ui.frameField.text())
self.setFrame(value)
def _sliderMoved(self, frameIndex):
"""Slot called when the frame slider is moved by a user.
Args:
frameIndex (int): The new frame index value.
"""
# If redraw on scrub is disabled, ensure we still update the
# frame field.
if not self._ui.redrawOnScrub.isChecked():
self.setFrameField(self._timeSamples[frameIndex])
def setFrameField(self, frame):
"""Set the frame field to the given `frame`.
Args:
frame (str|int|float): The new frame value.
"""
frame = round(float(frame), ndigits=2)
self._ui.frameField.setText(str(frame))
# Prim/Attribute search functionality =====================================
def _findPrims(self, pattern, useRegex=True):
"""Search the Usd Stage for matching prims
"""
# If pattern doesn't contain regexp special chars, drop
# down to simple search, as it's faster
if useRegex and re.match("^[0-9_A-Za-z]+$", pattern):
useRegex = False
if useRegex:
isMatch = re.compile(pattern, re.IGNORECASE).search
else:
pattern = pattern.lower()
isMatch = lambda x: pattern in x.lower()
matches = [prim.GetPath() for prim
in Usd.PrimRange.Stage(self._dataModel.stage,
self._displayPredicate)
if isMatch(prim.GetName())]
if self._dataModel.viewSettings.showAllMasterPrims:
for master in self._dataModel.stage.GetMasters():
matches += [prim.GetPath() for prim
in Usd.PrimRange(master, self._displayPredicate)
if isMatch(prim.GetName())]
return matches
def _primViewFindNext(self):
if (self._primSearchString == self._ui.primViewLineEdit.text() and
len(self._primSearchResults) > 0 and
self._lastPrimSearched == self._dataModel.selection.getFocusPrim()):
# Go to the next result of the currently ongoing search.
# First time through, we'll be converting from SdfPaths
# to items (see the append() below)
nextResult = self._primSearchResults.popleft()
if isinstance(nextResult, Sdf.Path):
nextResult = self._getItemAtPath(nextResult)
if nextResult:
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
self._dataModel.selection.addPrim(nextResult.prim)
self._primSearchResults.append(nextResult)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
self._ui.primView.setCurrentItem(nextResult)
# The path is effectively pruned if we couldn't map the
# path to an item
else:
# Begin a new search
with Timer() as t:
self._primSearchString = self._ui.primViewLineEdit.text()
self._primSearchResults = self._findPrims(str(self._ui.primViewLineEdit.text()))
self._primSearchResults = deque(self._primSearchResults)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
selectedPrim = self._dataModel.selection.getFocusPrim()
# reorders search results so results are centered on selected
# prim. this could be optimized, but a binary search with a
# custom operator for the result closest to and after the
# selected prim is messier to implement.
if (selectedPrim != None and
selectedPrim != self._dataModel.stage.GetPseudoRoot() and
len(self._primSearchResults) > 0):
for i in range(len(self._primSearchResults)):
searchResultPath = self._primSearchResults[0]
selectedPath = selectedPrim.GetPath()
if self._comparePaths(searchResultPath, selectedPath) < 1:
self._primSearchResults.rotate(-1)
else:
break
if (len(self._primSearchResults) > 0):
self._primViewFindNext()
if self._printTiming:
t.PrintTime("match '%s' (%d matches)" %
(self._primSearchString,
len(self._primSearchResults)))
# returns -1 if path1 appears before path2 in flattened tree
# returns 0 if path1 and path2 are equal
# returns 1 if path2 appears before path1 in flattened tree
def _comparePaths(self, path1, path2):
# function for removing a certain number of elements from a path
def stripPath(path, numElements):
strippedPath = path
for i in range(numElements):
strippedPath = strippedPath.GetParentPath()
return strippedPath
lca = path1.GetCommonPrefix(path2)
path1NumElements = path1.pathElementCount
path2NumElements = path2.pathElementCount
lcaNumElements = lca.pathElementCount
if path1 == path2:
return 0
if lca == path1:
return -1
if lca == path2:
return 1
path1Stripped = stripPath(path1, path1NumElements - (lcaNumElements + 1))
path2Stripped = stripPath(path2, path2NumElements - (lcaNumElements + 1))
lcaChildrenPrims = self._getFilteredChildren(self._dataModel.stage.GetPrimAtPath(lca))
lcaChildrenPaths = [prim.GetPath() for prim in lcaChildrenPrims]
indexPath1 = lcaChildrenPaths.index(path1Stripped)
indexPath2 = lcaChildrenPaths.index(path2Stripped)
if (indexPath1 < indexPath2):
return -1
if (indexPath1 > indexPath2):
return 1
else:
return 0
def _primLegendToggleCollapse(self):
ToggleLegendWithBrowser(self._ui.primLegendContainer,
self._ui.primLegendQButton,
self._primLegendAnim)
def _propertyLegendToggleCollapse(self):
ToggleLegendWithBrowser(self._ui.propertyLegendContainer,
self._ui.propertyLegendQButton,
self._propertyLegendAnim)
def _attrViewFindNext(self):
if (self._attrSearchString == self._ui.attrViewLineEdit.text() and
len(self._attrSearchResults) > 0 and
self._lastPrimSearched == self._dataModel.selection.getFocusPrim()):
# Go to the next result of the currently ongoing search
nextResult = self._attrSearchResults.popleft()
itemName = str(nextResult.text(PropertyViewIndex.NAME))
selectedProp = self._propertiesDict[itemName]
if isinstance(selectedProp, CustomAttribute):
self._dataModel.selection.clearProps()
self._dataModel.selection.setComputedProp(selectedProp)
else:
self._dataModel.selection.setProp(selectedProp)
self._dataModel.selection.clearComputedProps()
self._ui.propertyView.scrollToItem(nextResult)
self._attrSearchResults.append(nextResult)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
self._ui.attributeValueEditor.populate(
self._dataModel.selection.getFocusPrim().GetPath(), itemName)
self._updateMetadataView(self._getSelectedObject())
self._updateLayerStackView(self._getSelectedObject())
else:
# Begin a new search
self._attrSearchString = self._ui.attrViewLineEdit.text()
attrSearchItems = self._ui.propertyView.findItems(
self._ui.attrViewLineEdit.text(),
QtCore.Qt.MatchRegExp,
PropertyViewIndex.NAME)
# Now just search for the string itself
otherSearch = self._ui.propertyView.findItems(
self._ui.attrViewLineEdit.text(),
QtCore.Qt.MatchContains,
PropertyViewIndex.NAME)
combinedItems = attrSearchItems + otherSearch
# We find properties first, then connections/targets
# Based on the default recursive match finding in Qt.
combinedItems.sort()
self._attrSearchResults = deque(combinedItems)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
if (len(self._attrSearchResults) > 0):
self._attrViewFindNext()
@classmethod
def _outputBaseDirectory(cls):
if os.getenv('PXR_USDVIEW_SUPPRESS_STATE_SAVING', "0") == "1":
return None
homeDirRoot = os.getenv('HOME') or os.path.expanduser('~')
baseDir = os.path.join(homeDirRoot, '.usdview')
try:
if not os.path.exists(baseDir):
os.makedirs(baseDir)
return baseDir
except OSError:
sys.stderr.write("ERROR: Unable to create base directory '%s' "
"for settings file, settings will not be saved.\n"
% baseDir)
return None
# View adjustment functionality ===========================================
def _storeAndReturnViewState(self):
lastView = self._lastViewContext
self._lastViewContext = self._stageView.copyViewState()
return lastView
def _frameSelection(self):
if self._stageView:
# Save all the pertinent attribute values (for _toggleFramedView)
self._storeAndReturnViewState() # ignore return val - we're stomping it
self._stageView.updateView(True, True) # compute bbox on frame selection
def _toggleFramedView(self):
if self._stageView:
self._stageView.restoreViewState(self._storeAndReturnViewState())
def _resetSettings(self):
"""Reloads the UI and Sets up the initial settings for the
_stageView object created in _reloadVaryingUI"""
# Seems like a good time to clear the texture registry
Glf.TextureRegistry.Reset()
# RELOAD fixed and varying UI
self._reloadFixedUI()
self._reloadVaryingUI()
if self._stageView:
self._stageView.update()
self._ui.actionFreeCam._prim = None
self._ui.actionFreeCam.triggered.connect(
lambda : self._cameraSelectionChanged(None))
if self._stageView:
self._stageView.signalSwitchedToFreeCam.connect(
lambda : self._cameraSelectionChanged(None))
self._refreshCameraListAndMenu(preserveCurrCamera = False)
def _updateForStageChanges(self, hasPrimResync=True):
"""Assuming there have been authoring changes to the already-loaded
stage, make the minimal updates to the UI required to maintain a
consistent state. This may still be over-zealous until we know
what actually changed, but we should be able to preserve camera and
playback positions (unless viewing through a stage camera that no
longer exists"""
self._hasPrimResync = hasPrimResync or self._hasPrimResync
self._clearCaches(preserveCamera=True)
# Update the UIs (it gets all of them) and StageView on a timer
self.updateGUI()
def _cacheViewerModeEscapeSizes(self, pos=None, index=None):
topHeight, bottomHeight = self._ui.topBottomSplitter.sizes()
primViewWidth, stageViewWidth = self._ui.primStageSplitter.sizes()
if bottomHeight > 0 or primViewWidth > 0:
self._viewerModeEscapeSizes = topHeight, bottomHeight, primViewWidth, stageViewWidth
else:
self._viewerModeEscapeSizes = None
def _toggleViewerMode(self):
topHeight, bottomHeight = self._ui.topBottomSplitter.sizes()
primViewWidth, stageViewWidth = self._ui.primStageSplitter.sizes()
if bottomHeight > 0 or primViewWidth > 0:
topHeight += bottomHeight
bottomHeight = 0
stageViewWidth += primViewWidth
primViewWidth = 0
else:
if self._viewerModeEscapeSizes is not None:
topHeight, bottomHeight, primViewWidth, stageViewWidth = self._viewerModeEscapeSizes
else:
bottomHeight = UIDefaults.BOTTOM_HEIGHT
topHeight = UIDefaults.TOP_HEIGHT
primViewWidth = UIDefaults.PRIM_VIEW_WIDTH
stageViewWidth = UIDefaults.STAGE_VIEW_WIDTH
self._ui.topBottomSplitter.setSizes([topHeight, bottomHeight])
self._ui.primStageSplitter.setSizes([primViewWidth, stageViewWidth])
def _resetView(self,selectPrim = None):
""" Reverts the GL frame to the initial camera view,
and clears selection (sets to pseudoRoot), UNLESS 'selectPrim' is
not None, in which case we'll select and frame it."""
self._ui.primView.clearSelection()
pRoot = self._dataModel.stage.GetPseudoRoot()
if selectPrim is None:
# if we had a command-line specified selection, re-frame it
selectPrim = self._initialSelectPrim or pRoot
item = self._getItemAtPath(selectPrim.GetPath())
# Our response to selection-change includes redrawing. We do NOT
# want that to happen here, since we are subsequently going to
# change the camera framing (and redraw, again), which can cause
# flickering. So make sure we don't redraw!
self._allowViewUpdates = False
self._ui.primView.setCurrentItem(item)
self._allowViewUpdates = True
if self._stageView:
if (selectPrim and selectPrim != pRoot) or not self._startingPrimCamera:
# _frameSelection translates the camera from wherever it happens
# to be at the time. If we had a starting selection AND a
# primCam, then before framing, switch back to the prim camera
if selectPrim == self._initialSelectPrim and self._startingPrimCamera:
self._dataModel.viewSettings.cameraPrim = self._startingPrimCamera
self._frameSelection()
else:
self._dataModel.viewSettings.cameraPrim = self._startingPrimCamera
self._stageView.updateView()
def _changeRenderMode(self, mode):
self._dataModel.viewSettings.renderMode = str(mode.text())
def _changeColorCorrection(self, mode):
self._dataModel.viewSettings.colorCorrectionMode = str(mode.text())
def _changePickMode(self, mode):
self._dataModel.viewSettings.pickMode = str(mode.text())
def _changeSelHighlightMode(self, mode):
self._dataModel.viewSettings.selHighlightMode = str(mode.text())
def _changeHighlightColor(self, color):
self._dataModel.viewSettings.highlightColorName = str(color.text())
def _changeInterpolationType(self, interpolationType):
for t in Usd.InterpolationType.allValues:
if t.displayName == str(interpolationType.text()):
self._dataModel.stage.SetInterpolationType(t)
self._resetSettings()
break
def _ambientOnlyClicked(self, checked=None):
if self._stageView and checked is not None:
self._dataModel.viewSettings.ambientLightOnly = checked
def _onDomeLightClicked(self, checked=None):
if self._stageView and checked is not None:
self._dataModel.viewSettings.domeLightEnabled = checked
def _changeBgColor(self, mode):
self._dataModel.viewSettings.clearColorText = str(mode.text())
def _toggleShowBBoxPlayback(self):
"""Called when the menu item for showing BBoxes
during playback is activated or deactivated."""
self._dataModel.viewSettings.showBBoxPlayback = (
self._ui.showBBoxPlayback.isChecked())
def _toggleAutoComputeClippingPlanes(self):
autoClip = self._ui.actionAuto_Compute_Clipping_Planes.isChecked()
self._dataModel.viewSettings.autoComputeClippingPlanes = autoClip
if autoClip:
self._stageView.detachAndReClipFromCurrentCamera()
def _setUseExtentsHint(self):
self._dataModel.useExtentsHint = self._ui.useExtentsHint.isChecked()
self._updatePropertyView()
#recompute and display bbox
self._refreshBBox()
def _toggleShowBBoxes(self):
"""Called when the menu item for showing BBoxes
is activated."""
self._dataModel.viewSettings.showBBoxes = self._ui.showBBoxes.isChecked()
#recompute and display bbox
self._refreshBBox()
def _toggleShowAABBox(self):
"""Called when Axis-Aligned bounding boxes
are activated/deactivated via menu item"""
self._dataModel.viewSettings.showAABBox = self._ui.showAABBox.isChecked()
# recompute and display bbox
self._refreshBBox()
def _toggleShowOBBox(self):
"""Called when Oriented bounding boxes
are activated/deactivated via menu item"""
self._dataModel.viewSettings.showOBBox = self._ui.showOBBox.isChecked()
# recompute and display bbox
self._refreshBBox()
def _refreshBBox(self):
"""Recompute and hide/show Bounding Box."""
if self._stageView:
self._stageView.updateView(forceComputeBBox=True)
def _toggleDisplayGuide(self):
self._dataModel.viewSettings.displayGuide = (
self._ui.actionDisplay_Guide.isChecked())
def _toggleDisplayProxy(self):
self._dataModel.viewSettings.displayProxy = (
self._ui.actionDisplay_Proxy.isChecked())
def _toggleDisplayRender(self):
self._dataModel.viewSettings.displayRender = (
self._ui.actionDisplay_Render.isChecked())
def _toggleDisplayCameraOracles(self):
self._dataModel.viewSettings.displayCameraOracles = (
self._ui.actionDisplay_Camera_Oracles.isChecked())
def _toggleDisplayPrimId(self):
self._dataModel.viewSettings.displayPrimId = (
self._ui.actionDisplay_PrimId.isChecked())
def _toggleEnableSceneMaterials(self):
self._dataModel.viewSettings.enableSceneMaterials = (
self._ui.actionEnable_Scene_Materials.isChecked())
def _toggleCullBackfaces(self):
self._dataModel.viewSettings.cullBackfaces = (
self._ui.actionCull_Backfaces.isChecked())
def _showInterpreter(self):
if self._interpreter is None:
self._interpreter = QtWidgets.QDialog(self._mainWindow)
self._interpreter.setObjectName("Interpreter")
self._console = Myconsole(self._interpreter, self._usdviewApi)
self._interpreter.setFocusProxy(self._console) # this is important!
lay = QtWidgets.QVBoxLayout()
lay.addWidget(self._console)
self._interpreter.setLayout(lay)
# dock the interpreter window next to the main usdview window
self._interpreter.move(self._mainWindow.x() + self._mainWindow.frameGeometry().width(),
self._mainWindow.y())
self._interpreter.resize(600, self._mainWindow.size().height()//2)
self._interpreter.show()
self._interpreter.activateWindow()
self._interpreter.setFocus()
def _showDebugFlags(self):
if self._debugFlagsWindow is None:
from .debugFlagsWidget import DebugFlagsWidget
self._debugFlagsWindow = DebugFlagsWidget()
self._debugFlagsWindow.show()
# Screen capture functionality ===========================================
def GrabWindowShot(self):
'''Returns a QImage of the full usdview window '''
# generate an image of the window. Due to how Qt's rendering
# works, this will not pick up the GL Widget(_stageView)'s
# contents, and we'll need to compose it separately.
windowShot = QtGui.QImage(self._mainWindow.size(),
QtGui.QImage.Format_ARGB32_Premultiplied)
painter = QtGui.QPainter(windowShot)
self._mainWindow.render(painter, QtCore.QPoint())
if self._stageView:
# overlay the QGLWidget on and return the composed image
# we offset by a single point here because of Qt.Pos funkyness
offset = QtCore.QPoint(0,1)
pos = self._stageView.mapTo(self._mainWindow, self._stageView.pos()) - offset
painter.drawImage(pos, self.GrabViewportShot())
return windowShot
def GrabViewportShot(self):
'''Returns a QImage of the current stage view in usdview.'''
if self._stageView:
return self._stageView.grabFrameBuffer()
else:
return None
# File handling functionality =============================================
def _cleanAndClose(self):
# This function is called by the main window's closeEvent handler.
self._settings2.save()
# If the current path widget is focused when closing usdview, it can
# trigger an "editingFinished()" signal, which will look for a prim in
# the scene (which is already deleted). This prevents that.
# XXX:
# This method is reentrant and calling disconnect twice on a signal
# causes an exception to be thrown.
try:
self._ui.currentPathWidget.editingFinished.disconnect(
self._currentPathChanged)
except RuntimeError:
pass
# Shut down some timers and our eventFilter
self._primViewUpdateTimer.stop()
self._guiResetTimer.stop()
QtWidgets.QApplication.instance().removeEventFilter(self._filterObj)
# If the timer is currently active, stop it from being invoked while
# the USD stage is being torn down.
if self._timer.isActive():
self._timer.stop()
# Close stage and release renderer resources (if applicable).
self._closeStage()
# Start timer to measure Qt shutdown time
self._startQtShutdownTimer()
def _openFile(self):
extensions = Sdf.FileFormat.FindAllFileFormatExtensions()
builtInFiles = lambda f: f.startswith(".usd")
notBuiltInFiles = lambda f: not f.startswith(".usd")
extensions = list(filter(builtInFiles, extensions)) + \
list(filter(notBuiltInFiles, extensions))
fileFilter = "USD Compatible Files (" + " ".join("*." + e for e in extensions) + ")"
(filename, _) = QtWidgets.QFileDialog.getOpenFileName(
self._mainWindow,
caption="Select file",
dir=".",
filter=fileFilter,
selectedFilter=fileFilter)
if len(filename) > 0:
self._parserData.usdFile = str(filename)
self._mainWindow.setWindowTitle(filename)
self._reopenStage()
def _getSaveFileName(self, caption, recommendedFilename):
(saveName, _) = QtWidgets.QFileDialog.getSaveFileName(
self._mainWindow,
caption,
'./' + recommendedFilename,
'USD Files (*.usd)'
';;USD ASCII Files (*.usda)'
';;USD Crate Files (*.usdc)'
';;Any USD File (*.usd *.usda *.usdc)',
'Any USD File (*.usd *.usda *.usdc)')
if len(saveName) == 0:
return ''
_, ext = os.path.splitext(saveName)
if ext not in ('.usd', '.usda', '.usdc'):
saveName += '.usd'
return saveName
def _saveOverridesAs(self):
recommendedFilename = self._parserData.usdFile.rsplit('.', 1)[0]
recommendedFilename += '_overrides.usd'
saveName = self._getSaveFileName(
'Save Overrides As', recommendedFilename)
if len(saveName) == 0:
return
if not self._dataModel.stage:
return
with BusyContext():
# In the future, we may allow usdview to be brought up with no file,
# in which case it would create an in-memory root layer, to which
# all edits will be targeted. In order to future proof
# this, first fetch the root layer, and if it is anonymous, just
# export it to the given filename. If it isn't anonmyous (i.e., it
# is a regular usd file on disk), export the session layer and add
# the stage root file as a sublayer.
rootLayer = self._dataModel.stage.GetRootLayer()
if not rootLayer.anonymous:
self._dataModel.stage.GetSessionLayer().Export(
saveName, 'Created by UsdView')
targetLayer = Sdf.Layer.FindOrOpen(saveName)
UsdUtils.CopyLayerMetadata(rootLayer, targetLayer,
skipSublayers=True)
# We don't ever store self.realStartTimeCode or
# self.realEndTimeCode in a layer, so we need to author them
# here explicitly.
if self.realStartTimeCode:
targetLayer.startTimeCode = self.realStartTimeCode
if self.realEndTimeCode:
targetLayer.endTimeCode = self.realEndTimeCode
targetLayer.subLayerPaths.append(
self._dataModel.stage.GetRootLayer().realPath)
targetLayer.RemoveInertSceneDescription()
targetLayer.Save()
else:
self._dataModel.stage.GetRootLayer().Export(
saveName, 'Created by UsdView')
def _saveFlattenedAs(self):
recommendedFilename = self._parserData.usdFile.rsplit('.', 1)[0]
recommendedFilename += '_flattened.usd'
saveName = self._getSaveFileName(
'Save Flattened As', recommendedFilename)
if len(saveName) == 0:
return
with BusyContext():
self._dataModel.stage.Export(saveName)
def _togglePause(self):
if self._stageView.IsPauseRendererSupported():
self._paused = not self._paused
self._stageView.SetRendererPaused(self._paused)
self._ui.actionPause.setChecked(self._paused)
def _toggleStop(self):
if self._stageView.IsStopRendererSupported():
# Ask the renderer whether its currently stopped or not
# as the value of the _stopped variable can become out of
# date if for example any camera munging happens
self._stopped = self._stageView.IsRendererConverged()
self._stopped = not self._stopped
self._stageView.SetRendererStopped(self._stopped)
self._ui.actionStop.setChecked(self._stopped)
def _reopenStage(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
# Pause the stage view while we update
if self._stageView:
self._stageView.setUpdatesEnabled(False)
try:
# Clear out any Usd objects that may become invalid.
self._dataModel.selection.clear()
self._currentSpec = None
self._currentLayer = None
# Close the current stage so that we don't keep it in memory
# while trying to open another stage.
self._closeStage()
stage = self._openStage(
self._parserData.usdFile, self._parserData.sessionLayer,
self._parserData.populationMask)
# We need this for layers which were cached in memory but changed on
# disk. The additional Reload call should be cheap when nothing
# actually changed.
stage.Reload()
self._dataModel.stage = stage
self._resetSettings()
self._resetView()
self._stepSizeChanged()
except Exception as err:
self.statusMessage('Error occurred reopening Stage: %s' % err)
traceback.print_exc()
finally:
if self._stageView:
self._stageView.setUpdatesEnabled(True)
QtWidgets.QApplication.restoreOverrideCursor()
self.statusMessage('Stage Reopened')
def _reloadStage(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
self._dataModel.stage.Reload()
# Seems like a good time to clear the texture registry
Glf.TextureRegistry.Reset()
# reset timeline, and playback settings from stage metadata
self._reloadFixedUI(resetStageDataOnly=True)
except Exception as err:
self.statusMessage('Error occurred rereading all layers for Stage: %s' % err)
finally:
QtWidgets.QApplication.restoreOverrideCursor()
self.statusMessage('All Layers Reloaded.')
def _cameraSelectionChanged(self, camera):
self._dataModel.viewSettings.cameraPrim = camera
def _refreshCameraListAndMenu(self, preserveCurrCamera):
self._allSceneCameras = Utils._GetAllPrimsOfType(
self._dataModel.stage, Tf.Type.Find(UsdGeom.Camera))
currCamera = self._startingPrimCamera
if self._stageView:
currCamera = self._dataModel.viewSettings.cameraPrim
self._stageView.allSceneCameras = self._allSceneCameras
# if the stageView is holding an expired camera, clear it first
# and force search for a new one
if currCamera != None and not (currCamera and currCamera.IsActive()):
currCamera = None
self._dataModel.viewSettings.cameraPrim = None
preserveCurrCamera = False
if not preserveCurrCamera:
cameraWasSet = False
def setCamera(camera):
self._startingPrimCamera = currCamera = camera
self._dataModel.viewSettings.cameraPrim = camera
cameraWasSet = True
if self._startingPrimCameraPath:
prim = self._dataModel.stage.GetPrimAtPath(
self._startingPrimCameraPath)
if not prim.IsValid():
msg = sys.stderr
print("WARNING: Camera path %r did not exist in stage"
% self._startingPrimCameraPath, file=msg)
self._startingPrimCameraPath = None
elif not prim.IsA(UsdGeom.Camera):
msg = sys.stderr
print("WARNING: Camera path %r was not a UsdGeom.Camera"
% self._startingPrimCameraPath, file=msg)
self._startingPrimCameraPath = None
else:
setCamera(prim)
if not cameraWasSet and self._startingPrimCameraName:
for camera in self._allSceneCameras:
if camera.GetName() == self._startingPrimCameraName:
setCamera(camera)
break
# Now that we have the current camera and all cameras, build the menu
self._ui.menuCamera.clear()
if len(self._allSceneCameras) == 0:
self._ui.menuCamera.setEnabled(False)
else:
self._ui.menuCamera.setEnabled(True)
currCameraPath = None
if currCamera:
currCameraPath = currCamera.GetPath()
for camera in self._allSceneCameras:
action = self._ui.menuCamera.addAction(camera.GetName())
action.setData(camera.GetPath())
action.setToolTip(str(camera.GetPath()))
action.setCheckable(True)
action.triggered[bool].connect(
lambda _, cam = camera: self._cameraSelectionChanged(cam))
action.setChecked(action.data() == currCameraPath)
def _updatePropertiesFromPropertyView(self):
"""Update the data model's property selection to match property view's
current selection.
"""
selectedProperties = dict()
for item in self._ui.propertyView.selectedItems():
# We define data 'roles' in the property viewer to distinguish between things
# like attributes and attributes with connections, relationships and relationships
# with targets etc etc.
role = item.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
if role in (PropertyViewDataRoles.CONNECTION, PropertyViewDataRoles.TARGET):
# Get the owning property's set of selected targets.
propName = str(item.parent().text(PropertyViewIndex.NAME))
prop = self._propertiesDict[propName]
targets = selectedProperties.setdefault(prop, set())
# Add the target to the set of targets.
targetPath = Sdf.Path(str(item.text(PropertyViewIndex.NAME)))
if role == PropertyViewDataRoles.CONNECTION:
prim = self._dataModel.stage.GetPrimAtPath(
targetPath.GetPrimPath())
target = prim.GetProperty(targetPath.name)
else: # role == PropertyViewDataRoles.TARGET
target = self._dataModel.stage.GetPrimAtPath(
targetPath)
targets.add(target)
else:
propName = str(item.text(PropertyViewIndex.NAME))
prop = self._propertiesDict[propName]
selectedProperties.setdefault(prop, set())
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for prop, targets in selectedProperties.items():
if not isinstance(prop, CustomAttribute):
self._dataModel.selection.addProp(prop)
for target in targets:
self._dataModel.selection.addPropTarget(prop, target)
with self._dataModel.selection.batchComputedPropChanges:
self._dataModel.selection.clearComputedProps()
for prop, targets in selectedProperties.items():
if isinstance(prop, CustomAttribute):
self._dataModel.selection.addComputedProp(prop)
def _propertyViewSelectionChanged(self):
"""Called whenever property view's selection changes."""
if self._propertyViewSelectionBlocker.blocked():
return
self._updatePropertiesFromPropertyView()
def _propertyViewCurrentItemChanged(self, currentItem, lastItem):
"""Called whenever property view's current item changes."""
if self._propertyViewSelectionBlocker.blocked():
return
# If a selected item becomes the current item, it will not fire a
# selection changed signal but we still want to change the property
# selection.
if currentItem is not None and currentItem.isSelected():
self._updatePropertiesFromPropertyView()
def _propSelectionChanged(self):
"""Called whenever the property selection in the data model changes.
Updates any UI that relies on the selection state.
"""
self._updatePropertyViewSelection()
self._populatePropertyInspector()
self._updatePropertyInspector()
def _populatePropertyInspector(self):
focusPrimPath = None
focusPropName = None
focusProp = self._dataModel.selection.getFocusProp()
if focusProp is None:
focusPrimPath, focusPropName = (
self._dataModel.selection.getFocusComputedPropPath())
else:
focusPrimPath = focusProp.GetPrimPath()
focusPropName = focusProp.GetName()
if focusPropName is not None:
# inform the value editor that we selected a new attribute
self._ui.attributeValueEditor.populate(focusPrimPath, focusPropName)
else:
self._ui.attributeValueEditor.clear()
def _onCompositionSelectionChanged(self, curr=None, prev=None):
self._currentSpec = getattr(curr, 'spec', None)
self._currentLayer = getattr(curr, 'layer', None)
def _updatePropertyInspector(self, index=None, obj=None):
# index must be the first parameter since this method is used as
# propertyInspector tab widget's currentChanged(int) signal callback
if index is None:
index = self._ui.propertyInspector.currentIndex()
if obj is None:
obj = self._getSelectedObject()
if index == PropertyIndex.METADATA:
self._updateMetadataView(obj)
elif index == PropertyIndex.LAYERSTACK:
self._updateLayerStackView(obj)
elif index == PropertyIndex.COMPOSITION:
self._updateCompositionView(obj)
def _refreshAttributeValue(self):
self._ui.attributeValueEditor.refresh()
def _propertyViewContextMenu(self, point):
item = self._ui.propertyView.itemAt(point)
if item:
self.contextMenu = AttributeViewContextMenu(self._mainWindow,
item, self._dataModel)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _layerStackContextMenu(self, point):
item = self._ui.layerStackView.itemAt(point)
if item:
self.contextMenu = LayerStackContextMenu(self._mainWindow, item)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _compositionTreeContextMenu(self, point):
item = self._ui.compositionTreeWidget.itemAt(point)
self.contextMenu = LayerStackContextMenu(self._mainWindow, item)
self.contextMenu.exec_(QtGui.QCursor.pos())
# Headers & Columns =================================================
def _propertyViewHeaderContextMenu(self, point):
self.contextMenu = HeaderContextMenu(self._ui.propertyView)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _primViewHeaderContextMenu(self, point):
self.contextMenu = HeaderContextMenu(self._ui.primView)
self.contextMenu.exec_(QtGui.QCursor.pos())
# Widget management =================================================
def _changePrimViewDepth(self, action):
"""Signal handler for view-depth menu items
"""
actionTxt = str(action.text())
# recover the depth factor from the action's name
depth = int(actionTxt[actionTxt.find(" ")+1])
self._expandToDepth(depth)
def _expandToDepth(self, depth, suppressTiming=False):
"""Expands treeview prims to the given depth
"""
with Timer() as t, BusyContext():
# Populate items down to depth. Qt will expand items at depth
# depth-1 so we need to have items at depth. We know something
# changed if any items were added to _itemsToPush.
n = len(self._itemsToPush)
self._populateItem(self._dataModel.stage.GetPseudoRoot(),
maxDepth=depth)
changed = (n != len(self._itemsToPush))
# Expand the tree to depth.
self._ui.primView.expandToDepth(depth-1)
if changed:
# Resize column.
self._scheduleResizePrimView()
# Start pushing prim data to the UI during idle cycles.
# Qt doesn't need the data unless the item is actually
# visible (or affects what's visible) but to avoid
# jerky scrolling when that data is pulled during the
# scroll, we can do it ahead of time. But don't do it
# if we're currently playing to maximize playback
# performance.
if not self._dataModel.playing:
self._primViewUpdateTimer.start()
if self._printTiming and not suppressTiming:
t.PrintTime("expand Prim browser to depth %d" % depth)
def _primViewExpanded(self, index):
"""Signal handler for expanded(index), facilitates lazy tree population
"""
self._populateChildren(self._ui.primView.itemFromIndex(index))
self._scheduleResizePrimView()
def _toggleShowInactivePrims(self):
self._dataModel.viewSettings.showInactivePrims = (
self._ui.actionShow_Inactive_Prims.isChecked())
# Note: _toggleShowInactivePrims, _toggleShowMasterPrims,
# _toggleShowUndefinedPrims, and _toggleShowAbstractPrims all call
# _resetPrimView after being toggled, but only from menu items.
# In the future, we should do this when a signal from
# ViewSettingsDataModel is emitted so the prim view always updates
# when they are changed.
self._dataModel.selection.removeInactivePrims()
self._resetPrimView()
def _toggleShowMasterPrims(self):
self._dataModel.viewSettings.showAllMasterPrims = (
self._ui.actionShow_All_Master_Prims.isChecked())
self._dataModel.selection.removeMasterPrims()
self._resetPrimView()
def _toggleShowUndefinedPrims(self):
self._dataModel.viewSettings.showUndefinedPrims = (
self._ui.actionShow_Undefined_Prims.isChecked())
self._dataModel.selection.removeUndefinedPrims()
self._resetPrimView()
def _toggleShowAbstractPrims(self):
self._dataModel.viewSettings.showAbstractPrims = (
self._ui.actionShow_Abstract_Prims.isChecked())
self._dataModel.selection.removeAbstractPrims()
self._resetPrimView()
def _toggleRolloverPrimInfo(self):
self._dataModel.viewSettings.rolloverPrimInfo = (
self._ui.actionRollover_Prim_Info.isChecked())
if self._stageView:
self._stageView.rolloverPicking = self._dataModel.viewSettings.rolloverPrimInfo
def _tallyPrimStats(self, prim):
def _GetType(prim):
typeString = prim.GetTypeName()
return HUDEntries.NOTYPE if not typeString else typeString
childTypeDict = {}
primCount = 0
for child in Usd.PrimRange(prim):
typeString = _GetType(child)
# skip pseudoroot
if typeString is HUDEntries.NOTYPE and not prim.GetParent():
continue
primCount += 1
childTypeDict[typeString] = 1 + childTypeDict.get(typeString, 0)
return (primCount, childTypeDict)
def _populateChildren(self, item, depth=0, maxDepth=1, childrenToAdd=None):
"""Populates the children of the given item in the prim viewer.
If childrenToAdd is given its a list of prims to add as
children."""
if depth < maxDepth and item.prim.IsActive():
if item.needsChildrenPopulated() or childrenToAdd:
# Populate all the children.
if not childrenToAdd:
childrenToAdd = self._getFilteredChildren(item.prim)
item.addChildren([self._populateItem(child, depth+1, maxDepth)
for child in childrenToAdd])
elif depth + 1 < maxDepth:
# The children already exist but we're recursing deeper.
for i in range(item.childCount()):
self._populateChildren(item.child(i), depth+1, maxDepth)
def _populateItem(self, prim, depth=0, maxDepth=0):
"""Populates a prim viewer item."""
item = self._primToItemMap.get(prim)
if not item:
# Create a new item. If we want its children we obviously
# have to create those too.
children = self._getFilteredChildren(prim)
item = PrimViewItem(prim, self, len(children) != 0)
self._primToItemMap[prim] = item
self._populateChildren(item, depth, maxDepth, children)
# Push the item after the children so ancestors are processed
# before descendants.
self._itemsToPush.append(item)
else:
# Item already exists. Its children may or may not exist.
# Either way, we need to have them to get grandchildren.
self._populateChildren(item, depth, maxDepth)
return item
def _populateRoots(self):
invisibleRootItem = self._ui.primView.invisibleRootItem()
rootPrim = self._dataModel.stage.GetPseudoRoot()
rootItem = self._populateItem(rootPrim)
self._populateChildren(rootItem)
if self._dataModel.viewSettings.showAllMasterPrims:
self._populateChildren(rootItem,
childrenToAdd=self._dataModel.stage.GetMasters())
# Add all descendents all at once.
invisibleRootItem.addChild(rootItem)
def _getFilteredChildren(self, prim):
return prim.GetFilteredChildren(self._displayPredicate)
def _computeDisplayPredicate(self):
# Take current browser filtering into account when discovering
# prims while traversing
self._displayPredicate = None
if not self._dataModel.viewSettings.showInactivePrims:
self._displayPredicate = Usd.PrimIsActive \
if self._displayPredicate is None \
else self._displayPredicate & Usd.PrimIsActive
if not self._dataModel.viewSettings.showUndefinedPrims:
self._displayPredicate = Usd.PrimIsDefined \
if self._displayPredicate is None \
else self._displayPredicate & Usd.PrimIsDefined
if not self._dataModel.viewSettings.showAbstractPrims:
self._displayPredicate = ~Usd.PrimIsAbstract \
if self._displayPredicate is None \
else self._displayPredicate & ~Usd.PrimIsAbstract
if self._displayPredicate is None:
self._displayPredicate = Usd._PrimFlagsPredicate.Tautology()
# Unless user experience indicates otherwise, we think we always
# want to show instance proxies
self._displayPredicate = Usd.TraverseInstanceProxies(self._displayPredicate)
def _getItemAtPath(self, path, ensureExpanded=False):
# If the prim hasn't been expanded yet, drill down into it.
# Note the explicit str(path) in the following expr is necessary
# because path may be a QString.
path = path if isinstance(path, Sdf.Path) else Sdf.Path(str(path))
parent = self._dataModel.stage.GetPrimAtPath(path)
if not parent:
raise RuntimeError("Prim not found at path in stage: %s" % str(path))
pseudoRoot = self._dataModel.stage.GetPseudoRoot()
if parent not in self._primToItemMap:
# find the first loaded parent
childList = []
while parent != pseudoRoot \
and not parent in self._primToItemMap:
childList.append(parent)
parent = parent.GetParent()
# go one step further, since the first item found could be hidden
# under a norgie and we would want to populate its siblings as well
if parent != pseudoRoot:
childList.append(parent)
# now populate down to the child
for parent in reversed(childList):
try:
item = self._primToItemMap[parent]
self._populateChildren(item)
if ensureExpanded:
item.setExpanded(True)
except:
item = None
# finally, return the requested item, which now should be in
# the map. If something has been added, this can fail. Not
# sure how to rebuild or add this to the map in a minimal way,
# but after the first hiccup, I don't see any ill
# effects. Would love to know a better way...
# - wave 04.17.2018
prim = self._dataModel.stage.GetPrimAtPath(path)
try:
item = self._primToItemMap[prim]
except:
item = None
return item
def selectPseudoroot(self):
"""Selects only the pseudoroot."""
self._dataModel.selection.clearPrims()
def selectEnclosingModel(self):
"""Iterates through all selected prims, selecting their containing model
instead if they are not a model themselves.
"""
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
model = GetEnclosingModelPrim(prim)
if model:
self._dataModel.selection.addPrim(model)
else:
self._dataModel.selection.addPrim(prim)
def selectBoundMaterialForPurpose(self, materialPurpose):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
(boundMaterial, bindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=materialPurpose)
if boundMaterial:
self._dataModel.selection.addPrim(boundMaterial.GetPrim())
def selectBindingRelForPurpose(self, materialPurpose):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
relsToSelect = []
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
(boundMaterial, bindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=materialPurpose)
if boundMaterial and bindingRel:
self._dataModel.selection.addPrim(bindingRel.GetPrim())
relsToSelect.append(bindingRel)
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for rel in relsToSelect:
self._dataModel.selection.addProp(rel)
def selectBoundPreviewMaterial(self):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
self.selectBoundMaterialForPurpose(
materialPurpose=UsdShade.Tokens.preview)
def selectBoundFullMaterial(self):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
self.selectBoundMaterialForPurpose(
materialPurpose=UsdShade.Tokens.full)
def selectPreviewBindingRel(self):
"""Iterates through all selected prims, computing their resolved
"preview" bindings and selecting the cooresponding binding relationship.
"""
self.selectBindingRelForPurpose(materialPurpose=UsdShade.Tokens.preview)
def selectFullBindingRel(self):
"""Iterates through all selected prims, computing their resolved
"full" bindings and selecting the cooresponding binding relationship.
"""
self.selectBindingRelForPurpose(materialPurpose=UsdShade.Tokens.full)
def _getCommonPrims(self, pathsList):
commonPrefix = os.path.commonprefix(pathsList)
### To prevent /Canopies/TwigA and /Canopies/TwigB
### from registering /Canopies/Twig as prefix
return commonPrefix.rsplit('/', 1)[0]
def _primSelectionChanged(self, added, removed):
"""Called when the prim selection is updated in the data model. Updates
any UI that depends on the state of the selection.
"""
with self._primViewSelectionBlocker:
self._updatePrimViewSelection(added, removed)
self._updatePrimPathText()
if self._stageView:
self._updateHUDPrimStats()
self._updateHUDGeomCounts()
self._stageView.updateView()
self._updatePropertyInspector(
obj=self._dataModel.selection.getFocusPrim())
self._updatePropertyView()
self._refreshAttributeValue()
def _getPrimsFromPaths(self, paths):
"""Get all prims from a list of paths."""
prims = []
for path in paths:
# Ensure we have an Sdf.Path, not a string.
sdfPath = Sdf.Path(str(path))
prim = self._dataModel.stage.GetPrimAtPath(
sdfPath.GetAbsoluteRootOrPrimPath())
if not prim:
raise PrimNotFoundException(sdfPath)
prims.append(prim)
return prims
def _updatePrimPathText(self):
self._ui.currentPathWidget.setText(
', '.join([str(prim.GetPath())
for prim in self._dataModel.selection.getPrims()]))
def _currentPathChanged(self):
"""Called when the currentPathWidget text is changed"""
newPaths = self._ui.currentPathWidget.text()
pathList = re.split(", ?", newPaths)
pathList = [path for path in pathList if len(path) != 0]
try:
prims = self._getPrimsFromPaths(pathList)
except PrimNotFoundException as ex:
# _getPrimsFromPaths couldn't find one of the prims
sys.stderr.write("ERROR: %s\n" % str(ex))
self._updatePrimPathText()
return
explicitProps = any(Sdf.Path(str(path)).IsPropertyPath()
for path in pathList)
if len(prims) == 1 and not explicitProps:
self._dataModel.selection.switchToPrimPath(prims[0].GetPath())
else:
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in prims:
self._dataModel.selection.addPrim(prim)
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for path, prim in zip(pathList, prims):
sdfPath = Sdf.Path(str(path))
if sdfPath.IsPropertyPath():
self._dataModel.selection.addPropPath(path)
self._dataModel.selection.clearComputedProps()
# A function for maintaining the primview. For each prim in prims,
# first check that it exists. Then if its item has not
# yet been populated, use _getItemAtPath to populate its "chain"
# of parents, so that the prim's item can be accessed. If it
# does already exist in the _primToItemMap, either expand or
# unexpand the item.
def _expandPrims(self, prims, expand=True):
if prims:
for prim in prims:
if prim:
item = self._primToItemMap.get(prim)
if not item:
primPath = prim.GetPrimPath()
item = self._getItemAtPath(primPath)
# Depending on our "Show Prim" settings, a valid,
# yet inactive, undefined, or abstract prim may
# not yield an item at all.
if item:
item.setExpanded(expand)
def _refreshPrimViewSelection(self, expandedPrims):
"""Refresh the selected prim view items to match the selection data
model.
"""
self._ui.primView.clearSelection()
selectedItems = [
self._getItemAtPath(prim.GetPath())
for prim in self._dataModel.selection.getPrims()]
if len(selectedItems) > 0:
self._ui.primView.setCurrentItem(selectedItems[0])
# unexpand items that were expanded through setting the current item
currExpandedPrims = self._getExpandedPrimViewPrims()
self._expandPrims(currExpandedPrims, expand=False)
# expand previously expanded items in primview
self._expandPrims(expandedPrims)
self._ui.primView.updateSelection(selectedItems, [])
def _updatePrimViewSelection(self, added, removed):
"""Do an incremental update to primView's selection using the added and
removed prim paths from the selectionDataModel.
"""
addedItems = [
self._getItemAtPath(path)
for path in added ]
removedItems = [ self._getItemAtPath(path) for path in removed ]
self._ui.primView.updateSelection(addedItems, removedItems)
def _primsFromSelectionRanges(self, ranges):
"""Iterate over all prims in a QItemSelection from primView."""
for itemRange in ranges:
for index in itemRange.indexes():
if index.column() == 0:
item = self._ui.primView.itemFromIndex(index)
yield item.prim
def _selectionChanged(self, added, removed):
"""Called when primView's selection is changed. If the selection was
changed by a user, update the selection data model with the changes.
"""
if self._primViewSelectionBlocker.blocked():
return
items = self._ui.primView.selectedItems()
if len(items) == 1:
self._dataModel.selection.switchToPrimPath(items[0].prim.GetPath())
else:
with self._dataModel.selection.batchPrimChanges:
for prim in self._primsFromSelectionRanges(added):
self._dataModel.selection.addPrim(prim)
for prim in self._primsFromSelectionRanges(removed):
self._dataModel.selection.removePrim(prim)
def _itemClicked(self, item, col):
# If user clicked in a selected row, we will toggle all selected items;
# otherwise, just the clicked one.
if col == PrimViewColumnIndex.VIS:
itemsToToggle = [ item ]
if item.isSelected():
itemsToToggle = [
self._getItemAtPath(prim.GetPath(), ensureExpanded=True)
for prim in self._dataModel.selection.getPrims()]
changedAny = False
with Timer() as t:
for toToggle in itemsToToggle:
# toggleVis() returns True if the click caused a visibility
# change.
changedOne = toToggle.toggleVis()
if changedOne:
PrimViewItem.propagateVis(toToggle)
changedAny = True
if changedAny:
self.editComplete('Updated prim visibility')
if self._printTiming:
t.PrintTime("update vis column")
def _itemPressed(self, item, col):
if col == PrimViewColumnIndex.DRAWMODE:
self._ui.primView.ShowDrawModeWidgetForItem(item)
def _getPathsFromItems(self, items, prune = False):
# this function returns a list of paths given a list of items if
# prune=True, it excludes certain paths if a parent path is already
# there this avoids double-rendering if both a prim and its parent
# are selected.
#
# Don't include the pseudoroot, though, if it's still selected, because
# leaving it in the pruned list will cause everything else to get
# pruned away!
allPaths = [itm.prim.GetPath() for itm in items]
if not prune:
return allPaths
if len(allPaths) > 1:
allPaths = [p for p in allPaths if p != Sdf.Path.absoluteRootPath]
return Sdf.Path.RemoveDescendentPaths(allPaths)
def _primViewContextMenu(self, point):
item = self._ui.primView.itemAt(point)
self._showPrimContextMenu(item)
def _showPrimContextMenu(self, item):
self.contextMenu = PrimContextMenu(self._mainWindow, item, self)
self.contextMenu.exec_(QtGui.QCursor.pos())
def setFrame(self, frame):
"""Set the `frame`.
Args:
frame (float): The new frame value.
"""
frameIndex = self._findClosestFrameIndex(frame)
self._setFrameIndex(frameIndex)
def _setFrameIndex(self, frameIndex):
"""Set the `frameIndex`.
Args:
frameIndex (int): The new frame index value.
"""
# Ensure the frameIndex exists, if not, return.
try:
frame = self._timeSamples[frameIndex]
except IndexError:
return
currentFrame = Usd.TimeCode(frame)
if self._dataModel.currentFrame != currentFrame:
self._dataModel.currentFrame = currentFrame
self._ui.frameSlider.setValue(frameIndex)
self._updateOnFrameChange()
self.setFrameField(self._dataModel.currentFrame.GetValue())
def _updateGUIForFrameChange(self):
"""Called when the frame changes have finished.
e.g When the playback/scrubbing has stopped.
"""
# slow stuff that we do only when not playing
# topology might have changed, recalculate
self._updateHUDGeomCounts()
self._updatePropertyView()
self._refreshAttributeValue()
# value sources of an attribute can change upon frame change
# due to value clips, so we must update the layer stack.
self._updateLayerStackView()
# refresh the visibility column
self._resetPrimViewVis(selItemsOnly=False, authoredVisHasChanged=False)
def _updateOnFrameChange(self):
"""Called when the frame changes, updates the renderer and such"""
# do not update HUD/BBOX if scrubbing or playing
if not (self._dataModel.playing or self._ui.frameSlider.isSliderDown()):
self._updateGUIForFrameChange()
if self._stageView:
# this is the part that renders
if self._dataModel.playing:
highlightMode = self._dataModel.viewSettings.selHighlightMode
if highlightMode == SelectionHighlightModes.ALWAYS:
# We don't want to resend the selection to the renderer
# every frame during playback unless we are actually going
# to see the selection (which is only when highlight mode is
# ALWAYS).
self._stageView.updateSelection()
self._stageView.updateForPlayback()
else:
self._stageView.updateSelection()
self._stageView.updateView()
def saveFrame(self, fileName):
if self._stageView:
pm = QtGui.QPixmap.grabWindow(self._stageView.winId())
pm.save(fileName, 'TIFF')
def _getPropertiesDict(self):
propertiesDict = OrderedDict()
# leave attribute viewer empty if multiple prims selected
if len(self._dataModel.selection.getPrims()) != 1:
return propertiesDict
prim = self._dataModel.selection.getFocusPrim()
composed = _GetCustomAttributes(prim, self._dataModel)
inheritedPrimvars = UsdGeom.PrimvarsAPI(prim).FindInheritablePrimvars()
# There may be overlap between inheritedProps and prim attributes,
# but that's OK because propsDict will uniquify them below
inheritedProps = [primvar.GetAttr() for primvar in inheritedPrimvars]
props = prim.GetAttributes() + prim.GetRelationships() + inheritedProps
def _cmp(v1, v2):
if v1 < v2:
return -1
if v2 < v1:
return 1
return 0
def cmpFunc(propA, propB):
aName = propA.GetName()
bName = propB.GetName()
return _cmp(aName.lower(), bName.lower())
props.sort(key=cmp_to_key(cmpFunc))
# Add the special composed attributes usdview generates
# at the top of our property list.
for prop in composed:
propertiesDict[prop.GetName()] = prop
for prop in props:
propertiesDict[prop.GetName()] = prop
return propertiesDict
def _propertyViewDeselectItem(self, item):
item.setSelected(False)
for i in range(item.childCount()):
item.child(i).setSelected(False)
def _updatePropertyViewSelection(self):
"""Updates property view's selected items to match the data model."""
focusPrim = self._dataModel.selection.getFocusPrim()
propTargets = self._dataModel.selection.getPropTargets()
computedProps = self._dataModel.selection.getComputedPropPaths()
selectedPrimPropNames = dict()
selectedPrimPropNames.update({prop.GetName(): targets
for prop, targets in propTargets.items()})
selectedPrimPropNames.update({propName: set()
for primPath, propName in computedProps})
rootItem = self._ui.propertyView.invisibleRootItem()
with self._propertyViewSelectionBlocker:
for i in range(rootItem.childCount()):
item = rootItem.child(i)
propName = str(item.text(PropertyViewIndex.NAME))
if propName in selectedPrimPropNames:
item.setSelected(True)
# Select relationships and connections.
targets = {prop.GetPath()
for prop in selectedPrimPropNames[propName]}
for j in range(item.childCount()):
childItem = item.child(j)
targetPath = Sdf.Path(
str(childItem.text(PropertyViewIndex.NAME)))
if targetPath in targets:
childItem.setSelected(True)
else:
self._propertyViewDeselectItem(item)
def _updatePropertyViewInternal(self):
frame = self._dataModel.currentFrame
treeWidget = self._ui.propertyView
treeWidget.setTextElideMode(QtCore.Qt.ElideMiddle)
scrollPosition = treeWidget.verticalScrollBar().value()
# get a dictionary of prim attribs/members and store it in self._propertiesDict
self._propertiesDict = self._getPropertiesDict()
with self._propertyViewSelectionBlocker:
treeWidget.clear()
self._populatePropertyInspector()
curPrimSelection = self._dataModel.selection.getFocusPrim()
currRow = 0
for key, primProperty in self._propertiesDict.items():
targets = None
isInheritedProperty = isinstance(primProperty, Usd.Property) and \
(primProperty.GetPrim() != curPrimSelection)
if type(primProperty) == Usd.Attribute:
if primProperty.HasAuthoredConnections():
typeContent = PropertyViewIcons.ATTRIBUTE_WITH_CONNECTIONS()
typeRole = PropertyViewDataRoles.ATTRIBUTE_WITH_CONNNECTIONS
targets = primProperty.GetConnections()
else:
typeContent = PropertyViewIcons.ATTRIBUTE()
typeRole = PropertyViewDataRoles.ATTRIBUTE
elif isinstance(primProperty, ResolvedBoundMaterial):
typeContent = PropertyViewIcons.COMPOSED()
typeRole = PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
elif isinstance(primProperty, CustomAttribute):
typeContent = PropertyViewIcons.COMPOSED()
typeRole = PropertyViewDataRoles.COMPOSED
elif isinstance(primProperty, Usd.Relationship):
# Otherwise we have a relationship
targets = primProperty.GetTargets()
if targets:
typeContent = PropertyViewIcons.RELATIONSHIP_WITH_TARGETS()
typeRole = PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
else:
typeContent = PropertyViewIcons.RELATIONSHIP()
typeRole = PropertyViewDataRoles.RELATIONSHIP
else:
PrintWarning("Property '%s' has unknown property type <%s>." %
(key, type(primProperty)))
continue
valFunc, attrText = GetValueAndDisplayString(primProperty, frame)
item = QtWidgets.QTreeWidgetItem(["", str(key), attrText])
item.rawValue = valFunc()
treeWidget.addTopLevelItem(item)
treeWidget.topLevelItem(currRow).setIcon(PropertyViewIndex.TYPE,
typeContent)
treeWidget.topLevelItem(currRow).setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
typeRole)
currItem = treeWidget.topLevelItem(currRow)
valTextFont = GetPropertyTextFont(primProperty, frame)
if valTextFont:
currItem.setFont(PropertyViewIndex.VALUE, valTextFont)
currItem.setFont(PropertyViewIndex.NAME, valTextFont)
else:
currItem.setFont(PropertyViewIndex.NAME, UIFonts.BOLD)
fgColor = GetPropertyColor(primProperty, frame)
# Inherited properties are colored 15% darker, along with the
# addition of "(i)" in the type column.
if isInheritedProperty:
# Add "(i)" to the type column to indicate an inherited
# property.
treeWidget.topLevelItem(currRow).setText(PropertyViewIndex.TYPE,
"(i)")
fgColor = fgColor.darker(115)
currItem.setFont(PropertyViewIndex.TYPE, UIFonts.INHERITED)
currItem.setForeground(PropertyViewIndex.NAME, fgColor)
currItem.setForeground(PropertyViewIndex.VALUE, fgColor)
if targets:
childRow = 0
for t in targets:
valTextFont = GetPropertyTextFont(primProperty, frame) or \
UIFonts.BOLD
# USD does not provide or infer values for relationship or
# connection targets, so we don't display them here.
currItem.addChild(
QtWidgets.QTreeWidgetItem(["", str(t), ""]))
currItem.setFont(PropertyViewIndex.VALUE, valTextFont)
child = currItem.child(childRow)
if typeRole == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS:
child.setIcon(PropertyViewIndex.TYPE,
PropertyViewIcons.TARGET())
child.setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
PropertyViewDataRoles.TARGET)
else:
child.setIcon(PropertyViewIndex.TYPE,
PropertyViewIcons.CONNECTION())
child.setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
PropertyViewDataRoles.CONNECTION)
childRow += 1
currRow += 1
self._updatePropertyViewSelection()
# For some reason, resetting the scrollbar position here only works on a
# frame change, not when the prim changes. When the prim changes, the
# scrollbar always stays at the top of the list and setValue() has no
# effect.
treeWidget.verticalScrollBar().setValue(scrollPosition)
def _updatePropertyView(self):
""" Sets the contents of the attribute value viewer """
cursorOverride = not self._timer.isActive()
if cursorOverride:
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
self._updatePropertyViewInternal()
except Exception as err:
print("Problem encountered updating attribute view: %s" % err)
raise
finally:
if cursorOverride:
QtWidgets.QApplication.restoreOverrideCursor()
def _getSelectedObject(self):
focusPrim = self._dataModel.selection.getFocusPrim()
attrs = self._ui.propertyView.selectedItems()
if len(attrs) == 0:
return focusPrim
selectedAttribute = attrs[0]
attrName = str(selectedAttribute.text(PropertyViewIndex.NAME))
if PropTreeWidgetTypeIsRel(selectedAttribute):
return focusPrim.GetRelationship(attrName)
obj = focusPrim.GetAttribute(attrName)
if not obj:
# Check if it is an inherited primvar.
inheritedPrimvar = UsdGeom.PrimvarsAPI(
focusPrim).FindPrimvarWithInheritance(attrName)
if inheritedPrimvar:
obj = inheritedPrimvar.GetAttr()
return obj
def _findIndentPos(self, s):
for index, char in enumerate(s):
if char != ' ':
return index
return len(s) - 1
def _maxToolTipWidth(self):
return 90
def _maxToolTipHeight(self):
return 32
def _trimWidth(self, s, isList=False):
# We special-case the display offset because list
# items will have </li> tags embedded in them.
offset = 10 if isList else 5
if len(s) >= self._maxToolTipWidth():
# For strings, well do special ellipsis behavior
# which displays the last 5 chars with an ellipsis
# in between. For other values, we simply display a
# trailing ellipsis to indicate more data.
if s[0] == '\'' and s[-1] == '\'':
return (s[:self._maxToolTipWidth() - offset]
+ '...'
+ s[len(s) - offset:])
else:
return s[:self._maxToolTipWidth()] + '...'
return s
def _limitToolTipSize(self, s, isList=False):
ttStr = ''
lines = s.split('<br>')
for index, line in enumerate(lines):
if index+1 > self._maxToolTipHeight():
break
ttStr += self._trimWidth(line, isList)
if not isList and index != len(lines)-1:
ttStr += '<br>'
if (len(lines) > self._maxToolTipHeight()):
ellipsis = ' '*self._findIndentPos(line) + '...'
if isList:
ellipsis = '<li>' + ellipsis + '</li>'
else:
ellipsis += '<br>'
ttStr += ellipsis
ttStr += self._trimWidth(lines[len(lines)-2], isList)
return ttStr
def _addRichTextIndicators(self, s):
# - We'll need to use html-style spaces to ensure they are respected
# in the toolTip which uses richtext formatting.
# - We wrap the tooltip as a paragraph to ensure 's are
# respected by Qt's rendering engine.
return '<p>' + s.replace(' ', ' ') + '</p>'
def _limitValueDisplaySize(self, s):
maxValueChars = 300
return s[:maxValueChars]
def _cleanStr(self, s, repl):
# Remove redundant char seqs and strip newlines.
replaced = str(s).replace('\n', repl)
filtered = [u for (u, _) in groupby(replaced.split())]
return ' '.join(filtered)
def _formatMetadataValueView(self, val):
from pprint import pformat, pprint
valStr = self._cleanStr(val, ' ')
ttStr = ''
isList = False
# For iterable things, like VtArrays and lists, we want to print
# a nice numbered list.
if isinstance(val, list) or getattr(val, "_isVtArray", False):
isList = True
# We manually supply the index for our list elements
# because Qt's richtext processor starts the <ol> numbering at 1.
for index, value in enumerate(val):
last = len(val) - 1
trimmed = self._cleanStr(value, ' ')
ttStr += ("<li>" + str(index) + ": " + trimmed + "</li><br>")
elif isinstance(val, dict):
# We stringify all dict elements so they display more nicely.
# For example, by default, the pprint operation would print a
# Vt Array as Vt.Array(N, (E1, ....). By running it through
# str(..). we'd get [(E1, E2), ....] which is more useful to
# the end user trying to examine their data.
for k, v in val.items():
val[k] = str(v)
# We'll need to strip the quotes generated by the str' operation above
stripQuotes = lambda s: s.replace('\'', '').replace('\"', "")
valStr = stripQuotes(self._cleanStr(val, ' '))
formattedDict = pformat(val)
formattedDictLines = formattedDict.split('\n')
for index, line in enumerate(formattedDictLines):
ttStr += (stripQuotes(line)
+ ('' if index == len(formattedDictLines) - 1 else '<br>'))
else:
ttStr = self._cleanStr(val, '<br>')
valStr = self._limitValueDisplaySize(valStr)
ttStr = self._addRichTextIndicators(
self._limitToolTipSize(ttStr, isList))
return valStr, ttStr
def _updateMetadataView(self, obj=None):
""" Sets the contents of the metadata viewer"""
# XXX: this method gets called multiple times on selection, it
# would be nice to clean that up and ensure we only update as needed.
tableWidget = self._ui.metadataView
self._propertiesDict = self._getPropertiesDict()
# Setup table widget
tableWidget.clearContents()
tableWidget.setRowCount(0)
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
m = obj.GetAllMetadata()
# We have to explicitly add in metadata related to composition arcs
# and value clips here, since GetAllMetadata prunes them out.
#
# XXX: Would be nice to have some official facility to query
# this.
compKeys = [# composition related metadata
"references", "inheritPaths", "specializes",
"payload", "subLayers"]
for k in compKeys:
v = obj.GetMetadata(k)
if not v is None:
m[k] = v
clipMetadata = obj.GetMetadata("clips")
if clipMetadata is None:
clipMetadata = {}
numClipRows = 0
for (clip, data) in clipMetadata.items():
numClipRows += len(data)
m["clips"] = clipMetadata
numMetadataRows = (len(m) - 1) + numClipRows
# Variant selections that don't have a defined variant set will be
# displayed as well to aid debugging. Collect them separately from
# the variant sets.
variantSets = {}
setlessVariantSelections = {}
if (isinstance(obj, Usd.Prim)):
# Get all variant selections as setless and remove the ones we find
# sets for.
setlessVariantSelections = obj.GetVariantSets().GetAllVariantSelections()
variantSetNames = obj.GetVariantSets().GetNames()
for variantSetName in variantSetNames:
variantSet = obj.GetVariantSet(variantSetName)
variantNames = variantSet.GetVariantNames()
variantSelection = variantSet.GetVariantSelection()
combo = VariantComboBox(None, obj, variantSetName, self._mainWindow)
# First index is always empty to indicate no (or invalid)
# variant selection.
combo.addItem('')
for variantName in variantNames:
combo.addItem(variantName)
indexToSelect = combo.findText(variantSelection)
combo.setCurrentIndex(indexToSelect)
variantSets[variantSetName] = combo
# Remove found variant set from setless.
setlessVariantSelections.pop(variantSetName, None)
tableWidget.setRowCount(numMetadataRows + len(variantSets) +
len(setlessVariantSelections) + 2)
rowIndex = 0
# Although most metadata should be presented alphabetically,the most
# user-facing items should be placed at the beginning of the metadata
# list, these consist of [object type], [path], variant sets, active,
# assetInfo, and kind.
def populateMetadataTable(key, val, rowIndex):
attrName = QtWidgets.QTableWidgetItem(str(key))
tableWidget.setItem(rowIndex, 0, attrName)
valStr, ttStr = self._formatMetadataValueView(val)
attrVal = QtWidgets.QTableWidgetItem(valStr)
attrVal.setToolTip(ttStr)
tableWidget.setItem(rowIndex, 1, attrVal)
sortedKeys = sorted(m.keys())
reorderedKeys = ["kind", "assetInfo", "active"]
for key in reorderedKeys:
if key in sortedKeys:
sortedKeys.remove(key)
sortedKeys.insert(0, key)
object_type = "Attribute" if type(obj) is Usd.Attribute \
else "Prim" if type(obj) is Usd.Prim \
else "Relationship" if type(obj) is Usd.Relationship \
else "Unknown"
populateMetadataTable("[object type]", object_type, rowIndex)
rowIndex += 1
populateMetadataTable("[path]", str(obj.GetPath()), rowIndex)
rowIndex += 1
for variantSetName, combo in variantSets.items():
attrName = QtWidgets.QTableWidgetItem(str(variantSetName+ ' variant'))
tableWidget.setItem(rowIndex, 0, attrName)
tableWidget.setCellWidget(rowIndex, 1, combo)
combo.currentIndexChanged.connect(
lambda i, combo=combo: combo.updateVariantSelection(
i, self._printTiming))
rowIndex += 1
# Add all the setless variant selections directly after the variant
# combo boxes
for variantSetName, variantSelection in setlessVariantSelections.items():
attrName = QtWidgets.QTableWidgetItem(str(variantSetName+ ' variant'))
tableWidget.setItem(rowIndex, 0, attrName)
valStr, ttStr = self._formatMetadataValueView(variantSelection)
# Italicized label to stand out when debugging a scene.
label = QtWidgets.QLabel('<i>' + valStr + '</i>')
label.setIndent(3)
label.setToolTip(ttStr)
tableWidget.setCellWidget(rowIndex, 1, label)
rowIndex += 1
for key in sortedKeys:
if key == "clips":
for (clip, metadataGroup) in m[key].items():
attrName = QtWidgets.QTableWidgetItem(str('clips:' + clip))
tableWidget.setItem(rowIndex, 0, attrName)
for metadata in metadataGroup.keys():
dataPair = (metadata, metadataGroup[metadata])
valStr, ttStr = self._formatMetadataValueView(dataPair)
attrVal = QtWidgets.QTableWidgetItem(valStr)
attrVal.setToolTip(ttStr)
tableWidget.setItem(rowIndex, 1, attrVal)
rowIndex += 1
elif key == "customData":
populateMetadataTable(key, obj.GetCustomData(), rowIndex)
rowIndex += 1
else:
populateMetadataTable(key, m[key], rowIndex)
rowIndex += 1
tableWidget.resizeColumnToContents(0)
def _updateCompositionView(self, obj=None):
""" Sets the contents of the composition tree view"""
treeWidget = self._ui.compositionTreeWidget
treeWidget.clear()
# Update current spec & current layer, and push those updates
# to the python console
self._onCompositionSelectionChanged()
# If no prim or attribute selected, nothing to show.
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
# For brevity, we display only the basename of layer paths.
def LabelForLayer(l):
return ('~session~' if l == self._dataModel.stage.GetSessionLayer()
else l.GetDisplayName())
# Create treeview items for all sublayers in the layer tree.
def WalkSublayers(parent, node, layerTree, sublayer=False):
layer = layerTree.layer
spec = layer.GetObjectAtPath(node.path)
item = QtWidgets.QTreeWidgetItem(
parent,
[
LabelForLayer(layer),
'sublayer' if sublayer else node.arcType.displayName,
str(node.GetPathAtIntroduction()),
'yes' if bool(spec) else 'no'
] )
# attributes for selection:
item.layer = layer
item.spec = spec
item.identifier = layer.identifier
# attributes for LayerStackContextMenu:
if layer.realPath:
item.layerPath = layer.realPath
if spec:
item.path = node.path
item.setExpanded(True)
item.setToolTip(0, layer.identifier)
if not spec:
for i in range(item.columnCount()):
item.setForeground(i, UIPropertyValueSourceColors.NONE)
for subtree in layerTree.childTrees:
WalkSublayers(item, node, subtree, True)
return item
# Create treeview items for all nodes in the composition index.
def WalkNodes(parent, node):
nodeItem = WalkSublayers(parent, node, node.layerStack.layerTree)
for child in node.children:
WalkNodes(nodeItem, child)
path = obj.GetPath().GetAbsoluteRootOrPrimPath()
prim = self._dataModel.stage.GetPrimAtPath(path)
if not prim:
return
# Populate the treeview with items from the prim index.
index = prim.GetPrimIndex()
if index.IsValid():
WalkNodes(treeWidget, index.rootNode)
def _updateLayerStackView(self, obj=None):
""" Sets the contents of the layer stack viewer"""
tableWidget = self._ui.layerStackView
# Setup table widget
tableWidget.clearContents()
tableWidget.setRowCount(0)
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
path = obj.GetPath()
# The pseudoroot is different enough from prims and properties that
# it makes more sense to process it separately
if path == Sdf.Path.absoluteRootPath:
layers = GetRootLayerStackInfo(
self._dataModel.stage.GetRootLayer())
tableWidget.setColumnCount(2)
tableWidget.horizontalHeaderItem(1).setText('Layer Offset')
tableWidget.setRowCount(len(layers))
for i, layer in enumerate(layers):
layerItem = QtWidgets.QTableWidgetItem(layer.GetHierarchicalDisplayString())
layerItem.layerPath = layer.layer.realPath
layerItem.identifier = layer.layer.identifier
toolTip = "<b>identifier:</b> @%s@ <br> <b>resolved path:</b> %s" % \
(layer.layer.identifier, layerItem.layerPath)
toolTip = self._limitToolTipSize(toolTip)
layerItem.setToolTip(toolTip)
tableWidget.setItem(i, 0, layerItem)
offsetItem = QtWidgets.QTableWidgetItem(layer.GetOffsetString())
offsetItem.layerPath = layer.layer.realPath
offsetItem.identifier = layer.layer.identifier
toolTip = self._limitToolTipSize(str(layer.offset))
offsetItem.setToolTip(toolTip)
tableWidget.setItem(i, 1, offsetItem)
tableWidget.resizeColumnToContents(0)
else:
specs = []
tableWidget.setColumnCount(3)
header = tableWidget.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
tableWidget.horizontalHeaderItem(1).setText('Path')
if path.IsPropertyPath():
prop = obj.GetPrim().GetProperty(path.name)
specs = prop.GetPropertyStack(self._dataModel.currentFrame)
c3 = "Value" if (len(specs) == 0 or
isinstance(specs[0], Sdf.AttributeSpec)) else "Target Paths"
tableWidget.setHorizontalHeaderItem(2,
QtWidgets.QTableWidgetItem(c3))
else:
specs = obj.GetPrim().GetPrimStack()
tableWidget.setHorizontalHeaderItem(2,
QtWidgets.QTableWidgetItem('Metadata'))
tableWidget.setRowCount(len(specs))
for i, spec in enumerate(specs):
layerItem = QtWidgets.QTableWidgetItem(spec.layer.GetDisplayName())
layerItem.setToolTip(self._limitToolTipSize(spec.layer.realPath))
tableWidget.setItem(i, 0, layerItem)
pathItem = QtWidgets.QTableWidgetItem(spec.path.pathString)
pathItem.setToolTip(self._limitToolTipSize(spec.path.pathString))
tableWidget.setItem(i, 1, pathItem)
if path.IsPropertyPath():
_, valStr = GetValueAndDisplayString(spec,
self._dataModel.currentFrame)
ttStr = valStr
valueItem = QtWidgets.QTableWidgetItem(valStr)
sampleBased = spec.layer.GetNumTimeSamplesForPath(path) > 0
valueItemColor = (UIPropertyValueSourceColors.TIME_SAMPLE if
sampleBased else UIPropertyValueSourceColors.DEFAULT)
valueItem.setForeground(valueItemColor)
valueItem.setToolTip(ttStr)
else:
metadataKeys = spec.GetMetaDataInfoKeys()
metadataDict = {}
for mykey in metadataKeys:
if spec.HasInfo(mykey):
metadataDict[mykey] = spec.GetInfo(mykey)
valStr, ttStr = self._formatMetadataValueView(metadataDict)
valueItem = QtWidgets.QTableWidgetItem(valStr)
valueItem.setToolTip(ttStr)
tableWidget.setItem(i, 2, valueItem)
# Add the data the context menu needs
for j in range(3):
item = tableWidget.item(i, j)
item.layerPath = spec.layer.realPath
item.path = spec.path.pathString
item.identifier = spec.layer.identifier
def _isHUDVisible(self):
"""Checks if the upper HUD is visible by looking at the global HUD
visibility menu as well as the 'Subtree Info' menu"""
return self._dataModel.viewSettings.showHUD and self._dataModel.viewSettings.showHUD_Info
def _updateCameraMaskMenu(self):
if self._ui.actionCameraMask_Full.isChecked():
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.FULL
elif self._ui.actionCameraMask_Partial.isChecked():
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.PARTIAL
else:
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.NONE
def _updateCameraMaskOutlineMenu(self):
self._dataModel.viewSettings.showMask_Outline = (
self._ui.actionCameraMask_Outline.isChecked())
def _pickCameraMaskColor(self):
QtWidgets.QColorDialog.setCustomColor(0, 0xFF000000)
QtWidgets.QColorDialog.setCustomColor(1, 0xFF808080)
color = QtWidgets.QColorDialog.getColor()
color = (
color.redF(),
color.greenF(),
color.blueF(),
color.alphaF()
)
self._dataModel.viewSettings.cameraMaskColor = color
def _updateCameraReticlesInsideMenu(self):
self._dataModel.viewSettings.showReticles_Inside = (
self._ui.actionCameraReticles_Inside.isChecked())
def _updateCameraReticlesOutsideMenu(self):
self._dataModel.viewSettings.showReticles_Outside = (
self._ui.actionCameraReticles_Outside.isChecked())
def _pickCameraReticlesColor(self):
QtWidgets.QColorDialog.setCustomColor(0, 0xFF000000)
QtWidgets.QColorDialog.setCustomColor(1, 0xFF0080FF)
color = QtWidgets.QColorDialog.getColor()
color = (
color.redF(),
color.greenF(),
color.blueF(),
color.alphaF()
)
self._dataModel.viewSettings.cameraReticlesColor = color
def _showHUDChanged(self):
self._dataModel.viewSettings.showHUD = self._ui.actionHUD.isChecked()
def _showHUD_InfoChanged(self):
self._dataModel.viewSettings.showHUD_Info = (
self._ui.actionHUD_Info.isChecked())
def _showHUD_ComplexityChanged(self):
self._dataModel.viewSettings.showHUD_Complexity = (
self._ui.actionHUD_Complexity.isChecked())
def _showHUD_PerformanceChanged(self):
self._dataModel.viewSettings.showHUD_Performance = (
self._ui.actionHUD_Performance.isChecked())
def _showHUD_GPUstatsChanged(self):
self._dataModel.viewSettings.showHUD_GPUstats = (
self._ui.actionHUD_GPUstats.isChecked())
def _getHUDStatKeys(self):
''' returns the keys of the HUD with PRIM and NOTYPE and the top and
CV, VERT, and FACE at the bottom.'''
keys = [k for k in self._upperHUDInfo.keys() if k not in (
HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE, HUDEntries.PRIM, HUDEntries.NOTYPE)]
keys = [HUDEntries.PRIM, HUDEntries.NOTYPE] + keys + [HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE]
return keys
def _updateHUDPrimStats(self):
"""update the upper HUD with the proper prim information"""
self._upperHUDInfo = dict()
if self._isHUDVisible():
currentPaths = [n.GetPath()
for n in self._dataModel.selection.getLCDPrims()
if n.IsActive()]
for pth in currentPaths:
count,types = self._tallyPrimStats(
self._dataModel.stage.GetPrimAtPath(pth))
# no entry for Prim counts? initilize it
if HUDEntries.PRIM not in self._upperHUDInfo:
self._upperHUDInfo[HUDEntries.PRIM] = 0
self._upperHUDInfo[HUDEntries.PRIM] += count
for typeKey in types.keys():
# no entry for this prim type? initilize it
if typeKey not in self._upperHUDInfo:
self._upperHUDInfo[typeKey] = 0
self._upperHUDInfo[typeKey] += types[typeKey]
if self._stageView:
self._stageView.upperHUDInfo = self._upperHUDInfo
self._stageView.HUDStatKeys = self._getHUDStatKeys()
def _updateHUDGeomCounts(self):
"""updates the upper HUD with the right geom counts
calls _getGeomCounts() to get the info, which means it could be cached"""
if not self._isHUDVisible():
return
# we get multiple geom dicts, if we have multiple prims selected
geomDicts = [self._getGeomCounts(n, self._dataModel.currentFrame)
for n in self._dataModel.selection.getLCDPrims()]
for key in (HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE):
self._upperHUDInfo[key] = 0
for gDict in geomDicts:
self._upperHUDInfo[key] += gDict[key]
if self._stageView:
self._stageView.upperHUDInfo = self._upperHUDInfo
self._stageView.HUDStatKeys = self._getHUDStatKeys()
def _clearGeomCountsForPrimPath(self, primPath):
entriesToRemove = []
# Clear all entries whose prim is either an ancestor or a descendant
# of the given prim path.
for (p, frame) in self._geomCounts:
if (primPath.HasPrefix(p.GetPath()) or p.GetPath().HasPrefix(primPath)):
entriesToRemove.append((p, frame))
for entry in entriesToRemove:
del self._geomCounts[entry]
def _getGeomCounts( self, prim, frame ):
"""returns cached geom counts if available, or calls _calculateGeomCounts()"""
if (prim,frame) not in self._geomCounts:
self._calculateGeomCounts( prim, frame )
return self._geomCounts[(prim,frame)]
def _accountForFlattening(self,shape):
"""Helper function for computing geomCounts"""
if len(shape) == 1:
return shape[0] // 3
else:
return shape[0]
def _calculateGeomCounts(self, prim, frame):
"""Computes the number of CVs, Verts, and Faces for each prim and each
frame in the stage (for use by the HUD)"""
# This is expensive enough that we should give the user feedback
# that something is happening...
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
thisDict = {HUDEntries.CV: 0, HUDEntries.VERT: 0, HUDEntries.FACE: 0}
if prim.IsA(UsdGeom.Curves):
curves = UsdGeom.Curves(prim)
vertexCounts = curves.GetCurveVertexCountsAttr().Get(frame)
if vertexCounts is not None:
for count in vertexCounts:
thisDict[HUDEntries.CV] += count
elif prim.IsA(UsdGeom.Mesh):
mesh = UsdGeom.Mesh(prim)
faceVertexCount = mesh.GetFaceVertexCountsAttr().Get(frame)
faceVertexIndices = mesh.GetFaceVertexIndicesAttr().Get(frame)
if faceVertexCount is not None and faceVertexIndices is not None:
uniqueVerts = set(faceVertexIndices)
thisDict[HUDEntries.VERT] += len(uniqueVerts)
thisDict[HUDEntries.FACE] += len(faceVertexCount)
self._geomCounts[(prim,frame)] = thisDict
for child in prim.GetChildren():
childResult = self._getGeomCounts(child, frame)
for key in (HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE):
self._geomCounts[(prim,frame)][key] += childResult[key]
except Exception as err:
print("Error encountered while computing prim subtree HUD info: %s" % err)
finally:
QtWidgets.QApplication.restoreOverrideCursor()
def _updateNavigationMenu(self):
"""Make the Navigation menu items enabled or disabled depending on the
selected prim."""
anyModels = False
anyBoundPreviewMaterials = False
anyBoundFullMaterials = False
for prim in self._dataModel.selection.getPrims():
if prim.IsA(UsdGeom.Imageable):
imageable = UsdGeom.Imageable(prim)
anyModels = anyModels or GetEnclosingModelPrim(prim) is not None
(previewMat,previewBindingRel) =\
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.preview)
anyBoundPreviewMaterials |= bool(previewMat)
(fullMat,fullBindingRel) =\
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.full)
anyBoundFullMaterials |= bool(fullMat)
self._ui.actionSelect_Model_Root.setEnabled(anyModels)
self._ui.actionSelect_Bound_Preview_Material.setEnabled(
anyBoundPreviewMaterials)
self._ui.actionSelect_Preview_Binding_Relationship.setEnabled(
anyBoundPreviewMaterials)
self._ui.actionSelect_Bound_Full_Material.setEnabled(
anyBoundFullMaterials)
self._ui.actionSelect_Full_Binding_Relationship.setEnabled(
anyBoundFullMaterials)
def _updateEditMenu(self):
"""Make the Edit Prim menu items enabled or disabled depending on the
selected prim."""
# Use the descendent-pruned selection set to avoid redundant
# traversal of the stage to answer isLoaded...
anyLoadable, unused = GetPrimsLoadability(
self._dataModel.selection.getLCDPrims())
removeEnabled = False
anyImageable = False
anyActive = False
anyInactive = False
for prim in self._dataModel.selection.getPrims():
if prim.IsA(UsdGeom.Imageable):
imageable = UsdGeom.Imageable(prim)
anyImageable = anyImageable or bool(imageable)
removeEnabled = removeEnabled or HasSessionVis(prim)
if prim.IsActive():
anyActive = True
else:
anyInactive = True
self._ui.actionRemove_Session_Visibility.setEnabled(removeEnabled)
self._ui.actionMake_Visible.setEnabled(anyImageable)
self._ui.actionVis_Only.setEnabled(anyImageable)
self._ui.actionMake_Invisible.setEnabled(anyImageable)
self._ui.actionLoad.setEnabled(anyLoadable)
self._ui.actionUnload.setEnabled(anyLoadable)
self._ui.actionActivate.setEnabled(anyInactive)
self._ui.actionDeactivate.setEnabled(anyActive)
def getSelectedItems(self):
return [self._primToItemMap[n]
for n in self._dataModel.selection.getPrims()
if n in self._primToItemMap]
def _getPrimFromPropString(self, p):
return self._dataModel.stage.GetPrimAtPath(p.split('.')[0])
def visSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeVisible()
self.editComplete('Made selected prims visible')
def visOnlySelectedPrims(self):
with BusyContext():
ResetSessionVisibility(self._dataModel.stage)
InvisRootPrims(self._dataModel.stage)
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeVisible()
self.editComplete('Made ONLY selected prims visible')
def invisSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeInvisible()
self.editComplete('Made selected prims invisible')
def removeVisSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.GetVisibilityAttr().Clear()
self.editComplete("Removed selected prims' visibility opinions")
def resetSessionVisibility(self):
with BusyContext():
ResetSessionVisibility(self._dataModel.stage)
self.editComplete('Removed ALL session visibility opinions.')
def _setSelectedPrimsActivation(self, active):
"""Activate or deactivate all selected prims."""
with BusyContext():
# We can only activate/deactivate prims which are not in a master.
paths = []
for item in self.getSelectedItems():
if item.prim.IsPseudoRoot():
print("WARNING: Cannot change activation of pseudoroot.")
elif item.isInMaster:
print("WARNING: The prim <" + str(item.prim.GetPrimPath()) +
"> is in a master. Cannot change activation.")
else:
paths.append(item.prim.GetPrimPath())
# If we are deactivating prims, clear the selection so it doesn't
# hold onto paths from inactive prims.
if not active:
self._dataModel.selection.clear()
# If we try to deactivate prims one at a time in Usd, some may have
# become invalid by the time we get to them. Instead, we set the
# active state all at once through Sdf.
layer = self._dataModel.stage.GetEditTarget().GetLayer()
with Sdf.ChangeBlock():
for path in paths:
sdfPrim = Sdf.CreatePrimInLayer(layer, path)
sdfPrim.active = active
pathNames = ", ".join(path.name for path in paths)
if active:
self.editComplete("Activated {}.".format(pathNames))
else:
self.editComplete("Deactivated {}.".format(pathNames))
def activateSelectedPrims(self):
self._setSelectedPrimsActivation(True)
def deactivateSelectedPrims(self):
self._setSelectedPrimsActivation(False)
def loadSelectedPrims(self):
with BusyContext():
primNames=[]
for item in self.getSelectedItems():
item.setLoaded(True)
primNames.append(item.name)
self.editComplete("Loaded %s." % primNames)
def unloadSelectedPrims(self):
with BusyContext():
primNames=[]
for item in self.getSelectedItems():
item.setLoaded(False)
primNames.append(item.name)
self.editComplete("Unloaded %s." % primNames)
def onStageViewMouseDrag(self):
return
def onPrimSelected(self, path, instanceIndex, topLevelPath, topLevelInstanceIndex, point, button, modifiers):
# Ignoring middle button until we have something
# meaningfully different for it to do
if button in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton]:
# Expected context-menu behavior is that even with no
# modifiers, if we are activating on something already selected,
# do not change the selection
doContext = (button == QtCore.Qt.RightButton and path
and path != Sdf.Path.emptyPath)
doSelection = True
if doContext:
for selPrim in self._dataModel.selection.getPrims():
selPath = selPrim.GetPath()
if (selPath != Sdf.Path.absoluteRootPath and
path.HasPrefix(selPath)):
doSelection = False
break
if doSelection:
self._dataModel.selection.setPoint(point)
shiftPressed = modifiers & QtCore.Qt.ShiftModifier
ctrlPressed = modifiers & QtCore.Qt.ControlModifier
if path != Sdf.Path.emptyPath:
prim = self._dataModel.stage.GetPrimAtPath(path)
# Model picking ignores instancing, but selects the enclosing
# model of the picked prim.
if self._dataModel.viewSettings.pickMode == PickModes.MODELS:
if prim.IsModel():
model = prim
else:
model = GetEnclosingModelPrim(prim)
if model:
prim = model
instanceIndex = ALL_INSTANCES
# Prim picking selects the top level boundable: either the
# gprim, the top-level point instancer (if it's point
# instanced), or the top level USD instance (if it's marked
# instantiable), whichever is closer to namespace root.
# It discards the instance index.
elif self._dataModel.viewSettings.pickMode == PickModes.PRIMS:
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
if topLevelPrim:
prim = topLevelPrim
while prim.IsInstanceProxy():
prim = prim.GetParent()
instanceIndex = ALL_INSTANCES
# Instance picking selects the top level boundable, like
# prim picking; but if that prim is a point instancer or
# a USD instance, it selects the particular instance
# containing the picked object.
elif self._dataModel.viewSettings.pickMode == PickModes.INSTANCES:
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
if topLevelPrim:
prim = topLevelPrim
instanceIndex = topLevelInstanceIndex
if prim.IsInstanceProxy():
while prim.IsInstanceProxy():
prim = prim.GetParent()
instanceIndex = ALL_INSTANCES
# Prototype picking selects a specific instance of the
# actual picked gprim, if the gprim is point-instanced.
# This differs from instance picking by selecting the gprim,
# rather than the prototype subtree; and selecting only one
# drawn instance, rather than all sub-instances of a top-level
# instance (for nested point instancers).
# elif self._dataModel.viewSettings.pickMode == PickModes.PROTOTYPES:
# Just pass the selection info through!
if shiftPressed:
# Clicking prim while holding shift adds it to the
# selection.
self._dataModel.selection.addPrim(prim, instanceIndex)
elif ctrlPressed:
# Clicking prim while holding ctrl toggles it in the
# selection.
self._dataModel.selection.togglePrim(prim, instanceIndex)
else:
# Clicking prim with no modifiers sets it as the
# selection.
self._dataModel.selection.switchToPrimPath(
prim.GetPath(), instanceIndex)
elif not shiftPressed and not ctrlPressed:
# Clicking the background with no modifiers clears the
# selection.
self._dataModel.selection.clear()
if doContext:
item = self._getItemAtPath(path)
self._showPrimContextMenu(item)
# context menu steals mouse release event from the StageView.
# We need to give it one so it can track its interaction
# mode properly
mrEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease,
QtGui.QCursor.pos(),
QtCore.Qt.RightButton,
QtCore.Qt.MouseButtons(QtCore.Qt.RightButton),
QtCore.Qt.KeyboardModifiers())
QtWidgets.QApplication.sendEvent(self._stageView, mrEvent)
def onRollover(self, path, instanceIndex, topLevelPath, topLevelInstanceIndex, modifiers):
prim = self._dataModel.stage.GetPrimAtPath(path)
if prim:
headerStr = ""
propertyStr = ""
materialStr = ""
aiStr = ""
vsStr = ""
model = GetEnclosingModelPrim(prim)
def _MakeModelRelativePath(path, model,
boldPrim=True, boldModel=False):
makeRelative = model and path.HasPrefix(model.GetPath())
if makeRelative:
path = path.MakeRelativePath(model.GetPath().GetParentPath())
pathParts = str(path).split('/')
if boldModel and makeRelative:
pathParts[0] = "<b>%s</b>" % pathParts[0]
if boldPrim:
pathParts[-1] = "<b>%s</b>" % pathParts[-1]
return '/'.join(pathParts)
def _HTMLEscape(s):
return s.replace('&', '&'). \
replace('<', '<'). \
replace('>', '>')
# First add in all model-related data, if present
if model:
groupPath = model.GetPath().GetParentPath()
# Make the model name and prim name bold.
primModelPath = _MakeModelRelativePath(prim.GetPath(),
model, True, True)
headerStr = "%s<br><nobr><small>in group:</small> %s</nobr>" % \
(str(primModelPath),str(groupPath))
# asset info, including computed creation date
mAPI = Usd.ModelAPI(model)
assetInfo = mAPI.GetAssetInfo()
aiStr = "<hr><b>assetInfo</b> for %s:" % model.GetName()
if assetInfo and len(assetInfo) > 0:
specs = model.GetPrimStack()
name, time, owner = GetAssetCreationTime(specs,
mAPI.GetAssetIdentifier())
for key, value in assetInfo.items():
aiStr += "<br> -- <em>%s</em> : %s" % (key, _HTMLEscape(str(value)))
aiStr += "<br><em><small>%s created on %s by %s</small></em>" % \
(_HTMLEscape(name), _HTMLEscape(time),
_HTMLEscape(owner))
else:
aiStr += "<br><small><em>No assetInfo!</em></small>"
# variantSets are by no means required/expected, so if there
# are none, don't bother to declare so.
mVarSets = model.GetVariantSets()
setNames = mVarSets.GetNames()
if len(setNames) > 0:
vsStr = "<hr><b>variantSets</b> on %s:" % model.GetName()
for name in setNames:
sel = mVarSets.GetVariantSelection(name)
vsStr += "<br> -- <em>%s</em> = %s" % (name, sel)
else:
headerStr = _MakeModelRelativePath(path, None)
# Property info: advise about rare visibility and purpose conditions
img = UsdGeom.Imageable(prim)
propertyStr = "<hr><b>Property Summary for %s '%s':</b>" % \
(prim.GetTypeName(), prim.GetName())
# Now cherry pick "important" attrs... could do more, here
if img:
if img.GetVisibilityAttr().ValueMightBeTimeVarying():
propertyStr += "<br> -- <em>visibility</em> varies over time"
purpose = img.GetPurposeAttr().Get()
inheritedPurpose = img.ComputePurpose()
if inheritedPurpose != UsdGeom.Tokens.default_:
propertyStr += "<br> -- <em>purpose</em> is <b>%s</b>%s " %\
(inheritedPurpose, "" if purpose == inheritedPurpose \
else ", <small>(inherited)</small>")
gprim = UsdGeom.Gprim(prim)
if gprim:
ds = gprim.GetDoubleSidedAttr().Get()
orient = gprim.GetOrientationAttr().Get()
propertyStr += "<br> -- <em>doubleSided</em> = %s" % \
( "true" if ds else "false")
propertyStr += "<br> -- <em>orientation</em> = %s" % orient
ptBased = UsdGeom.PointBased(prim)
if ptBased:
# XXX WBN to not have to read points in to get array size
# XXX2 Should try to determine varying topology
points = ptBased.GetPointsAttr().Get(
self._dataModel.currentFrame)
propertyStr += "<br> -- %d points" % len(points)
mesh = UsdGeom.Mesh(prim)
if mesh:
propertyStr += "<br> -- <em>subdivisionScheme</em> = %s" %\
mesh.GetSubdivisionSchemeAttr().Get()
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
pi = UsdGeom.PointInstancer(topLevelPrim)
if pi:
indices = pi.GetProtoIndicesAttr().Get(
self._dataModel.currentFrame)
propertyStr += "<br> -- <em>%d instances</em>" % len(indices)
protos = pi.GetPrototypesRel().GetForwardedTargets()
propertyStr += "<br> -- <em>%d unique prototypes</em>" % len(protos)
if topLevelInstanceIndex >= 0 and topLevelInstanceIndex < len(indices):
protoIndex = indices[topLevelInstanceIndex]
if protoIndex < len(protos):
currProtoPath = protos[protoIndex]
# If, as is common, proto is beneath the PI,
# strip the PI's prefix for display
if currProtoPath.HasPrefix(path):
currProtoPath = currProtoPath.MakeRelativePath(path)
propertyStr += "<br> -- <em>instance of prototype <%s></em>" % str(currProtoPath)
# Material info - this IS expected
materialStr = "<hr><b>Material assignment:</b>"
materialAssigns = {}
materialAssigns['generic'] = (genericMat, genericBindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.allPurpose)
materialAssigns[UsdShade.Tokens.preview] = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.preview)
materialAssigns[UsdShade.Tokens.full] = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.full)
gotValidMaterial = False
for purpose, materialAssign in materialAssigns.items():
(material, bindingRel) = materialAssign
if not material:
continue
gotValidMaterial = True
# skip specific purpose binding display if it is the same
# as the generic binding.
if purpose != 'generic' and bindingRel == genericBindingRel:
continue
# if the material is in the same model, make path
# model-relative
materialStr += "<br><em>%s</em>: %s" % (purpose,
_MakeModelRelativePath(material.GetPath(), model))
bindingRelPath = _MakeModelRelativePath(
bindingRel.GetPath(), model)
materialStr += "<br><small><em>Material binding "\
"relationship: %s</em></small>" % str(bindingRelPath)
if not gotValidMaterial:
materialStr += "<small><em>No assigned Material!</em></small>"
# Instance / master info, if this prim is a native instance, else
# instance index/id if it's from a PointInstancer
instanceStr = ""
if prim.IsInstance():
instanceStr = "<hr><b>Instancing:</b><br>"
instanceStr += "<nobr><small><em>Instance of master:</em></small> %s</nobr>" % \
str(prim.GetMaster().GetPath())
elif topLevelInstanceIndex != -1:
instanceStr = "<hr><b>Instance Id:</b> %d" % topLevelInstanceIndex
# Then put it all together
tip = headerStr + propertyStr + materialStr + instanceStr + aiStr + vsStr
else:
tip = ""
QtWidgets.QToolTip.showText(QtGui.QCursor.pos(), tip, self._stageView)
def processNavKeyEvent(self, kpEvent):
# This method is a standin for a hotkey processor... for now greatly
# limited in scope, as we mostly use Qt's builtin hotkey dispatch.
# Since we want navigation keys to be hover-context-sensitive, we
# cannot use the native mechanism.
key = kpEvent.key()
if key == QtCore.Qt.Key_Right:
self._advanceFrame()
return True
elif key == QtCore.Qt.Key_Left:
self._retreatFrame()
return True
elif key == KeyboardShortcuts.FramingKey:
self._frameSelection()
return False
def _viewSettingChanged(self):
self._refreshViewMenubar()
self._displayPurposeChanged()
self._HUDInfoChanged()
def _refreshViewMenubar(self):
"""Refresh the menubar actions associated with a view setting. This
includes updating checked/unchecked and enabled/disabled states for
actions and submenus to match the values in the ViewSettingsDataModel.
"""
self._refreshRenderModeMenu()
self._refreshColorCorrectionModeMenu()
self._refreshPickModeMenu()
self._refreshComplexityMenu()
self._refreshBBoxMenu()
self._refreshLightsMenu()
self._refreshClearColorsMenu()
self._refreshCameraMenu()
self._refreshCameraGuidesMenu()
self._refreshCameraMaskMenu()
self._refreshCameraReticlesMenu()
self._refreshDisplayPurposesMenu()
self._refreshViewMenu()
self._refreshHUDMenu()
self._refreshShowPrimMenu()
self._refreshRedrawOnScrub()
self._refreshRolloverPrimInfoMenu()
self._refreshSelectionHighlightingMenu()
self._refreshSelectionHighlightColorMenu()
def _refreshRenderModeMenu(self):
for action in self._renderModeActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.renderMode)
def _refreshColorCorrectionModeMenu(self):
for action in self._colorCorrectionActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.colorCorrectionMode)
def _refreshPickModeMenu(self):
for action in self._pickModeActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.pickMode)
def _refreshComplexityMenu(self):
complexityName = self._dataModel.viewSettings.complexity.name
for action in self._complexityActions:
action.setChecked(str(action.text()) == complexityName)
def _refreshBBoxMenu(self):
self._ui.showBBoxes.setChecked(self._dataModel.viewSettings.showBBoxes)
self._ui.showAABBox.setChecked(self._dataModel.viewSettings.showAABBox)
self._ui.showOBBox.setChecked(self._dataModel.viewSettings.showOBBox)
self._ui.showBBoxPlayback.setChecked(
self._dataModel.viewSettings.showBBoxPlayback)
def _refreshLightsMenu(self):
# lighting is not activated until a shaded mode is selected
self._ui.menuLights.setEnabled(
self._dataModel.viewSettings.renderMode in ShadedRenderModes)
self._ui.actionAmbient_Only.setChecked(
self._dataModel.viewSettings.ambientLightOnly)
self._ui.actionDomeLight.setChecked(
self._dataModel.viewSettings.domeLightEnabled)
def _refreshClearColorsMenu(self):
clearColorText = self._dataModel.viewSettings.clearColorText
for action in self._clearColorActions:
action.setChecked(str(action.text()) == clearColorText)
def getActiveCamera(self):
return self._dataModel.viewSettings.cameraPrim
def _refreshCameraMenu(self):
cameraPath = self._dataModel.viewSettings.cameraPath
for action in self._ui.menuCamera.actions():
action.setChecked(action.data() == cameraPath)
def _refreshCameraGuidesMenu(self):
self._ui.actionDisplay_Camera_Oracles.setChecked(
self._dataModel.viewSettings.displayCameraOracles)
self._ui.actionCameraMask_Outline.setChecked(
self._dataModel.viewSettings.showMask_Outline)
def _refreshCameraMaskMenu(self):
viewSettings = self._dataModel.viewSettings
self._ui.actionCameraMask_Full.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.FULL)
self._ui.actionCameraMask_Partial.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.PARTIAL)
self._ui.actionCameraMask_None.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.NONE)
def _refreshCameraReticlesMenu(self):
self._ui.actionCameraReticles_Inside.setChecked(
self._dataModel.viewSettings.showReticles_Inside)
self._ui.actionCameraReticles_Outside.setChecked(
self._dataModel.viewSettings.showReticles_Outside)
def _refreshDisplayPurposesMenu(self):
self._ui.actionDisplay_Guide.setChecked(
self._dataModel.viewSettings.displayGuide)
self._ui.actionDisplay_Proxy.setChecked(
self._dataModel.viewSettings.displayProxy)
self._ui.actionDisplay_Render.setChecked(
self._dataModel.viewSettings.displayRender)
def _refreshViewMenu(self):
self._ui.actionEnable_Scene_Materials.setChecked(
self._dataModel.viewSettings.enableSceneMaterials)
self._ui.actionDisplay_PrimId.setChecked(
self._dataModel.viewSettings.displayPrimId)
self._ui.actionCull_Backfaces.setChecked(
self._dataModel.viewSettings.cullBackfaces)
self._ui.actionAuto_Compute_Clipping_Planes.setChecked(
self._dataModel.viewSettings.autoComputeClippingPlanes)
def _refreshHUDMenu(self):
self._ui.actionHUD.setChecked(self._dataModel.viewSettings.showHUD)
self._ui.actionHUD_Info.setChecked(
self._dataModel.viewSettings.showHUD_Info)
self._ui.actionHUD_Complexity.setChecked(
self._dataModel.viewSettings.showHUD_Complexity)
self._ui.actionHUD_Performance.setChecked(
self._dataModel.viewSettings.showHUD_Performance)
self._ui.actionHUD_GPUstats.setChecked(
self._dataModel.viewSettings.showHUD_GPUstats)
def _refreshShowPrimMenu(self):
self._ui.actionShow_Inactive_Prims.setChecked(
self._dataModel.viewSettings.showInactivePrims)
self._ui.actionShow_All_Master_Prims.setChecked(
self._dataModel.viewSettings.showAllMasterPrims)
self._ui.actionShow_Undefined_Prims.setChecked(
self._dataModel.viewSettings.showUndefinedPrims)
self._ui.actionShow_Abstract_Prims.setChecked(
self._dataModel.viewSettings.showAbstractPrims)
def _refreshRedrawOnScrub(self):
self._ui.redrawOnScrub.setChecked(
self._dataModel.viewSettings.redrawOnScrub)
def _refreshRolloverPrimInfoMenu(self):
self._ui.actionRollover_Prim_Info.setChecked(
self._dataModel.viewSettings.rolloverPrimInfo)
def _refreshSelectionHighlightingMenu(self):
for action in self._selHighlightActions:
action.setChecked(
str(action.text())
== self._dataModel.viewSettings.selHighlightMode)
def _refreshSelectionHighlightColorMenu(self):
for action in self._selHighlightColorActions:
action.setChecked(
str(action.text())
== self._dataModel.viewSettings.highlightColorName)
def _displayPurposeChanged(self):
self._updatePropertyView()
if self._stageView:
self._stageView.updateBboxPurposes()
self._stageView.updateView()
def _HUDInfoChanged(self):
"""Called when a HUD setting that requires info refresh has changed."""
if self._isHUDVisible():
self._updateHUDPrimStats()
self._updateHUDGeomCounts()
def _onPrimsChanged(self, primsChange, propertiesChange):
"""Called when prims in the USD stage have changed."""
from .rootDataModel import ChangeNotice
self._updateForStageChanges(
hasPrimResync=(primsChange==ChangeNotice.RESYNC))
| 216,121 | Python | 42.138124 | 129 | 0.607174 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/settings2.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import os, sys, json
class _StateProp(object):
"""Defines a state property on a StateSource object."""
def __init__(self, name, default, propType, validator):
self.name = name
self.default = default
self.propType = propType
self.validator = validator
class StateSource(object):
"""An object which has some savable application state."""
def __init__(self, parent, name):
self._parentStateSource = parent
self._childStateSources = dict()
self._stateSourceName = name
self._stateSourceProperties = dict()
# Register child source with the parent.
if self._parentStateSource is not None:
self._parentStateSource._registerChildStateSource(self)
def _registerChildStateSource(self, child):
"""Registers a child StateSource with this source object."""
self._childStateSources[child._stateSourceName] = child
def _getState(self):
"""Get this source's state dict from its parent source."""
if self._parentStateSource is None:
return dict()
else:
return self._parentStateSource._getChildState(self._stateSourceName)
def _getChildState(self, childName):
"""Get a child source's state dict. This method guarantees that a dict
will be return but does not guarantee anything about the contents of
the dict.
"""
state = self._getState()
if childName in state:
childState = state[childName]
# Child state could be loaded from file as any JSON-serializable
# type (int, str, etc.). Only return it if it is a dict. Otherwise,
# fallback to empty dict.
if isinstance(childState, dict):
return childState
# Create a new state dict for the child and save it in this source's
# state dict.
childState = dict()
state[childName] = childState
return childState
def _typeCheck(self, value, prop):
"""Validate a value against a StateProp."""
# Make sure the value has the correct type.
valueType = type(value)
if valueType is not prop.propType:
if sys.version_info.major >= 3:
str_types = [str]
else:
str_types = [str, unicode]
if valueType is int and prop.propType is float:
pass # ints are valid for float types.
elif prop.propType in str_types and valueType in str_types:
pass # str and unicode can be used interchangeably.
else:
print("Value {} has type {} but state property {} has type {}.".format(
repr(value), valueType, repr(prop.name), prop.propType),
file=sys.stderr)
print(" Using default value {}.".format(repr(prop.default)),
file=sys.stderr)
return False
# Make sure value passes custom validation. Otherwise, use default value.
if prop.validator(value):
return True
else:
print("Value {} did not pass custom validation for state property {}.".format(
repr(value), repr(prop.name)), file=sys.stderr)
print(" Using default value {}.".format(repr(prop.default)),
file=sys.stderr)
return False
def _saveState(self):
"""Saves the source's state to the settings object's state buffer."""
newState = dict()
# Save state properties.
self.onSaveState(newState)
# Validate state properties.
for name, value in tuple(newState.items()):
if name not in self._stateSourceProperties:
print("State property {} not defined. It will be removed.".format(
repr(name)), file=sys.stderr)
del newState[name]
prop = self._stateSourceProperties[name]
if self._typeCheck(value, prop):
newState[name] = value
else:
newState[name] = prop.default
# Make sure no state properties were forgotten.
for prop in self._stateSourceProperties.values():
if prop.name not in newState:
print("State property {} not saved.".format(repr(prop.name)),
file=sys.stderr)
# Update the real state dict with the new state. This preserves unused
# data loaded from the state file.
self._getState().update(newState)
# Save all child states.
for child in self._childStateSources.values():
child._saveState()
def stateProperty(self, name, default, propType=None, validator=lambda value: True):
"""Validates and creates a new StateProp for this source. The property's
value is returned so this method can be used during StateSource
initialization."""
# Make sure there are no conflicting state properties.
if name in self._stateSourceProperties:
raise RuntimeError("State property name {} already in use.".format(
repr(name)))
# Grab state property type from default value if it was not defined.
if propType is None:
propType = type(default)
# Make sure default value is valid.
if not isinstance(default, propType):
raise RuntimeError("Default value {} does not match type {}.".format(
repr(default), repr(propType)))
if not validator(default):
raise RuntimeError("Default value {} does not pass custom validation "
"for state property {}.".format(repr(default), repr(name)))
prop = _StateProp(name, default, propType, validator)
self._stateSourceProperties[name] = prop
# Load the value from the state dict and validate it.
state = self._getState()
value = state.get(name, default)
if self._typeCheck(value, prop):
return value
else:
return prop.default
def onSaveState(self, state):
"""Save the source's state properties to a dict."""
raise NotImplementedError
class Settings(StateSource):
"""An object which encapsulates saving and loading of application state to
a state file. When created, it loads state from a state file and stores it
in a buffer. Its children sources can fetch their piece of state from the
buffer. On save, this object tells its children to save their current
states, then saves the buffer back to the state file.
"""
def __init__(self, version, stateFilePath=None):
# Settings should be the only StateSource with no parent or name.
StateSource.__init__(self, None, None)
self._version = version
self._stateFilePath = stateFilePath
self._versionsStateBuffer = None
self._stateBuffer = None
self._isEphemeral = (self._stateFilePath is None)
self._loadState()
def _loadState(self):
"""Loads and returns application state from a state file. If the file is
not found, contains invalid JSON, does not contain a dictionary, an
empty state is returned instead.
"""
# Load the dict containing all versions of app state.
if not self._isEphemeral:
try:
with open(self._stateFilePath, "r") as fp:
self._versionsStateBuffer = json.load(fp)
except IOError as e:
if os.path.isfile(self._stateFilePath):
print("Error opening state file: " + str(e), file=sys.stderr)
else:
print("State file not found, a new one will be created.",
file=sys.stderr)
except ValueError:
print("State file contained invalid JSON. Please fix or delete " +
"it. Default settings will be used for this instance of " +
"USDView, but will not be saved.", file=sys.stderr)
self._isEphemeral = True
# Make sure JSON returned a dict.
if not isinstance(self._versionsStateBuffer, dict):
self._versionsStateBuffer = dict()
# Load the correct version of the state dict.
self._stateBuffer = self._versionsStateBuffer.get(self._version, None)
if not isinstance(self._stateBuffer, dict):
self._stateBuffer = dict()
self._versionsStateBuffer[self._version] = self._stateBuffer
# overrides StateSource._getState
def _getState(self):
"""Gets the buffered state rather than asking its parent for its state.
"""
return self._stateBuffer
def save(self):
"""Inform all children to save their states, then write the state buffer
back to the state file.
"""
if not self._isEphemeral:
self._saveState()
try:
with open(self._stateFilePath, "w") as fp:
json.dump(self._versionsStateBuffer, fp,
indent=2, separators=(",", ": "))
except IOError as e:
print("Could not save state file: " + str(e), file=sys.stderr)
def onSaveState(self, state):
"""Settings object has no state properties."""
pass
| 10,551 | Python | 39.274809 | 90 | 0.610748 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/variantComboBox.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .common import Timer
class VariantComboBox(QtWidgets.QComboBox):
def __init__(self, parent, prim, variantSetName, mainWindow):
QtWidgets.QComboBox.__init__(self, parent)
self.prim = prim
self.variantSetName = variantSetName
def updateVariantSelection(self, index, printTiming):
variantSet = self.prim.GetVariantSet(self.variantSetName)
currentVariantSelection = variantSet.GetVariantSelection()
newVariantSelection = str(self.currentText())
if currentVariantSelection != newVariantSelection:
with Timer() as t:
variantSet.SetVariantSelection(newVariantSelection)
if printTiming:
t.PrintTime("change variantSet %s to %s" %
(variantSet.GetName(), newVariantSelection))
| 1,925 | Python | 40.869564 | 74 | 0.721039 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/freeCamera.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from math import atan, radians as rad
from pxr import Gf, Tf
from .qt import QtCore
from .common import DEBUG_CLIPPING
# FreeCamera inherits from QObject only so that it can send signals...
# which is really a pretty nice, easy to use notification system.
class FreeCamera(QtCore.QObject):
# Allows FreeCamera owner to act when the camera's relationship to
# its viewed content changes. For instance, to compute the value
# to supply for setClosestVisibleDistFromPoint()
signalFrustumChanged = QtCore.Signal()
defaultNear = 1
defaultFar = 2000000
# Experimentally on Nvidia M6000, if Far/Near is greater than this,
# then geometry in the back half of the volume will disappear
maxSafeZResolution = 1e6
# Experimentally on Nvidia M6000, if Far/Near is greater than this,
# then we will often see Z-fighting artifacts even for geometry that
# is close to camera, when rendering for picking
maxGoodZResolution = 5e4
def __init__(self, isZUp, fov=60.0):
"""FreeCamera can be either a Z up or Y up camera, based on 'zUp'"""
super(FreeCamera, self).__init__()
self._camera = Gf.Camera()
self._camera.SetPerspectiveFromAspectRatioAndFieldOfView(
1.0, fov, Gf.Camera.FOVVertical)
self._overrideNear = None
self._overrideFar = None
self.resetClippingPlanes()
self._isZUp = isZUp
self._cameraTransformDirty = True
self._rotTheta = 0
self._rotPhi = 0
self._rotPsi = 0
self._center = Gf.Vec3d(0,0,0)
self._dist = 100
self._camera.focusDistance = self._dist
self._closestVisibleDist = None
self._lastFramedDist = None
self._lastFramedClosestDist = None
self._selSize = 10
if isZUp:
# This is also Gf.Camera.Y_UP_TO_Z_UP_MATRIX
self._YZUpMatrix = Gf.Matrix4d().SetRotate(
Gf.Rotation(Gf.Vec3d.XAxis(), -90))
self._YZUpInvMatrix = self._YZUpMatrix.GetInverse()
else:
self._YZUpMatrix = Gf.Matrix4d(1.0)
self._YZUpInvMatrix = Gf.Matrix4d(1.0)
# Why a clone() method vs copy.deepcopy()ing the FreeCamera ?
# 1) Several of the Gf classes are not python-picklable (requirement of
# deepcopy), nor is GfCamera. Adding that infrastructure for this
# single client seems weighty.
# 2) We could make FreeCamera itself be picklable... that solution would
# require twice as much code as clone(). If we wind up extracting
# FreeCamera to be a more general building block, it may be worth it,
# and clone() would transition to __getstate__().
def clone(self):
clone = FreeCamera(self._isZUp)
clone._camera = Gf.Camera(self._camera)
# skipping stereo attrs for now
clone._rotTheta = self._rotTheta
clone._rotPhi = self._rotPhi
clone._rotPsi = self._rotPsi
clone._center = Gf.Vec3d(self._center)
clone._dist = self._dist
clone._closestVisibleDist = self._closestVisibleDist
clone._lastFramedClosestDist = self._lastFramedClosestDist
clone._lastFramedDist = self._lastFramedDist
clone._selSize = self._selSize
clone._overrideNear = self._overrideNear
clone._overrideFar = self._overrideFar
clone._YZUpMatrix = Gf.Matrix4d(self._YZUpMatrix)
clone._YZUpInvMatrix = Gf.Matrix4d(self._YZUpInvMatrix)
return clone
def _pushToCameraTransform(self):
"""
Updates the camera's transform matrix, that is, the matrix that brings
the camera to the origin, with the camera view pointing down:
+Y if this is a Zup camera, or
-Z if this is a Yup camera .
"""
if not self._cameraTransformDirty:
return
def RotMatrix(vec, angle):
return Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(vec, angle))
# self._YZUpInvMatrix influences the behavior about how the
# FreeCamera will tumble. It is the identity or a rotation about the
# x-Axis.
self._camera.transform = (
Gf.Matrix4d().SetTranslate(Gf.Vec3d.ZAxis() * self.dist) *
RotMatrix(Gf.Vec3d.ZAxis(), -self._rotPsi) *
RotMatrix(Gf.Vec3d.XAxis(), -self._rotPhi) *
RotMatrix(Gf.Vec3d.YAxis(), -self._rotTheta) *
self._YZUpInvMatrix *
Gf.Matrix4d().SetTranslate(self.center))
self._camera.focusDistance = self.dist
self._cameraTransformDirty = False
def _pullFromCameraTransform(self):
"""
Updates parameters (center, rotTheta, etc.) from the camera transform.
"""
# reads the transform set on the camera and updates all the other
# parameters. This is the inverse of _pushToCameraTransform
cam_transform = self._camera.transform
dist = self._camera.focusDistance
frustum = self._camera.frustum
cam_pos = frustum.position
cam_axis = frustum.ComputeViewDirection()
# Compute translational parts
self._dist = dist
self._selSize = dist / 10.0
self._center = cam_pos + dist * cam_axis
# self._YZUpMatrix influences the behavior about how the
# FreeCamera will tumble. It is the identity or a rotation about the
# x-Axis.
# Compute rotational part
transform = cam_transform * self._YZUpMatrix
transform.Orthonormalize()
rotation = transform.ExtractRotation()
# Decompose and set angles
self._rotTheta, self._rotPhi, self._rotPsi = -rotation.Decompose(
Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis(), Gf.Vec3d.ZAxis())
self._cameraTransformDirty = True
def _rangeOfBoxAlongRay(self, camRay, bbox, debugClipping=False):
maxDist = -float('inf')
minDist = float('inf')
boxRange = bbox.GetRange()
boxXform = bbox.GetMatrix()
for i in range (8):
# for each corner of the bounding box, transform to world
# space and project
point = boxXform.Transform(boxRange.GetCorner(i))
pointDist = camRay.FindClosestPoint(point)[1]
# find the projection of that point of the camera ray
# and find the farthest and closest point.
if pointDist > maxDist:
maxDist = pointDist
if pointDist < minDist:
minDist = pointDist
if debugClipping:
print("Projected bounds near/far: %f, %f" % (minDist, maxDist))
# if part of the bbox is behind the ray origin (i.e. camera),
# we clamp minDist to be positive. Otherwise, reduce minDist by a bit
# so that geometry at exactly the edge of the bounds won't be clipped -
# do the same for maxDist, also!
if minDist < FreeCamera.defaultNear:
minDist = FreeCamera.defaultNear
else:
minDist *= 0.99
maxDist *= 1.01
if debugClipping:
print("Contracted bounds near/far: %f, %f" % (minDist, maxDist))
return minDist, maxDist
def setClippingPlanes(self, stageBBox):
'''Computes and sets automatic clipping plane distances using the
camera's position and orientation, the bouding box
surrounding the stage, and the distance to the closest rendered
object in the central view of the camera (closestVisibleDist).
If either of the "override" clipping attributes are not None,
we use those instead'''
debugClipping = Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING)
# If the scene bounding box is empty, or we are fully on manual
# override, then just initialize to defaults.
if stageBBox.GetRange().IsEmpty() or \
(self._overrideNear and self._overrideFar) :
computedNear, computedFar = FreeCamera.defaultNear, FreeCamera.defaultFar
else:
# The problem: We want to include in the camera frustum all the
# geometry the viewer should be able to see, i.e. everything within
# the inifinite frustum starting at distance epsilon from the
# camera itself. However, the further the imageable geometry is
# from the near-clipping plane, the less depth precision we will
# have to resolve nearly colinear/incident polygons (which we get
# especially with any doubleSided geometry). We can run into such
# situations astonishingly easily with large sets when we are
# focussing in on just a part of a set that spans 10^5 units or
# more.
#
# Our solution: Begin by projecting the endpoints of the imageable
# world's bounds onto the ray piercing the center of the camera
# frustum, and take the near/far clipping distances from its
# extent, clamping at a positive value for near. To address the
# z-buffer precision issue, we rely on someone having told us how
# close the closest imageable geometry actually is to the camera,
# by having called setClosestVisibleDistFromPoint(). This gives us
# the most liberal near distance we can use and not clip the
# geometry we are looking at. We actually choose some fraction of
# that distance instead, because we do not expect the someone to
# recompute the closest point with every camera manipulation, as
# it can be expensive (we do emit signalFrustumChanged to notify
# them, however). We only use this if the current range of the
# bbox-based frustum will have precision issues.
frustum = self._camera.frustum
camPos = frustum.position
camRay = Gf.Ray(camPos, frustum.ComputeViewDirection())
computedNear, computedFar = self._rangeOfBoxAlongRay(camRay,
stageBBox,
debugClipping)
precisionNear = computedFar / FreeCamera.maxGoodZResolution
if debugClipping:
print("Proposed near for precision: {}, closestDist: {}"\
.format(precisionNear, self._closestVisibleDist))
if self._closestVisibleDist:
# Because of our concern about orbit/truck causing
# clipping, make sure we don't go closer than half the
# distance to the closest visible point
halfClose = self._closestVisibleDist / 2.0
if self._closestVisibleDist < self._lastFramedClosestDist:
# This can happen if we have zoomed in closer since
# the last time setClosestVisibleDistFromPoint() was called.
# Clamp to precisionNear, which gives a balance between
# clipping as we zoom in, vs bad z-fighting as we zoom in.
# See AdjustDistance() for comment about better solution.
halfClose = max(precisionNear, halfClose, computedNear)
if debugClipping:
print("ADJUSTING: Accounting for zoom-in")
if halfClose < computedNear:
# If there's stuff very very close to the camera, it
# may have been clipped by computedNear. Get it back!
computedNear = halfClose
if debugClipping:
print("ADJUSTING: closestDist was closer than bboxNear")
elif precisionNear > computedNear:
computedNear = min((precisionNear + halfClose) / 2.0,
halfClose)
if debugClipping:
print("ADJUSTING: gaining precision by pushing out")
near = self._overrideNear or computedNear
far = self._overrideFar or computedFar
# Make sure far is greater than near
far = max(near+1, far)
if debugClipping:
print("***Final Near/Far: {}, {}".format(near, far))
self._camera.clippingRange = Gf.Range1f(near, far)
def computeGfCamera(self, stageBBox, autoClip=False):
"""Makes sure the FreeCamera's computed parameters are up-to-date, and
returns the GfCamera object. If 'autoClip' is True, then compute
"optimal" positions for the near/far clipping planes based on the
current closestVisibleDist, in order to maximize Z-buffer resolution"""
self._pushToCameraTransform()
if autoClip:
self.setClippingPlanes(stageBBox)
else:
self.resetClippingPlanes()
return self._camera
def resetClippingPlanes(self):
"""Set near and far back to their uncomputed defaults."""
near = self._overrideNear or FreeCamera.defaultNear
far = self._overrideFar or FreeCamera.defaultFar
self._camera.clippingRange = Gf.Range1f(near, far)
def frameSelection(self, selBBox, frameFit):
# needs to be recomputed
self._closestVisibleDist = None
self.center = selBBox.ComputeCentroid()
selRange = selBBox.ComputeAlignedRange()
self._selSize = max(*selRange.GetSize())
if self.orthographic:
self.fov = self._selSize * frameFit
self.dist = self._selSize + FreeCamera.defaultNear
else:
halfFov = self.fov*0.5 or 0.5 # don't divide by zero
lengthToFit = self._selSize * frameFit * 0.5
self.dist = lengthToFit / atan(rad(halfFov))
# Very small objects that fill out their bounding boxes (like cubes)
# may well pierce our 1 unit default near-clipping plane. Make sure
# that doesn't happen.
if self.dist < FreeCamera.defaultNear + self._selSize * 0.5:
self.dist = FreeCamera.defaultNear + lengthToFit
def setClosestVisibleDistFromPoint(self, point):
frustum = self._camera.frustum
camPos = frustum.position
camRay = Gf.Ray(camPos, frustum.ComputeViewDirection())
self._closestVisibleDist = camRay.FindClosestPoint(point)[1]
self._lastFramedDist = self.dist
self._lastFramedClosestDist = self._closestVisibleDist
if Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING):
print("Resetting closest distance to {}; CameraPos: {}, closestPoint: {}".format(self._closestVisibleDist, camPos, point))
def ComputePixelsToWorldFactor(self, viewportHeight):
'''Computes the ratio that converts pixel distance into world units.
It treats the pixel distances as if they were projected to a plane going
through the camera center.'''
self._pushToCameraTransform()
if self.orthographic:
return self.fov / viewportHeight
else:
frustumHeight = self._camera.frustum.window.GetSize()[1]
return frustumHeight * self._dist / viewportHeight
def Tumble(self, dTheta, dPhi):
''' Tumbles the camera around the center point by (dTheta, dPhi) degrees. '''
self._rotTheta += dTheta
self._rotPhi += dPhi
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def AdjustDistance(self, scaleFactor):
'''Scales the distance of the freeCamera from it's center typically by
scaleFactor unless it puts the camera into a "stuck" state.'''
# When dist gets very small, you can get stuck and not be able to
# zoom back out, if you just keep multiplying. Switch to addition
# in that case, choosing an incr that works for the scale of the
# framed geometry.
if scaleFactor > 1 and self.dist < 2:
selBasedIncr = self._selSize / 25.0
scaleFactor -= 1.0
self.dist += min(selBasedIncr, scaleFactor)
else:
self.dist *= scaleFactor
# Make use of our knowledge that we are changing distance to camera
# to also adjust _closestVisibleDist to keep it useful. Make sure
# not to recede farther than the last *computed* closeDist, since that
# will generally cause unwanted clipping of close objects.
# XXX: This heuristic does a good job of preventing undesirable
# clipping as we zoom in and out, but sacrifices the z-buffer
# precision we worked hard to get. If Hd/UsdImaging could cheaply
# provide us with the closest-point from the last-rendered image,
# we could use it safely here to update _closestVisibleDist much
# more accurately than this calculation.
if self._closestVisibleDist:
if self.dist > self._lastFramedDist:
self._closestVisibleDist = self._lastFramedClosestDist
else:
self._closestVisibleDist = \
self._lastFramedClosestDist - \
self._lastFramedDist + \
self.dist
def Truck(self, deltaRight, deltaUp):
''' Moves the camera by (deltaRight, deltaUp) in worldspace coordinates.
This is similar to a camera Truck/Pedestal.
'''
# need to update the camera transform before we access the frustum
self._pushToCameraTransform()
frustum = self._camera.frustum
cam_up = frustum.ComputeUpVector()
cam_right = Gf.Cross(frustum.ComputeViewDirection(), cam_up)
self._center += (deltaRight * cam_right + deltaUp * cam_up)
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def PanTilt(self, dPan, dTilt):
''' Rotates the camera around the current camera base (approx. the film
plane). Both parameters are in degrees.
This moves the center point that we normally tumble around.
This is similar to a camera Pan/Tilt.
'''
self._camera.transform = (
Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d.XAxis(), dTilt)) *
Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d.YAxis(), dPan)) *
self._camera.transform)
self._pullFromCameraTransform()
# When we Pan/Tilt, we don't want to roll the camera so we just zero it
# out here.
self._rotPsi = 0.0
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def Walk(self, dForward, dRight):
''' Specialized camera movement that moves it on the "horizontal" plane
'''
# need to update the camera transform before we access the frustum
self._pushToCameraTransform()
frustum = self._camera.frustum
cam_up = frustum.ComputeUpVector().GetNormalized()
cam_forward = frustum.ComputeViewDirection().GetNormalized()
cam_right = Gf.Cross(cam_forward, cam_up)
delta = dForward * cam_forward + dRight * cam_right
self._center += delta
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@staticmethod
def FromGfCamera(gfCamera, isZUp):
self = FreeCamera(isZUp)
self._camera = gfCamera
self._pullFromCameraTransform()
return self
@property
def rotTheta(self):
return self._rotTheta
@rotTheta.setter
def rotTheta(self, value):
self._rotTheta = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def rotPhi(self):
return self._rotPhi
@rotPhi.setter
def rotPhi(self, value):
self._rotPhi = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def center(self):
return self._center
@center.setter
def center(self, value):
self._center = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def dist(self):
return self._dist
@dist.setter
def dist(self, value):
self._dist = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def orthographic(self):
return self._camera.projection == Gf.Camera.Orthographic
@orthographic.setter
def orthographic(self, orthographic):
if orthographic:
self._camera.projection = Gf.Camera.Orthographic
else:
self._camera.projection = Gf.Camera.Perspective
self.signalFrustumChanged.emit()
@property
def fov(self):
"""The vertical field of view, in degrees, for perspective cameras.
For orthographic cameras fov is the height of the view frustum, in
world units.
"""
if self._camera.projection == Gf.Camera.Perspective:
return self._camera.GetFieldOfView(Gf.Camera.FOVVertical)
else:
return (self._camera.verticalAperture * Gf.Camera.APERTURE_UNIT)
@fov.setter
def fov(self, value):
if self._camera.projection == Gf.Camera.Perspective:
self._camera.SetPerspectiveFromAspectRatioAndFieldOfView(
self._camera.aspectRatio, value, Gf.Camera.FOVVertical)
else:
self._camera.SetOrthographicFromAspectRatioAndSize(
self._camera.aspectRatio, value, Gf.Camera.FOVVertical)
self.signalFrustumChanged.emit()
@property
def near(self):
return self._camera.clippingRange.min
@property
def far(self):
return self._camera.clippingRange.max
# no setters for near and far - one must set overrideNear/Far instead
@property
def overrideNear(self):
return self._overrideNear
@overrideNear.setter
def overrideNear(self, value):
"""To remove the override, set to None"""
self._overrideNear = value
@property
def overrideFar(self):
return self._overrideFar
@overrideFar.setter
def overrideFar(self, value):
"""To remove the override, set to None"""
self._overrideFar = value
| 23,336 | Python | 40.37766 | 134 | 0.631385 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/propertyLegend.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
""" This module provides the help dialog(also known as the property legend)
in Usdview's MainWindow. This provides a key describing the items displayed
in the property browser.
"""
from .qt import QtWidgets
from .propertyLegendUI import Ui_PropertyLegend
from .common import UIBaseColors, UIPropertyValueSourceColors, ItalicizeLabelText, PropertyViewIcons
class PropertyLegend(QtWidgets.QWidget):
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._ui = Ui_PropertyLegend()
self._ui.setupUi(self)
# The property legend always starts off collapsed.
self.setMaximumHeight(0)
self._isMinimized = True
self._iconDisplaySize = (16, 16)
graphicsScene = QtWidgets.QGraphicsScene()
self._ui.propertyLegendColorFallback.setScene(graphicsScene)
self._ui.propertyLegendColorDefault.setScene(graphicsScene)
self._ui.propertyLegendColorTimeSample.setScene(graphicsScene)
self._ui.propertyLegendColorNoValue.setScene(graphicsScene)
self._ui.propertyLegendColorValueClips.setScene(graphicsScene)
self._ui.propertyLegendColorCustom.setScene(graphicsScene)
# set color of attribute viewer legend boxes
self._ui.propertyLegendColorFallback.setForegroundBrush(
UIPropertyValueSourceColors.FALLBACK)
self._ui.propertyLegendColorDefault.setForegroundBrush(
UIPropertyValueSourceColors.DEFAULT)
self._ui.propertyLegendColorTimeSample.setForegroundBrush(
UIPropertyValueSourceColors.TIME_SAMPLE)
self._ui.propertyLegendColorNoValue.setForegroundBrush(
UIPropertyValueSourceColors.NONE)
self._ui.propertyLegendColorValueClips.setForegroundBrush(
UIPropertyValueSourceColors.VALUE_CLIPS)
self._ui.propertyLegendColorCustom.setForegroundBrush(
UIBaseColors.RED)
# set color of attribute viewer text items
legendTextUpdate = lambda t, c: (
('<font color=\"%s\">' % c.color().name()) + t.text() + '</font>')
timeSampleLegend = self._ui.propertyLegendLabelTimeSample
timeSampleLegend.setText(
legendTextUpdate(timeSampleLegend, UIPropertyValueSourceColors.TIME_SAMPLE))
fallbackLegend = self._ui.propertyLegendLabelFallback
fallbackLegend.setText(
legendTextUpdate(fallbackLegend, UIPropertyValueSourceColors.FALLBACK))
valueClipLegend = self._ui.propertyLegendLabelValueClips
valueClipLegend.setText(
legendTextUpdate(valueClipLegend, UIPropertyValueSourceColors.VALUE_CLIPS))
noValueLegend = self._ui.propertyLegendLabelNoValue
noValueLegend.setText(
legendTextUpdate(noValueLegend, UIPropertyValueSourceColors.NONE))
defaultLegend = self._ui.propertyLegendLabelDefault
defaultLegend.setText(
legendTextUpdate(defaultLegend, UIPropertyValueSourceColors.DEFAULT))
customLegend = self._ui.propertyLegendLabelCustom
customLegend.setText(
legendTextUpdate(customLegend, UIBaseColors.RED))
interpolatedStr = 'Interpolated'
tsLabel = self._ui.propertyLegendLabelTimeSample
tsLabel.setText(ItalicizeLabelText(tsLabel.text(), interpolatedStr))
vcLabel = self._ui.propertyLegendLabelValueClips
vcLabel.setText(ItalicizeLabelText(vcLabel.text(), interpolatedStr))
# Load up and set the icons for the property legend
self._ui.propertyLegendTargetIcon.setPixmap(
PropertyViewIcons.TARGET().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendConnIcon.setPixmap(
PropertyViewIcons.CONNECTION().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendAttrPlainIcon.setPixmap(
PropertyViewIcons.ATTRIBUTE().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendRelPlainIcon.setPixmap(
PropertyViewIcons.RELATIONSHIP().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendAttrWithConnIcon.setPixmap(
PropertyViewIcons.ATTRIBUTE_WITH_CONNECTIONS().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendRelWithTargetIcon.setPixmap(
PropertyViewIcons.RELATIONSHIP_WITH_TARGETS().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendCompIcon.setPixmap(
PropertyViewIcons.COMPOSED().pixmap(*self._iconDisplaySize))
def IsMinimized(self):
return self._isMinimized
def ToggleMinimized(self):
self._isMinimized = not self._isMinimized
def GetHeight(self):
return self.height()
def GetResetHeight(self):
return self.sizeHint().height()
| 5,787 | Python | 43.523077 | 100 | 0.724555 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/appEventFilter.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Qt Components
from .qt import QtCore, QtGui, QtWidgets
from .common import KeyboardShortcuts
class AppEventFilter(QtCore.QObject):
'''This class's primary responsibility is delivering key events to
"the right place". Given usdview's simplistic approach to shortcuts
(i.e. just uses the native Qt mechanism that does not allow for
context-sensitive keypress dispatching), we take a simplistic approach
to routing: use Qt's preferred mechanism of processing keyPresses
only in widgets that have focus; therefore, the primary behavior of this
filter is to track mouse-position in order to set widget focus, so that
widgets with keyboard navigation behaviors operate when the mouse is over
them.
We add one special behaviors on top of that, which is to turn unaccepted
left/right events into up/down events for TreeView widgets, because we
do not have a specialized class on which to provide this nice navigation
behavior.'''
# in future it would be a hotkey dispatcher instead of appController
# that we'd dispatch to, but we don't have one yet
def __init__(self, appController):
QtCore.QObject.__init__(self)
self._appController = appController
def IsNavKey(self, key, modifiers):
# Note that the arrow keys are considered part of the keypad on macOS.
return (key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right,
QtCore.Qt.Key_Up, QtCore.Qt.Key_Down,
QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown,
QtCore.Qt.Key_Home, QtCore.Qt.Key_End,
KeyboardShortcuts.FramingKey)
and modifiers in (QtCore.Qt.NoModifier,
QtCore.Qt.KeypadModifier))
def _IsWindow(self, obj):
if isinstance(obj, QtWidgets.QWidget):
return obj.isWindow()
else:
return isinstance(obj, QtGui.QWindow)
def TopLevelWindow(self, obj):
parent = obj.parent()
return obj if (self._IsWindow(obj) or not parent) else self.TopLevelWindow(parent)
def WantsNavKeys(self, w):
if not w or self._IsWindow(w):
return False
# The broader test would be QtWidgets.QAbstractItemView,
# but pragmatically, the TableViews in usdview don't really
# benefit much from keyboard navigation, and we'd rather
# allow the arrow keys drive the playhead when such widgets would
# otherwise get focus
elif isinstance(w, QtWidgets.QTreeView):
return True
else:
return self.WantsNavKeys(w.parent())
def NavigableOrTopLevelObject(self, w):
if (not w or
self._IsWindow(w) or
isinstance(w, QtWidgets.QTreeView) or
isinstance(w, QtWidgets.QDialog)):
return w
else:
parent = w.parent()
return w if not parent else self.NavigableOrTopLevelObject(parent)
def JealousFocus(self, w):
return (isinstance(w, QtWidgets.QLineEdit) or
isinstance(w, QtWidgets.QComboBox) or
isinstance(w, QtWidgets.QTextEdit) or
isinstance(w, QtWidgets.QAbstractSlider) or
isinstance(w, QtWidgets.QAbstractSpinBox) or
isinstance(w, QtWidgets.QWidget) and w.windowModality() in [QtCore.Qt.WindowModal,
QtCore.Qt.ApplicationModal])
def SetFocusFromMousePos(self, backupWidget):
# It's possible the mouse isn't over any of our windows at the time,
# in which case use the top-level window of backupWidget.
overObject = QtWidgets.QApplication.widgetAt(QtGui.QCursor.pos())
topLevelObject = self.NavigableOrTopLevelObject(overObject)
focusObject = topLevelObject if topLevelObject else self.TopLevelWindow(backupWidget)
if focusObject and isinstance(focusObject, QtWidgets.QWidget):
focusObject.setFocus()
def eventFilter(self, widget, event):
# There is currently no filtering we want to do for modal or popups
if (QtWidgets.QApplication.activeModalWidget() or
QtWidgets.QApplication.activePopupWidget()):
return False
currFocusWidget = QtWidgets.QApplication.focusWidget()
if event.type() == QtCore.QEvent.KeyPress:
key = event.key()
isNavKey = self.IsNavKey(key, event.modifiers())
if key == QtCore.Qt.Key_Escape:
# ESC resets focus based on mouse position, regardless of
# who currently holds focus
self.SetFocusFromMousePos(widget)
return True
elif currFocusWidget and self.JealousFocus(currFocusWidget):
# Don't touch if there's a greedy focus widget
return False
elif (isNavKey and self.WantsNavKeys(currFocusWidget)):
# Special handling for navigation keys:
# 1. When a "navigable" widget is focussed (a TreeView),
# route arrow keys to the widget and consume them
# 2. To make for snappier navigation, when the TreeView
# won't accept a left/right because an item is already
# opened or closed, turn it into an up/down event. It
# WBN if this behavior could be part of the widgets
# themselves, but currently, usdview does not specialize
# a class for its TreeView widgets.
event.setAccepted(False)
currFocusWidget.event(event)
accepted = event.isAccepted()
if (not accepted and
key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right)):
advance = (key == QtCore.Qt.Key_Right)
altNavKey = QtCore.Qt.Key_Down if advance else QtCore.Qt.Key_Up
subEvent = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
altNavKey,
event.modifiers())
QtWidgets.QApplication.postEvent(currFocusWidget, subEvent)
event.setAccepted(True)
return True
elif isNavKey:
if self._appController.processNavKeyEvent(event):
return True
elif (event.type() == QtCore.QEvent.MouseMove and
not self.JealousFocus(currFocusWidget)):
self.SetFocusFromMousePos(widget)
# Note we do not consume the event!
# During startup, Qt seems to queue up events on objects that may
# have disappeared by the time the eventFilter is called upon. This
# is true regardless of how late we install the eventFilter, and
# whether we process pending events before installing. So we
# silently ignore Runtime errors that occur as a result.
try:
return QtCore.QObject.eventFilter(self, widget, event)
except RuntimeError:
return True
| 8,300 | Python | 46.982659 | 104 | 0.628795 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/pythonInterpreter.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from pxr import Tf
from .qt import QtCore, QtGui, QtWidgets
from .usdviewApi import UsdviewApi
from code import InteractiveInterpreter
import os, sys, keyword
# just a handy debugging method
def _PrintToErr(line):
old = sys.stdout
sys.stdout = sys.__stderr__
print(line)
sys.stdout = old
def _Redirected(method):
def new(self, *args, **kw):
old = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = self, self, self
try:
ret = method(self, *args, **kw)
finally:
sys.stdin, sys.stdout, sys.stderr = old
return ret
return new
class _Completer(object):
"""Taken from rlcompleter, with readline references stripped, and a local
dictionary to use."""
def __init__(self, locals):
self.locals = locals
def Complete(self, text, state):
"""Return the next possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'.
"""
if state == 0:
if "." in text:
self.matches = self._AttrMatches(text)
else:
self.matches = self._GlobalMatches(text)
try:
return self.matches[state]
except IndexError:
return None
def _GlobalMatches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names
currently defines in __main__ that match.
"""
builtin_mod = None
if sys.version_info.major >= 3:
import builtins
builtin_mod = builtins
else:
import __builtin__
builtin_mod = __builtin__
import __main__
matches = set()
n = len(text)
for l in [keyword.kwlist,builtin_mod.__dict__.keys(),
__main__.__dict__.keys(), self.locals.keys()]:
for word in l:
if word[:n] == text and word != "__builtins__":
matches.add(word)
return list(matches)
def _AttrMatches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in the globals of __main__, it will be evaluated
and its attributes (as revealed by dir()) are used as possible
completions. (For class instances, class members are are also
considered.)
WARNING: this can still invoke arbitrary C code, if an object
with a __getattr__ hook is evaluated.
"""
import re, __main__
assert len(text)
# This is all a bit hacky, but that's tab-completion for you.
# Now find the last index in the text of a set of characters, and split
# the string into a prefix and suffix token there. The suffix token
# will be used for completion.
splitChars = ' )(;,+=*/-%!<>'
index = -1
for char in splitChars:
index = max(text.rfind(char), index)
if index >= len(text)-1:
return []
prefix = ''
suffix = text
if index >= 0:
prefix = text[:index+1]
suffix = text[index+1:]
m = re.match(r"([^.]+(\.[^.]+)*)\.(.*)", suffix)
if not m:
return []
expr, attr = m.group(1, 3)
try:
myobject = eval(expr, __main__.__dict__, self.locals)
except (AttributeError, NameError, SyntaxError):
return []
words = set(dir(myobject))
if hasattr(myobject,'__class__'):
words.add('__class__')
words = words.union(set(_GetClassMembers(myobject.__class__)))
words = list(words)
matches = set()
n = len(attr)
for word in words:
if word[:n] == attr and word != "__builtins__":
matches.add("%s%s.%s" % (prefix, expr, word))
return list(matches)
def _GetClassMembers(cls):
ret = dir(cls)
if hasattr(cls, '__bases__'):
for base in cls.__bases__:
ret = ret + _GetClassMembers(base)
return ret
class Interpreter(InteractiveInterpreter):
def __init__(self, locals = None):
InteractiveInterpreter.__init__(self,locals)
self._outputBrush = None
# overridden
def showsyntaxerror(self, filename = None):
self._outputBrush = QtGui.QBrush(QtGui.QColor('#ffcc63'))
try:
InteractiveInterpreter.showsyntaxerror(self, filename)
finally:
self._outputBrush = None
# overridden
def showtraceback(self):
self._outputBrush = QtGui.QBrush(QtGui.QColor('#ff0000'))
try:
InteractiveInterpreter.showtraceback(self)
finally:
self._outputBrush = None
def GetOutputBrush(self):
return self._outputBrush
# Modified from site.py in the Python distribution.
#
# This allows each interpreter editor to have it's own Helper object.
# The built-in pydoc.help grabs sys.stdin and sys.stdout the first time it
# is run and then never lets them go.
class _Helper(object):
"""Define a replacement for the built-in 'help'.
This is a wrapper around pydoc.Helper (with a twist).
"""
def __init__(self, input, output):
import pydoc
self._helper = pydoc.Helper(input, output)
def __repr__(self):
return "Type help() for interactive help, " \
"or help(object) for help about object."
def __call__(self, *args, **kwds):
return self._helper(*args, **kwds)
class Controller(QtCore.QObject):
"""
Controller is a Python shell written using Qt.
This class is a controller between Python and something which acts
like a QTextEdit.
"""
_isAnyReadlineEventLoopActive = False
def __init__(self, textEdit, initialPrompt, locals = None):
"""Constructor.
The optional 'locals' argument specifies the dictionary in
which code will be executed; it defaults to a newly created
dictionary with key "__name__" set to "__console__" and key
"__doc__" set to None.
"""
super(Controller, self).__init__()
self.interpreter = Interpreter(locals)
self.interpreter.locals['help'] = _Helper(self, self)
self.completer = _Completer(self.interpreter.locals)
# last line + last incomplete lines
self.lines = []
# flag: the interpreter needs more input to run the last lines.
self.more = 0
# history
self.history = []
self.historyPointer = None
self.historyInput = ''
# flag: readline() is being used for e.g. raw_input and input().
# We use a nested QEventloop here because we want to emulate
# modeless UI even though the readline protocol requires blocking calls.
self.readlineEventLoop = QtCore.QEventLoop(textEdit)
# interpreter prompt.
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
self.textEdit = textEdit
self.textEdit.destroyed.connect(self._TextEditDestroyedSlot)
self.textEdit.returnPressed.connect(self._ReturnPressedSlot)
self.textEdit.requestComplete.connect(self._CompleteSlot)
self.textEdit.requestNext.connect(self._NextSlot)
self.textEdit.requestPrev.connect(self._PrevSlot)
appInstance = QtWidgets.QApplication.instance()
appInstance.aboutToQuit.connect(self._QuitSlot)
self.textEdit.setTabChangesFocus(False)
self.textEdit.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
self.textEdit.setWindowTitle('Interpreter')
self.textEdit.promptLength = len(sys.ps1)
# Do initial auto-import.
self._DoAutoImports()
# interpreter banner
self.write('Python %s on %s.\n' % (sys.version, sys.platform))
# Run $PYTHONSTARTUP startup script.
startupFile = os.getenv('PYTHONSTARTUP')
if startupFile:
path = os.path.realpath(os.path.expanduser(startupFile))
if os.path.isfile(path):
self.ExecStartupFile(path)
self.write(initialPrompt)
self.write(sys.ps1)
self.SetInputStart()
def _DoAutoImports(self):
modules = Tf.ScriptModuleLoader().GetModulesDict()
for name, mod in modules.items():
self.interpreter.runsource('import ' + mod.__name__ +
' as ' + name + '\n')
@_Redirected
def ExecStartupFile(self, path):
# fix for bug 9104
# this sets __file__ in the globals dict while we are execing these
# various startup scripts, so that they can access the location from
# which they are being run.
# also, update the globals dict after we exec the file (bug 9529)
self.interpreter.runsource( 'g = dict(globals()); g["__file__"] = ' +
'"%s"; execfile("%s", g);' % (path, path) +
'del g["__file__"]; globals().update(g);' )
self.SetInputStart()
self.lines = []
def SetInputStart(self):
cursor = self.textEdit.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.textEdit.SetStartOfInput(cursor.position())
def _QuitSlot(self):
if self.readlineEventLoop:
if self.readlineEventLoop.isRunning():
self.readlineEventLoop.Exit()
def _TextEditDestroyedSlot(self):
self.readlineEventLoop = None
def _ReturnPressedSlot(self):
if self.readlineEventLoop.isRunning():
self.readlineEventLoop.Exit()
else:
self._Run()
def flush(self):
"""
Simulate stdin, stdout, and stderr.
"""
pass
def isatty(self):
"""
Simulate stdin, stdout, and stderr.
"""
return 1
def readline(self):
"""
Simulate stdin, stdout, and stderr.
"""
# XXX: Prevent more than one interpreter from blocking on a readline()
# call. Starting more than one subevent loop does not work,
# because they must exit in the order that they were created.
if Controller._isAnyReadlineEventLoopActive:
raise RuntimeError("Simultaneous readline() calls in multiple "
"interpreters are not supported.")
cursor = self.textEdit.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.SetInputStart()
self.textEdit.setTextCursor(cursor)
try:
Controller._isAnyReadlineEventLoopActive = True
# XXX TODO - Make this suck less if possible. We're invoking a
# subeventloop here, which means until we return from this
# readline we'll never get up to the main event loop. To avoid
# using a subeventloop, we would need to return control to the
# main event loop in the main thread, suspending the execution of
# the code that called into here, which also lives in the main
# thread. This essentially requires a
# co-routine/continuation-based solution capable of dealing with
# an arbitrary stack of interleaved Python/C calls (e.g. greenlet).
self.readlineEventLoop.Exec()
finally:
Controller._isAnyReadlineEventLoopActive = False
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.KeepAnchor)
txt = str(cursor.selectedText())
if len(txt) == 0:
return '\n'
else:
self.write('\n')
return txt
@_Redirected
def write(self, text):
'Simulate stdin, stdout, and stderr.'
# Move the cursor to the end of the document
self.textEdit.moveCursor(QtGui.QTextCursor.End)
# Clear any existing text format. We will explicitly set the format
# later to something else if need be.
self.textEdit.ResetCharFormat()
# Copy the textEdit's current cursor.
cursor = self.textEdit.textCursor()
try:
# If there's a designated output brush, merge that character format
# into the cursor's character format.
if self.interpreter.GetOutputBrush():
cf = QtGui.QTextCharFormat()
cf.setForeground(self.interpreter.GetOutputBrush())
cursor.mergeCharFormat(cf)
# Write the text to the textEdit.
cursor.insertText(text)
finally:
# Set the textEdit's cursor to the end of input
self.textEdit.moveCursor(QtGui.QTextCursor.End)
# get the length of a string in pixels bases on our current font
@staticmethod
def _GetStringLengthInPixels(cf, string):
font = cf.font()
fm = QtGui.QFontMetrics(font)
strlen = fm.width(string)
return strlen
def _CompleteSlot(self):
cf = self.textEdit.currentCharFormat()
line = self._GetInputLine()
cursor = self.textEdit.textCursor()
origPos = cursor.position()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.KeepAnchor)
text = str(cursor.selectedText())
tokens = text.split()
token = ''
if len(tokens) != 0:
token = tokens[-1]
completions = []
p = self.completer.Complete(token,len(completions))
while p != None:
completions.append(p)
p = self.completer.Complete(token, len(completions))
if len(completions) == 0:
return
elif len(completions) != 1:
self.write("\n")
contentsRect = self.textEdit.contentsRect()
# get the width inside the margins to eventually determine the
# number of columns in our text table based on the max string width
# of our completed words XXX TODO - paging based on widget height
width = contentsRect.right() - contentsRect.left()
maxLength = 0
for i in completions:
maxLength = max(maxLength, self._GetStringLengthInPixels(cf, i))
# pad it a bit
maxLength = maxLength + self._GetStringLengthInPixels(cf, ' ')
# how many columns can we fit on screen?
numCols = max(1,width // maxLength)
# how many rows do we need to fit our data
numRows = (len(completions) // numCols) + 1
columnWidth = QtGui.QTextLength(QtGui.QTextLength.FixedLength,
maxLength)
tableFormat = QtGui.QTextTableFormat()
tableFormat.setAlignment(QtCore.Qt.AlignLeft)
tableFormat.setCellPadding(0)
tableFormat.setCellSpacing(0)
tableFormat.setColumnWidthConstraints([columnWidth] * numCols)
tableFormat.setBorder(0)
cursor = self.textEdit.textCursor()
# Make the completion table insertion a single edit block
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.End)
textTable = cursor.insertTable(numRows, numCols, tableFormat)
completions.sort()
index = 0
completionsLength = len(completions)
for col in range(0,numCols):
for row in range(0,numRows):
cellNum = (row * numCols) + col
if (cellNum >= completionsLength):
continue
tableCell = textTable.cellAt(row,col)
cellCursor = tableCell.firstCursorPosition()
cellCursor.insertText(completions[index], cf)
index +=1
cursor.endEditBlock()
self.textEdit.setTextCursor(cursor)
self.write("\n")
if self.more:
self.write(sys.ps2)
else:
self.write(sys.ps1)
self.SetInputStart()
# complete up to the common prefix
cp = os.path.commonprefix(completions)
# make sure that we keep everything after the cursor the same as it
# was previously
i = line.rfind(token)
textToRight = line[i+len(token):]
line = line[0:i] + cp + textToRight
self.write(line)
# replace the line and reset the cursor
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput() + len(line) -
len(textToRight))
self.textEdit.setTextCursor(cursor)
else:
i = line.rfind(token)
line = line[0:i] + completions[0] + line[i+len(token):]
# replace the line and reset the cursor
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.insertText(line)
cursor.setPosition(origPos + len(completions[0]) - len(token))
self.textEdit.setTextCursor(cursor)
def _NextSlot(self):
if len(self.history):
# if we have no history pointer, we can't go forward..
if (self.historyPointer == None):
return
# if we are at the end of our history stack, we can't go forward
elif (self.historyPointer == len(self.history) - 1):
self._ClearLine()
self.write(self.historyInput)
self.historyPointer = None
return
self.historyPointer += 1
self._Recall()
def _PrevSlot(self):
if len(self.history):
# if we have no history pointer, set it to the most recent
# item in the history stack, and stash away our current input
if (self.historyPointer == None):
self.historyPointer = len(self.history)
self.historyInput = self._GetInputLine()
# if we are at the end of our history, beep
elif (self.historyPointer <= 0):
return
self.historyPointer -= 1
self._Recall()
def _IsBlank(self, txt):
return len(txt.strip()) == 0
def _GetInputLine(self):
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
txt = str(cursor.selectedText())
return txt
def _ClearLine(self):
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
@_Redirected
def _Run(self):
"""
Append the last line to the history list, let the interpreter execute
the last line(s), and clean up accounting for the interpreter results:
(1) the interpreter succeeds
(2) the interpreter fails, finds no errors and wants more line(s)
(3) the interpreter fails, finds errors and writes them to sys.stderr
"""
self.historyPointer = None
inputLine = self._GetInputLine()
if (inputLine != ""):
self.history.append(inputLine)
self.lines.append(inputLine)
source = '\n'.join(self.lines)
self.write('\n')
self.more = self.interpreter.runsource(source)
if self.more:
self.write(sys.ps2)
self.SetInputStart()
else:
self.write(sys.ps1)
self.SetInputStart()
self.lines = []
def _Recall(self):
"""
Display the current item from the command history.
"""
self._ClearLine()
self.write(self.history[self.historyPointer])
class View(QtWidgets.QTextEdit):
"""View is a QTextEdit which provides some extra
facilities to help implement an interpreter console. In particular,
QTextEdit does not provide for complete control over the buffer being
edited. Some signals are emitted *after* action has already been
taken, disallowing controller classes from really controlling the widget.
This widget fixes that.
"""
returnPressed = QtCore.Signal()
requestPrev = QtCore.Signal()
requestNext = QtCore.Signal()
requestComplete = QtCore.Signal()
def __init__(self, parent=None):
super(View, self).__init__(parent)
self.promptLength = 0
self.__startOfInput = 0
self.setUndoRedoEnabled(False)
self.setAcceptRichText(False)
self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.tripleClickTimer = QtCore.QBasicTimer()
self.tripleClickPoint = QtCore.QPoint()
self._ignoreKeyPresses = True
self.ResetCharFormat()
def SetStartOfInput(self, position):
self.__startOfInput = position
def StartOfInput(self):
return self.__startOfInput
def ResetCharFormat(self):
charFormat = QtGui.QTextCharFormat()
charFormat.setFontFamily('monospace')
self.setCurrentCharFormat(charFormat)
def _PositionInInputArea(self, position):
return position - self.__startOfInput
def _PositionIsInInputArea(self, position):
return self._PositionInInputArea(position) >= 0
def _CursorIsInInputArea(self):
return self._PositionIsInInputArea(self.textCursor().position())
def _SelectionIsInInputArea(self):
if (not self.textCursor().hasSelection()):
return False
selStart = self.textCursor().selectionStart()
selEnd = self.textCursor().selectionEnd()
return self._PositionIsInInputArea(selStart) and \
self._PositionIsInInputArea(selEnd)
def _MoveCursorToStartOfInput(self, select=False):
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.movePosition(QtGui.QTextCursor.End, anchor)
cursor.setPosition(self.__startOfInput, anchor)
self.setTextCursor(cursor)
def _MoveCursorToEndOfInput(self, select=False):
c = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
c.movePosition(QtGui.QTextCursor.End, anchor)
self.setTextCursor(c)
def _WritableCharsToLeftOfCursor(self):
return (self._PositionInInputArea(self.textCursor().position()) > 0)
def mousePressEvent(self, e):
app = QtWidgets.QApplication.instance()
# is this a triple click?
if ((e.button() & QtCore.Qt.LeftButton) and
self.tripleClickTimer.isActive() and
(e.globalPos() - self.tripleClickPoint).manhattanLength() <
app.startDragDistance() ):
# instead of duplicating the triple click code completely, we just
# pass it along. but we modify the selection that comes out of it
# to exclude the prompt, if appropriate
super(View, self).mousePressEvent(e)
if (self._CursorIsInInputArea()):
selStart = self.textCursor().selectionStart()
selEnd = self.textCursor().selectionEnd()
if (self._PositionInInputArea(selStart) < 0):
# remove selection up until start of input
self._MoveCursorToStartOfInput(False)
cursor = self.textCursor()
cursor.setPosition(selEnd, QtGui.QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
else:
super(View, self).mousePressEvent(e)
def mouseDoubleClickEvent(self, e):
super(View, self).mouseDoubleClickEvent(e)
app = QtWidgets.QApplication.instance()
self.tripleClickTimer.start(app.doubleClickInterval(), self)
# make a copy here, otherwise tripleClickPoint will always = globalPos
self.tripleClickPoint = QtCore.QPoint(e.globalPos())
def timerEvent(self, e):
if (e.timerId() == self.tripleClickTimer.timerId()):
self.tripleClickTimer.stop()
else:
super(View, self).timerEvent(e)
def enterEvent(self, e):
self._ignoreKeyPresses = False
def leaveEvent(self, e):
self._ignoreKeyPresses = True
def dragEnterEvent(self, e):
self._ignoreKeyPresses = False
super(View, self).dragEnterEvent(e)
def dragLeaveEvent(self, e):
self._ignoreKeyPresses = True
super(View, self).dragLeaveEvent(e)
def insertFromMimeData(self, source):
if not self._CursorIsInInputArea():
self._MoveCursorToEndOfInput()
if source.hasText():
text = source.text().replace('\r', '')
textLines = text.split('\n')
if (textLines[-1] == ''):
textLines = textLines[:-1]
for i in range(len(textLines)):
line = textLines[i]
cursor = self.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(line)
cursor.movePosition(QtGui.QTextCursor.End)
self.setTextCursor(cursor)
if i < len(textLines) - 1:
self.returnPressed.emit()
def keyPressEvent(self, e):
"""
Handle user input a key at a time.
"""
if (self._ignoreKeyPresses):
e.ignore()
return
key = e.key()
ctrl = e.modifiers() & QtCore.Qt.ControlModifier
alt = e.modifiers() & QtCore.Qt.AltModifier
shift = e.modifiers() & QtCore.Qt.ShiftModifier
cursorInInput = self._CursorIsInInputArea()
selectionInInput = self._SelectionIsInInputArea()
hasSelection = self.textCursor().hasSelection()
canBackspace = self._WritableCharsToLeftOfCursor()
canEraseSelection = selectionInInput and cursorInInput
if key == QtCore.Qt.Key_Backspace:
if (canBackspace and not hasSelection) or canEraseSelection:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Delete:
if (cursorInInput and not hasSelection) or canEraseSelection:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Left:
pos = self._PositionInInputArea(self.textCursor().position())
if pos == 0:
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Right:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter:
# move cursor to end of line.
# emit signal to tell controller enter was pressed.
if not cursorInInput:
self._MoveCursorToStartOfInput(False)
cursor = self.textCursor()
cursor.movePosition(QtGui.QTextCursor.EndOfBlock)
self.setTextCursor(cursor)
# emit returnPressed
self.returnPressed.emit()
elif (key == QtCore.Qt.Key_Up
or key == QtCore.Qt.Key_Down
# support Ctrl+P and Ctrl+N for history
# navigation along with arrows
or (ctrl and (key == QtCore.Qt.Key_P
or key == QtCore.Qt.Key_N))
# support Ctrl+E/End and Ctrl+A/Home for terminal
# style nav. to the ends of the line
or (ctrl and (key == QtCore.Qt.Key_A
or key == QtCore.Qt.Key_E))
or (key == QtCore.Qt.Key_Home
or key == QtCore.Qt.Key_End)):
if cursorInInput:
if (key == QtCore.Qt.Key_Up or key == QtCore.Qt.Key_P):
self.requestPrev.emit()
if (key == QtCore.Qt.Key_Down or key == QtCore.Qt.Key_N):
self.requestNext.emit()
if (key == QtCore.Qt.Key_A or key == QtCore.Qt.Key_Home):
self._MoveCursorToStartOfInput(select=shift)
if (key == QtCore.Qt.Key_E or key == QtCore.Qt.Key_End):
self._MoveCursorToEndOfInput(select=shift)
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Tab:
self.AutoComplete()
e.accept()
elif ((ctrl and key == QtCore.Qt.Key_C) or
(shift and key == QtCore.Qt.Key_Insert)):
# Copy should never move cursor.
super(View, self).keyPressEvent(e)
elif ((ctrl and key == QtCore.Qt.Key_X) or
(shift and key == QtCore.Qt.Key_Delete)):
# Disallow cut from outside the input area so users don't
# affect the scrollback buffer.
if not selectionInInput:
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif (key == QtCore.Qt.Key_Control or
key == QtCore.Qt.Key_Alt or
key == QtCore.Qt.Key_Shift):
# Ignore modifier keypresses by themselves so the cursor
# doesn't jump to the end of input when users begin a
# key combination.
e.ignore()
else:
# All other keypresses should append to the end of input.
if not cursorInInput:
self._MoveCursorToEndOfInput()
super(View, self).keyPressEvent(e)
def AutoComplete(self):
if self._CursorIsInInputArea():
self.requestComplete.emit()
def _MoveCursorToBeginning(self, select=False):
if self._CursorIsInInputArea():
self._MoveCursorToStartOfInput(select)
else:
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.setPosition(0, anchor)
self.setTextCursor(cursor)
def _MoveCursorToEnd(self, select=False):
if self._CursorIsInInputArea():
self._MoveCursorToEndOfInput(select)
else:
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.setPosition(self.__startOfInput, anchor)
cursor.movePosition(QtGui.QTextCursor.Up, anchor)
cursor.movePosition(QtGui.QTextCursor.EndOfLine, anchor)
self.setTextCursor(cursor)
def MoveCursorToBeginning(self):
self._MoveCursorToBeginning(False)
def MoveCursorToEnd(self):
self._MoveCursorToEnd(False)
def SelectToTop(self):
self._MoveCursorToBeginning(True)
def SelectToBottom(self):
self._MoveCursorToEnd(True)
FREQUENTLY_USED = [
"dataModel", "stage", "frame", "prim", "property", "spec", "layer"]
INITIAL_PROMPT = """
Use the `usdviewApi` variable to interact with UsdView.
Type `help(usdviewApi)` to view available API methods and properties.
Frequently used properties:
{}\n""".format(
"".join(" usdviewApi.{} - {}\n".format(
name, getattr(UsdviewApi, name).__doc__)
for name in FREQUENTLY_USED))
class Myconsole(View):
def __init__(self, parent, usdviewApi):
super(Myconsole, self).__init__(parent)
self.setObjectName("Myconsole")
# Inject the UsdviewApi into the interpreter variables.
interpreterLocals = vars()
interpreterLocals["usdviewApi"] = usdviewApi
# Make a Controller.
self._controller = Controller(self, INITIAL_PROMPT, interpreterLocals)
def locals(self):
return self._controller.interpreter.locals
| 33,935 | Python | 34.35 | 80 | 0.590423 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primContextMenuItems.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtGui, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
import os
import sys
#
# Edit the following to alter the per-prim context menu.
#
# Every entry should be an object derived from PrimContextMenuItem,
# defined below.
#
def _GetContextMenuItems(appController, item):
return [JumpToEnclosingModelItem(appController, item),
SelectBoundPreviewMaterialMenuItem(appController, item),
SelectBoundFullMaterialMenuItem(appController, item),
SeparatorMenuItem(appController, item),
ToggleVisibilityMenuItem(appController, item),
VisOnlyMenuItem(appController, item),
RemoveVisMenuItem(appController, item),
SeparatorMenuItem(appController, item),
LoadOrUnloadMenuItem(appController, item),
ActiveMenuItem(appController, item),
SeparatorMenuItem(appController, item),
CopyPrimPathMenuItem(appController, item),
CopyModelPathMenuItem(appController, item),
SeparatorMenuItem(appController, item),
IsolateAssetMenuItem(appController, item),
SetAsActiveCamera(appController, item)]
#
# The base class for per-prim context menu items.
#
class PrimContextMenuItem(UsdviewContextMenuItem):
def __init__(self, appController, item):
self._selectionDataModel = appController._dataModel.selection
self._currentFrame = appController._dataModel.currentFrame
self._appController = appController
self._item = item
def IsEnabled(self):
return True
def IsSeparator(self):
return False
def GetText(self):
return ""
def RunCommand(self):
return True
#
# Puts a separator in the context menu
#
class SeparatorMenuItem(PrimContextMenuItem):
def IsSeparator(self):
return True
#
# Replace each selected prim with its enclosing model prim, if it has one,
# in the selection set
#
class JumpToEnclosingModelItem(PrimContextMenuItem):
def IsEnabled(self):
from .common import GetEnclosingModelPrim
for p in self._selectionDataModel.getPrims():
if GetEnclosingModelPrim(p) is not None:
return True
return False
def GetText(self):
return "Jump to Enclosing Model"
def RunCommand(self):
self._appController.selectEnclosingModel()
#
# Replace each selected prim with the "preview" Material it is bound to.
#
class SelectBoundPreviewMaterialMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdShade
self._boundPreviewMaterial = None
self._bindingRel = None
for p in self._selectionDataModel.getPrims():
(self._boundPreviewMaterial, self._bindingRel) = \
UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial(
UsdShade.Tokens.preview)
if self._boundPreviewMaterial:
break
def IsEnabled(self):
return bool(self._boundPreviewMaterial)
def GetText(self):
if self._boundPreviewMaterial:
isPreviewBindingRel = 'preview' in self._bindingRel.SplitName()
return "Select Bound Preview Material (%s%s)" % (
self._boundPreviewMaterial.GetPrim().GetName(),
"" if isPreviewBindingRel else " from generic binding")
else:
return "Select Bound Preview Material (None)"
def RunCommand(self):
self._appController.selectBoundPreviewMaterial()
#
# Replace each selected prim with the "preview" Material it is bound to.
#
class SelectBoundFullMaterialMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdShade
self._boundFullMaterial = None
self._bindingRel = None
for p in self._selectionDataModel.getPrims():
(self._boundFullMaterial, self._bindingRel) = \
UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial(
UsdShade.Tokens.full)
if self._boundFullMaterial:
break
def IsEnabled(self):
return bool(self._boundFullMaterial)
def GetText(self):
if self._boundFullMaterial:
isFullBindingRel = 'full' in self._bindingRel.SplitName()
return "Select Bound Full Material (%s%s)" % (
self._boundFullMaterial.GetPrim().GetName(),
"" if isFullBindingRel else " from generic binding")
else:
return "Select Bound Full Material (None)"
def RunCommand(self):
self._appController.selectBoundFullMaterial()
#
# Allows you to activate/deactivate a prim in the graph
#
class ActiveMenuItem(PrimContextMenuItem):
def GetText(self):
if self._selectionDataModel.getFocusPrim().IsActive():
return "Deactivate"
else:
return "Activate"
def RunCommand(self):
active = self._selectionDataModel.getFocusPrim().IsActive()
if active:
self._appController.deactivateSelectedPrims()
else:
self._appController.activateSelectedPrims()
#
# Allows you to vis or invis a prim in the graph, based on its current
# resolved visibility
#
class ToggleVisibilityMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdGeom
self._imageable = False
self._isVisible = False
for prim in self._selectionDataModel.getPrims():
imgbl = UsdGeom.Imageable(prim)
if imgbl:
self._imageable = True
self._isVisible = (imgbl.ComputeVisibility(self._currentFrame)
== UsdGeom.Tokens.inherited)
break
def IsEnabled(self):
return self._imageable
def GetText(self):
return "Make Invisible" if self._isVisible else "Make Visible"
def RunCommand(self):
if self._isVisible:
self._appController.invisSelectedPrims()
else:
self._appController.visSelectedPrims()
#
# Allows you to vis-only a prim in the graph
#
class VisOnlyMenuItem(PrimContextMenuItem):
def IsEnabled(self):
from pxr import UsdGeom
for prim in self._selectionDataModel.getPrims():
if prim.IsA(UsdGeom.Imageable):
return True
return False
def GetText(self):
return "Vis Only"
def RunCommand(self):
self._appController.visOnlySelectedPrims()
#
# Remove any vis/invis authored on selected prims
#
class RemoveVisMenuItem(PrimContextMenuItem):
def IsEnabled(self):
from .common import HasSessionVis
for prim in self._selectionDataModel.getPrims():
if HasSessionVis(prim):
return True
return False
def GetText(self):
return "Remove Session Visibility"
def RunCommand(self):
self._appController.removeVisSelectedPrims()
#
# Toggle load-state on the selected prims, if loadable
#
class LoadOrUnloadMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from .common import GetPrimsLoadability
# Use the descendent-pruned selection set to avoid redundant
# traversal of the stage to answer isLoaded...
self._loadable, self._loaded = GetPrimsLoadability(
self._selectionDataModel.getLCDPrims())
def IsEnabled(self):
return self._loadable
def GetText(self):
return "Unload" if self._loaded else "Load"
def RunCommand(self):
if self._loaded:
self._appController.unloadSelectedPrims()
else:
self._appController.loadSelectedPrims()
#
# Copies the paths of the currently selected prims to the clipboard
#
class CopyPrimPathMenuItem(PrimContextMenuItem):
def GetText(self):
if len(self._selectionDataModel.getPrims()) > 1:
return "Copy Prim Paths"
return "Copy Prim Path"
def RunCommand(self):
pathlist = [str(p.GetPath())
for p in self._selectionDataModel.getPrims()]
pathStrings = '\n'.join(pathlist)
cb = QtWidgets.QApplication.clipboard()
cb.setText(pathStrings, QtGui.QClipboard.Selection )
cb.setText(pathStrings, QtGui.QClipboard.Clipboard )
#
# Copies the path of the first-selected prim's enclosing model
# to the clipboard, if the prim is inside a model
#
class CopyModelPathMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from .common import GetEnclosingModelPrim
if len(self._selectionDataModel.getPrims()) == 1:
self._modelPrim = GetEnclosingModelPrim(
self._selectionDataModel.getFocusPrim())
else:
self._modelPrim = None
def IsEnabled(self):
return self._modelPrim
def GetText(self):
name = ( "(%s)" % self._modelPrim.GetName() ) if self._modelPrim else ""
return "Copy Enclosing Model %s Path" % name
def RunCommand(self):
modelPath = str(self._modelPrim.GetPath())
cb = QtWidgets.QApplication.clipboard()
cb.setText(modelPath, QtGui.QClipboard.Selection )
cb.setText(modelPath, QtGui.QClipboard.Clipboard )
#
# Copies the current prim and subtree to a file of the user's choosing
# XXX This is not used, and does not work. Leaving code in for now for
# future reference/inspiration
#
class IsolateCopyPrimMenuItem(PrimContextMenuItem):
def GetText(self):
return "Isolate Copy of Prim..."
def RunCommand(self):
focusPrim = self._selectionDataModel.getFocusPrim()
inFile = focusPrim.GetScene().GetUsdFile()
guessOutFile = os.getcwd() + "/" + focusPrim.GetName() + "_copy.usd"
(outFile, _) = QtWidgets.QFileDialog.getSaveFileName(None,
"Specify the Usd file to create", guessOutFile, 'Usd files (*.usd)')
if (outFile.rsplit('.')[-1] != 'usd'):
outFile += '.usd'
if inFile == outFile:
sys.stderr.write( "Cannot isolate a copy to the source usd!\n" )
return
sys.stdout.write( "Writing copy to new file '%s' ... " % outFile )
sys.stdout.flush()
os.system( 'usdcopy -inUsd ' + inFile +
' -outUsd ' + outFile + ' ' +
' -sourcePath ' + focusPrim.GetPath() + '; ' +
'usdview ' + outFile + ' &')
sys.stdout.write( "Done!\n" )
def IsEnabled(self):
numSelectedPrims = len(self._selectionDataModel.getPrims())
focusPrimActive = self._selectionDataModel.getFocusPrim().GetActive()
return numSelectedPrims == 1 and focusPrimActive
#
# Launches usdview on the asset instantiated at the selected prim, as
# defined by USD assetInfo present on the prim
#
class IsolateAssetMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
self._assetName = None
if len(self._selectionDataModel.getPrims()) == 1:
from pxr import Usd
model = Usd.ModelAPI(self._selectionDataModel.getFocusPrim())
name = model.GetAssetName()
identifier = model.GetAssetIdentifier()
if name and identifier:
# Ar API is still settling out...
# from pxr import Ar
# identifier = Ar.GetResolver().Resolve("", identifier.path)
from pxr import Sdf
layer = Sdf.Layer.Find(identifier.path)
if layer:
self._assetName = name
self._filePath = layer.realPath
def IsEnabled(self):
return self._assetName
def GetText(self):
name = ( " '%s'" % self._assetName ) if self._assetName else ""
return "usdview asset%s" % name
def RunCommand(self):
print("Spawning usdview %s" % self._filePath)
os.system("usdview %s &" % self._filePath)
#
# If the selected prim is a camera and not the currently active camera, display
# an enabled menu item to set it as the active camera.
#
class SetAsActiveCamera(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
self._nonActiveCameraPrim = None
if len(self._selectionDataModel.getPrims()) is 1:
prim = self._selectionDataModel.getPrims()[0]
from pxr import UsdGeom
cam = UsdGeom.Camera(prim)
if cam:
if prim != appController.getActiveCamera():
self._nonActiveCameraPrim = prim
def IsEnabled(self):
return self._nonActiveCameraPrim
def GetText(self):
return "Set As Active Camera"
def RunCommand(self):
self._appController._cameraSelectionChanged(self._nonActiveCameraPrim)
| 14,333 | Python | 31.577273 | 80 | 0.650945 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/plugin.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import sys
import importlib
from pxr import Tf
from pxr import Plug
from .qt import QtGui
class DuplicateCommandPlugin(Exception):
"""Exception raised when two command plugins are registered with the same
name.
"""
def __init__(self, name):
super(DuplicateCommandPlugin, self).__init__(
("A command plugin with the name '{}' has already been "
"registered.").format(name))
self.name = name
class DeferredImport(object):
"""Defers importing a module until one of the target callable objects is
called for the first time. Note that there is no way to know if a callable
object exists in the target module or even if the target module exists until
import time. All objects that are referenced are assumed to exist until
proven otherwise when they are called (at which point an ImportError is
raised).
Example:
math = DeferredImport("math")
# You can pull as many callable objects from `math` as desired, even if they
# don't actually exist in `math`.
sqrt = math.sqrt
cos = math.cos
foo = math.foo # does not exist in the real `math` module
# The `math` module will only be imported when this next line runs because
# this is the first invocation of a callable object from `math`.
cos(0)
# This will raise an ImportError because `math.foo` doesn't really exist.
foo(0)
"""
def __init__(self, moduleName, packageName=None):
self._moduleName = moduleName
self._packageName = packageName
self._module = None
def __getattr__(self, attr):
"""Returns a function which calls the target function of the module and
passes along any parameters. The module is lazy-imported when a function
returned by this method is called for the first time.
"""
def f(*args, **kwargs):
if self._module is None:
# Try to import the target module.
try:
self._module = importlib.import_module(
self._moduleName, package=self._packageName)
except ImportError:
raise ImportError(
"Failed deferred import: module '{}' not found.".format(
self._moduleName))
# Try to get the target function from the imported module.
try:
moduleFunction = getattr(self._module, attr)
except AttributeError:
raise ImportError(("Failed deferred import: callable object "
" '{}' from module '{}' not found").format(
attr, self._moduleName))
# Module and function loaded successfully. Now we can call the
# function and pass it the parameters.
return moduleFunction(*args, **kwargs)
# Return the deferring function. It will be called at some point after
# this method returns.
return f
class PluginContainer(object):
"""A base class for a container which holds some Usdview plugins. Specific
containers should inherit from this class and define the 'registerPlugins'
and 'configureView' methods.
"""
def deferredImport(self, moduleName):
"""Return a DeferredImport object which can be used to lazy load
functions when they are invoked for the first time.
"""
return DeferredImport(moduleName, self.__module__)
def registerPlugins(self, plugRegistry, plugCtx):
"""This method is called after the container is discovered by Usdview,
and should call 'registerCommandPlugin' one or more times on the
plugRegistry to add commands to Usdview.
"""
raise NotImplementedError
def configureView(self, plugRegistry, plugUIBuilder):
"""This method is called directly after 'registerPlugins' and can be
used to add menus which invoke a plugin command using the plugUIBuilder.
"""
raise NotImplementedError
# We load the PluginContainer using libplug so it needs to be a defined Tf.Type.
PluginContainerTfType = Tf.Type.Define(PluginContainer)
class CommandPlugin(object):
"""A Usdview command plugin object. The plugin's `callback` parameter must
be a callable object which takes a UsdviewApi object as its only parameter.
"""
def __init__(self, name, displayName, callback, description, usdviewApi):
self._name = name
self._displayName = displayName
self._callback = callback
self._usdviewApi = usdviewApi
self._description = description
@property
def name(self):
"""Return the command's name."""
return self._name
@property
def displayName(self):
"""Return the command's display name."""
return self._displayName
@property
def description(self):
"""Return the command description."""
return self._description
def run(self):
"""Run the command's callback function."""
self._callback(self._usdviewApi)
class PluginMenu(object):
"""Object which adds Usdview command plugins to a QMenu."""
def __init__(self, qMenu):
self._qMenu = qMenu
self._submenus = dict()
def addItem(self, commandPlugin, shortcut=None):
"""Add a new command plugin to the menu. Optionally, provide a hotkey/
shortcut.
"""
action = self._qMenu.addAction(commandPlugin.displayName,
lambda: commandPlugin.run())
action.setToolTip(commandPlugin.description)
if shortcut is not None:
action.setShortcut(QtGui.QKeySequence(shortcut))
def findOrCreateSubmenu(self, menuName):
"""Get a PluginMenu object for the submenu with the given name. If no
submenu with the given name exists, it is created.
"""
if menuName in self._submenus:
return self._submenus[menuName]
else:
subQMenu = self._qMenu.addMenu(menuName)
subQMenu.setToolTipsVisible(True)
submenu = PluginMenu(subQMenu)
self._submenus[menuName] = submenu
return submenu
def addSeparator(self):
"""Add a separator to the menu."""
self._qMenu.addSeparator()
class PluginRegistry(object):
"""Manages all plugins loaded by Usdview."""
def __init__(self, usdviewApi):
self._usdviewApi = usdviewApi
self._commandPlugins = dict()
def registerCommandPlugin(self, name, displayName, callback,
description=""):
"""Creates, registers, and returns a new command plugin.
The plugin's `name` parameter is used to find the plugin from the
registry later. It is good practice to prepend the plugin container's
name to the plugin's `name` parameter to avoid duplicate names
(i.e. "MyPluginContainer.myPluginName"). If a duplicate name is found, a
DuplicateCommandPlugin exception will be raised.
The `displayName` parameter is the name displayed to users.
The plugin's `callback` parameter must be a callable object which takes
a UsdviewApi object as its only parameter.
The optional `description` parameter is a short description of what the
command does which can be displayed to users.
"""
plugin = CommandPlugin(name, displayName, callback, description,
self._usdviewApi)
if name in self._commandPlugins:
raise DuplicateCommandPlugin(name)
self._commandPlugins[name] = plugin
return plugin
def getCommandPlugin(self, name):
"""Finds and returns a registered command plugin. If no plugin with the
given name is registered, return None instead.
"""
return self._commandPlugins.get(name, None)
class PluginUIBuilder(object):
"""Used by plugins to construct UI elements in Usdview."""
def __init__(self, mainWindow):
self._mainWindow = mainWindow
self._menus = dict()
def findOrCreateMenu(self, menuName):
"""Get a PluginMenu object for the menu with the given name. If no menu
with the given name exists, it is created.
"""
if menuName in self._menus:
return self._menus[menuName]
else:
qMenu = self._mainWindow.menuBar().addMenu(menuName)
qMenu.setToolTipsVisible(True)
menu = PluginMenu(qMenu)
self._menus[menuName] = menu
return menu
def loadPlugins(usdviewApi, mainWindow):
"""Find and load all Usdview plugins."""
# Find all the defined container types using libplug.
containerTypes = Plug.Registry.GetAllDerivedTypes(
PluginContainerTfType)
# Find all plugins and plugin container types through libplug.
plugins = dict()
for containerType in containerTypes:
plugin = Plug.Registry().GetPluginForType(containerType)
pluginContainerTypes = plugins.setdefault(plugin, [])
pluginContainerTypes.append(containerType)
# Load each plugin in alphabetical order by name. For each plugin, load all
# of its containers in alphabetical order by type name.
allContainers = []
for plugin in sorted(plugins.keys(), key=lambda plugin: plugin.name):
plugin.Load()
pluginContainerTypes = sorted(
plugins[plugin], key=lambda containerType: containerType.typeName)
for containerType in pluginContainerTypes:
if containerType.pythonClass is None:
print(("WARNING: Missing plugin container '{}' from plugin "
"'{}'. Make sure the container is a defined Tf.Type and "
"the container's import path matches the path in "
"plugInfo.json.").format(
containerType.typeName, plugin.name), file=sys.stderr)
continue
container = containerType.pythonClass()
allContainers.append(container)
# No plugins to load, so don't create a registry.
if len(allContainers) == 0:
return None
# Register all plugins from each container. If there is a naming conflict,
# abort plugin initialization.
registry = PluginRegistry(usdviewApi)
for container in allContainers:
try:
container.registerPlugins(registry, usdviewApi)
except DuplicateCommandPlugin as e:
print("WARNING: {}".format(e), file=sys.stderr)
print("Plugins will not be loaded.", file=sys.stderr)
return None
# Allow each plugin to construct UI elements.
uiBuilder = PluginUIBuilder(mainWindow)
for container in allContainers:
container.configureView(registry, uiBuilder)
return registry
| 11,947 | Python | 33.333333 | 80 | 0.652549 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/settings.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
"""A module for persisting usdview settings
"""
from __future__ import print_function
import sys
if sys.version_info.major >= 3:
from pickle import dumps, loads
else:
from cPickle import dumps, loads
def EmitWarning(filePath):
"""Send a warning because the settings file should never fail to load
"""
import traceback
import sys
msg = sys.stderr
print("------------------------------------------------------------", file=msg)
print("WARNING: Unknown problem while trying to access settings:", file=msg)
print("------------------------------------------------------------", file=msg)
print("This message is being sent because the settings file (%s) " \
"could not be read" % filePath, file=msg)
print("--", file=msg)
traceback.print_exc(file=msg)
print("--", file=msg)
print("Please file a bug if this warning persists", file=msg)
print("Attempting to continue... ", file=msg)
print("------------------------------------------------------------", file=msg)
class Settings(dict):
"""A small wrapper around the standard Python dictionary.
See help(dict) for initialization arguments This class uses python naming
conventions, because it inherits from dict.
"""
def __init__(self, filename, seq=None, ephemeral=False, **kwargs):
self._filename = filename
# Ephemeral settings objects are created in the presence of
# file system failures, such as the inability to create a .usdview
# directory to store our settings. In these cases we won't perform
# and save or load operations.
self._ephemeral = ephemeral
if self._ephemeral:
return
if seq:
dict.__init__(self, seq)
elif kwargs:
dict.__init__(self, **kwargs)
def save(self, ignoreErrors=False):
"""Write the settings out to the file at filename
"""
if self._ephemeral:
return
try:
# Explicly specify protocol 0 for cPickle/pickle.dumps to maintain
# backwards compatibility. In Python 2 protocol 0 was the default
# for cPickle.dump, but this changed in Python 3. In pickle.dumps
# the return value is unicode, but we know it contains lower ascii
# because we specify protocol 0, so we need to decode/encode as
# utf-8 to convert to a writable string but that should not change
# the data.
contents = dumps(self, protocol = 0)
with open(self._filename, "w") as f:
f.write(contents.decode('utf-8'))
except:
if ignoreErrors:
return False
raise
return True
def load(self, ignoreErrors=False):
"""Load the settings from the file at filename
"""
if self._ephemeral:
return
try:
# In Python 3, pickle.load will not accept an input file that is
# opened in text mode. Opening in binary won't work on windows
# because of \r\n line endings. Reading in the settings file as
# text and converting to utf-8 should work on all
# platforms/versions.
with open(self._filename, "r") as f:
contents = f.read().encode('utf-8')
self.update(loads(contents))
except:
if ignoreErrors:
return False
raise
return True
def setAndSave(self, **kwargs):
"""Sets keyword arguments as settings and quietly saves
"""
if self._ephemeral:
return
self.update(kwargs)
self.save(ignoreErrors=True)
| 4,791 | Python | 36.4375 | 83 | 0.611981 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/rootDataModel.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd, UsdGeom, UsdShade
from .qt import QtCore
from .common import Timer, IncludedPurposes
from .constantGroup import ConstantGroup
class ChangeNotice(ConstantGroup):
NONE = 0
RESYNC = 1
INFOCHANGES = 2
class RootDataModel(QtCore.QObject):
"""Data model providing centralized, moderated access to fundamental
information used throughout Usdview controllers, data models, and plugins.
"""
# Emitted when a new stage is set.
signalStageReplaced = QtCore.Signal()
signalPrimsChanged = QtCore.Signal(ChangeNotice, ChangeNotice)
def __init__(self, printTiming=False):
QtCore.QObject.__init__(self)
self._stage = None
self._printTiming = printTiming
self._currentFrame = Usd.TimeCode.Default()
self._playing = False
self._bboxCache = UsdGeom.BBoxCache(self._currentFrame,
[IncludedPurposes.DEFAULT, IncludedPurposes.PROXY], True)
self._xformCache = UsdGeom.XformCache(self._currentFrame)
self._pcListener = None
@property
def stage(self):
"""Get the current Usd.Stage object."""
return self._stage
@stage.setter
def stage(self, value):
"""Sets the current Usd.Stage object, and emits a signal if it is
different from the previous stage.
"""
validStage = (value is None) or isinstance(value, Usd.Stage)
if not validStage:
raise ValueError("Expected USD Stage, got: {}".format(repr(value)))
if value is not self._stage:
if self._pcListener:
self._pcListener.Revoke()
self._pcListener = None
if value is None:
with Timer() as t:
self._stage = None
if self._printTiming:
t.PrintTime('close stage')
else:
self._stage = value
if self._stage:
from pxr import Tf
self._pcListener = \
Tf.Notice.Register(Usd.Notice.ObjectsChanged,
self.__OnPrimsChanged, self._stage)
self.signalStageReplaced.emit()
def _emitPrimsChanged(self, primChange, propertyChange):
self.signalPrimsChanged.emit(primChange, propertyChange)
def __OnPrimsChanged(self, notice, sender):
primChange = ChangeNotice.NONE
propertyChange = ChangeNotice.NONE
for p in notice.GetResyncedPaths():
if p.IsPrimPath():
primChange = ChangeNotice.RESYNC
if p.IsPropertyPath():
propertyChange = ChangeNotice.RESYNC
if primChange == ChangeNotice.NONE or propertyChange == ChangeNotice.NONE:
for p in notice.GetChangedInfoOnlyPaths():
if p.IsPrimPath() and primChange == ChangeNotice.NONE:
primChange = ChangeNotice.INFOCHANGES
if p.IsPropertyPath() and propertyChange == ChangeNotice.NONE:
propertyChange = ChangeNotice.INFOCHANGES
self._emitPrimsChanged(primChange, propertyChange)
@property
def currentFrame(self):
"""Get a Usd.TimeCode object which represents the current frame being
considered in Usdview."""
return self._currentFrame
@currentFrame.setter
def currentFrame(self, value):
"""Set the current frame to a new Usd.TimeCode object."""
if not isinstance(value, Usd.TimeCode):
raise ValueError("Expected Usd.TimeCode, got: {}".format(value))
self._currentFrame = value
self._bboxCache.SetTime(self._currentFrame)
self._xformCache.SetTime(self._currentFrame)
@property
def playing(self):
return self._playing
@playing.setter
def playing(self, value):
self._playing = value
# XXX This method should be removed after bug 114225 is resolved. Changes to
# the stage will then be used to trigger the caches to be cleared, so
# RootDataModel clients will not even need to know the caches exist.
def _clearCaches(self):
"""Clears internal caches of bounding box and transform data. Should be
called when the current stage is changed in a way which affects this
data."""
self._bboxCache.Clear()
self._xformCache.Clear()
@property
def useExtentsHint(self):
"""Return True if bounding box calculations use extents hints from
prims.
"""
return self._bboxCache.GetUseExtentsHint()
@useExtentsHint.setter
def useExtentsHint(self, value):
"""Set whether whether bounding box calculations should use extents
from prims.
"""
if not isinstance(value, bool):
raise ValueError("useExtentsHint must be of type bool.")
if value != self._bboxCache.GetUseExtentsHint():
# Unfortunate that we must blow the entire BBoxCache, but we have no
# other alternative, currently.
purposes = self._bboxCache.GetIncludedPurposes()
self._bboxCache = UsdGeom.BBoxCache(
self._currentFrame, purposes, value)
@property
def includedPurposes(self):
"""Get the set of included purposes used for bounding box calculations.
"""
return set(self._bboxCache.GetIncludedPurposes())
@includedPurposes.setter
def includedPurposes(self, value):
"""Set a new set of included purposes for bounding box calculations."""
if not isinstance(value, set):
raise ValueError(
"Expected set of included purposes, got: {}".format(
repr(value)))
for purpose in value:
if purpose not in IncludedPurposes:
raise ValueError("Unknown included purpose: {}".format(
repr(purpose)))
self._bboxCache.SetIncludedPurposes(value)
def computeWorldBound(self, prim):
"""Compute the world-space bounds of a prim."""
if not isinstance(prim, Usd.Prim):
raise ValueError("Expected Usd.Prim object, got: {}".format(
repr(prim)))
return self._bboxCache.ComputeWorldBound(prim)
def getLocalToWorldTransform(self, prim):
"""Compute the transformation matrix of a prim."""
if not isinstance(prim, Usd.Prim):
raise ValueError("Expected Usd.Prim object, got: {}".format(
repr(prim)))
return self._xformCache.GetLocalToWorldTransform(prim)
def computeBoundMaterial(self, prim, purpose):
"""Compute the material that the prim is bound to, for the given value
of material purpose.
"""
if not isinstance(prim, Usd.Prim):
raise ValueError("Expected Usd.Prim object, got: {}".format(
repr(prim)))
# We don't use the binding cache yet since it isn't exposed to python.
return UsdShade.MaterialBindingAPI(
prim).ComputeBoundMaterial(purpose)
| 8,129 | Python | 34.194805 | 82 | 0.638578 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/adjustDefaultMaterial.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets
from .adjustDefaultMaterialUI import Ui_AdjustDefaultMaterial
class AdjustDefaultMaterial(QtWidgets.QDialog):
"""Popup widget to adjust the default material used for rendering.
`datamodel` should be a ViewSettingsDataModel.
"""
def __init__(self, parent, dataModel):
QtWidgets.QDialog.__init__(self,parent)
self._ui = Ui_AdjustDefaultMaterial()
self._ui.setupUi(self)
self._dataModel = dataModel
self._ambientCache = None
self._specularCache = None
self._ui.ambientIntSpinBox.valueChanged['double'].connect(self._ambientChanged)
self._ui.specularIntSpinBox.valueChanged['double'].connect(self._specularChanged)
dataModel.signalDefaultMaterialChanged.connect(self._updateFromData)
self._ui.resetButton.clicked[bool].connect(self._reset)
self._ui.doneButton.clicked[bool].connect(self._done)
self._updateFromData()
def _updateFromData(self):
if self._dataModel.defaultMaterialAmbient != self._ambientCache:
self._ambientCache = self._dataModel.defaultMaterialAmbient
self._ui.ambientIntSpinBox.setValue(self._ambientCache)
if self._dataModel.defaultMaterialSpecular != self._specularCache:
self._specularCache = self._dataModel.defaultMaterialSpecular
self._ui.specularIntSpinBox.setValue(self._specularCache)
def _ambientChanged(self, val):
if val != self._ambientCache:
# Must do update cache first to prevent update cycle
self._ambientCache = val
self._dataModel.defaultMaterialAmbient = val
def _specularChanged(self, val):
if val != self._specularCache:
# Must do update cache first to prevent update cycle
self._specularCache = val
self._dataModel.defaultMaterialSpecular = val
def _reset(self, unused):
self._dataModel.resetDefaultMaterial()
def _done(self, unused):
self.close()
def closeEvent(self, event):
event.accept()
# Since the dialog is the immediate-edit kind, we consider
# window-close to be an accept, so our clients can know the dialog is
# done
self.accept()
| 3,333 | Python | 37.321839 | 89 | 0.70087 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/qt.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
def GetPySideModule():
"""Returns name of PySide module used by usdview,
e.g. 'PySide' or 'PySide2'"""
# Inspect objects imported in a UI module generated by uic to determine
# which PySide module they come from (e.g. PySide.QtCore, PySide2.QtCore).
# This insulates the code from assuming that the generated code will
# import something specific.
from . import attributeValueEditorUI
import inspect
for name in dir(attributeValueEditorUI):
obj = getattr(attributeValueEditorUI, name)
module = inspect.getmodule(obj)
if module and module.__name__.startswith('PySide'):
return module.__name__.split('.')[0]
return None
PySideModule = GetPySideModule()
if PySideModule == 'PySide':
from PySide import QtCore, QtGui, QtOpenGL
from PySide import QtGui as QtWidgets
# Patch missing functions to make PySide look like PySide2
if not hasattr(QtGui.QApplication, 'devicePixelRatio'):
QtGui.QApplication.devicePixelRatio = lambda self: 1
if not hasattr(QtOpenGL.QGLWidget, 'devicePixelRatioF'):
QtOpenGL.QGLWidget.devicePixelRatioF = lambda self: 1.0
if not hasattr(QtWidgets.QHeaderView, 'setSectionResizeMode'):
QtWidgets.QHeaderView.setSectionResizeMode = \
QtWidgets.QHeaderView.setResizeMode
if not hasattr(QtGui.QMenu, 'setToolTipsVisible'):
QtGui.QMenu.setToolTipsVisible = lambda self, _: None
if hasattr(QtGui.QWheelEvent, 'delta') \
and not hasattr(QtGui.QWheelEvent, 'angleDelta'):
def angleDelta(self):
return QtCore.QPoint(0, self.delta())
QtGui.QWheelEvent.angleDelta = angleDelta
# Patch missing classes to make PySide look like PySide2
if not hasattr(QtCore, 'QItemSelectionModel'):
QtCore.QItemSelectionModel = QtGui.QItemSelectionModel
if not hasattr(QtCore, 'QStringListModel'):
QtCore.QStringListModel = QtGui.QStringListModel
elif PySideModule == 'PySide2':
from PySide2 import QtCore, QtGui, QtWidgets, QtOpenGL
# Older versions still have QtGui.QStringListModel - this
# is apparently a bug:
# https://bugreports.qt.io/browse/PYSIDE-614
if not hasattr(QtCore, 'QStringListModel'):
QtCore.QStringListModel = QtGui.QStringListModel
else:
raise ImportError('Unrecognized PySide module "{}"'.format(PySideModule))
| 3,467 | Python | 40.285714 | 78 | 0.720508 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/headerContextMenu.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
#
# Specialized context menu for adding and removing columns
# in the prim browser and attribute inspector.
#
class HeaderContextMenu(QtWidgets.QMenu):
def __init__(self, parent):
QtWidgets.QMenu.__init__(self, "Columns", parent)
self._menuItems = _GetContextMenuItems(parent)
for menuItem in self._menuItems:
if menuItem.isValid():
# create menu actions. Associate them with each Item, so that
# we can update them when we show, since column visibility can
# change.
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
action.setCheckable(True)
menuItem.action = action
self.aboutToShow.connect(self._prepForShow)
def _prepForShow(self):
for menuItem in self._menuItems:
if menuItem.action:
menuItem.action.setChecked(menuItem.IsChecked())
menuItem.action.setEnabled(menuItem.IsEnabled())
def _GetContextMenuItems(parent):
# create a list of HeaderContextMenuItem classes
# initialized with the parent object and column
itemList = []
return [HeaderContextMenuItem(parent, column) \
for column in range(parent.columnCount())]
# The base class for header context menus
class HeaderContextMenuItem(UsdviewContextMenuItem):
def __init__(self, parent, column):
self._parent = parent
self._column = column
self._action = None
if isinstance(parent, QtWidgets.QTreeWidget):
self._text = parent.headerItem().text(column)
else:
self._text = parent.horizontalHeaderItem(column).text()
def GetText(self):
# returns the text to be displayed in menu
return self._text
def IsEnabled(self):
# Enable context menu item for columns except the "Name" column.
return 'Name' not in self.GetText()
def IsChecked(self):
# true if the column is visible, false otherwise
return not self._parent.isColumnHidden(self._column)
def RunCommand(self):
# show or hide the column depending on its previous state
self._parent.setColumnHidden(self._column, self.IsChecked())
@property
def action(self):
return self._action
@action.setter
def action(self, action):
self._action = action
| 3,548 | Python | 34.49 | 80 | 0.683484 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/legendUtil.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Functionality for expanding and collapsing legend components in usdview
LEGEND_BUTTON_SELECTEDSTYLE = ('background: rgb(189, 155, 84); '
'color: rgb(227, 227, 227);')
# Set the start/end points of an animation
def _SetAnimValues(anim, a1, a2):
anim.setStartValue(a1)
anim.setEndValue(a2)
# A function which takes a two-pane area and transforms it to
# open or close the bottom pane.
#
# legendHeight
# | separator height
# | | browser height
# | | |-> ___________ ___________
# | | | | | | |
# | | | | | | |
# | | |-> | | <---> | |
# |---|-------> +++++++++++++ | |
# | | | <---> | |
# | | | | |
# |-----------> ----------- +++++++++++
def ToggleLegendWithBrowser(legend, button, anim):
legend.ToggleMinimized()
# We are dragging downward, so collapse the legend and expand the
# attribute viewer panel to take up the remaining space.
if legend.IsMinimized():
button.setStyleSheet('')
_SetAnimValues(anim, legend.GetHeight(), 0)
# We are expanding, so do the opposite.
else:
button.setStyleSheet(LEGEND_BUTTON_SELECTEDSTYLE)
_SetAnimValues(anim, legend.GetHeight(), legend.GetResetHeight())
anim.start()
| 2,568 | Python | 39.777777 | 74 | 0.588006 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/adjustDefaultMaterialUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'adjustDefaultMaterialUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AdjustDefaultMaterial(object):
def setupUi(self, AdjustDefaultMaterial):
if not AdjustDefaultMaterial.objectName():
AdjustDefaultMaterial.setObjectName(u"AdjustDefaultMaterial")
AdjustDefaultMaterial.resize(238, 123)
sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(AdjustDefaultMaterial.sizePolicy().hasHeightForWidth())
AdjustDefaultMaterial.setSizePolicy(sizePolicy)
self.verticalLayout = QVBoxLayout(AdjustDefaultMaterial)
self.verticalLayout.setObjectName(u"verticalLayout")
self.verticalLayout_4 = QVBoxLayout()
self.verticalLayout_4.setObjectName(u"verticalLayout_4")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.horizontalSpacer_4 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(self.horizontalSpacer_4)
self.ambientInt = QLabel(AdjustDefaultMaterial)
self.ambientInt.setObjectName(u"ambientInt")
self.ambientInt.setFocusPolicy(Qt.NoFocus)
self.horizontalLayout.addWidget(self.ambientInt)
self.ambientIntSpinBox = QDoubleSpinBox(AdjustDefaultMaterial)
self.ambientIntSpinBox.setObjectName(u"ambientIntSpinBox")
self.ambientIntSpinBox.setDecimals(1)
self.ambientIntSpinBox.setMaximum(1.000000000000000)
self.ambientIntSpinBox.setSingleStep(0.100000000000000)
self.horizontalLayout.addWidget(self.ambientIntSpinBox)
self.horizontalSpacer_5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(self.horizontalSpacer_5)
self.verticalLayout_4.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalSpacer_6 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer_6)
self.specularInt = QLabel(AdjustDefaultMaterial)
self.specularInt.setObjectName(u"specularInt")
self.specularInt.setFocusPolicy(Qt.NoFocus)
self.horizontalLayout_2.addWidget(self.specularInt)
self.specularIntSpinBox = QDoubleSpinBox(AdjustDefaultMaterial)
self.specularIntSpinBox.setObjectName(u"specularIntSpinBox")
self.specularIntSpinBox.setDecimals(1)
self.specularIntSpinBox.setMaximum(1.000000000000000)
self.specularIntSpinBox.setSingleStep(0.100000000000000)
self.horizontalLayout_2.addWidget(self.specularIntSpinBox)
self.horizontalSpacer_7 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer_7)
self.verticalLayout_4.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.resetButton = QPushButton(AdjustDefaultMaterial)
self.resetButton.setObjectName(u"resetButton")
self.resetButton.setAutoDefault(False)
self.horizontalLayout_3.addWidget(self.resetButton)
self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(self.horizontalSpacer_2)
self.doneButton = QPushButton(AdjustDefaultMaterial)
self.doneButton.setObjectName(u"doneButton")
self.horizontalLayout_3.addWidget(self.doneButton)
self.verticalLayout_4.addLayout(self.horizontalLayout_3)
self.verticalLayout.addLayout(self.verticalLayout_4)
self.retranslateUi(AdjustDefaultMaterial)
QMetaObject.connectSlotsByName(AdjustDefaultMaterial)
# setupUi
def retranslateUi(self, AdjustDefaultMaterial):
AdjustDefaultMaterial.setProperty("comment", QCoreApplication.translate("AdjustDefaultMaterial", u"\n"
" Copyright 2017 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
AdjustDefaultMaterial.setWindowTitle(QCoreApplication.translate("AdjustDefaultMaterial", u"Adjust Default Material", None))
self.ambientInt.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Ambient Intensity", None))
self.specularInt.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Specular Intensity", None))
self.resetButton.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Reset", None))
self.doneButton.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Done", None))
# retranslateUi
| 7,259 | Python | 49.068965 | 131 | 0.635211 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primViewItem.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from .qt import QtCore, QtGui, QtWidgets
from pxr import Sdf, Usd, UsdGeom
from ._usdviewq import Utils
from .common import UIPrimTypeColors, UIFonts
HALF_DARKER = 150
# Pulled out as a wrapper to facilitate cprofile tracking
def _GetPrimInfo(prim, time):
return Utils.GetPrimInfo(prim, time)
# This class extends QTreeWidgetItem to also contain all the stage
# prim data associated with it and populate itself with that data.
class PrimViewItem(QtWidgets.QTreeWidgetItem):
def __init__(self, prim, appController, primHasChildren):
# Do *not* pass a parent. The client must build the hierarchy.
# This can dramatically improve performance when building a
# large hierarchy.
super(PrimViewItem, self).__init__()
self.prim = prim
self._appController = appController
self._needsPull = True
self._needsPush = True
self._needsChildrenPopulated = primHasChildren
# Initialize these now so loadVis(), _visData() and onClick() can
# use them without worrying if _pull() has been called.
self.imageable = False
self.active = False
# True if this item is an ancestor of a selected item.
self.ancestorOfSelected = False
# If we know we'll have children show a norgie, otherwise don't.
if primHasChildren:
self.setChildIndicatorPolicy(
QtWidgets.QTreeWidgetItem.ShowIndicator)
else:
self.setChildIndicatorPolicy(
QtWidgets.QTreeWidgetItem.DontShowIndicator)
# If this item includes a persistent drawMode widget, it is stored here.
self.drawModeWidget = None
def push(self):
"""Pushes prim data to the UI."""
# Push to UI.
if self._needsPush:
self._needsPush = False
self._pull()
def _pull(self):
"""Extracts and stores prim data."""
if self._needsPull:
# Only do this once.
self._needsPull = False
# Visibility is recursive so the parent must pull before us.
parent = self.parent()
if isinstance(parent, PrimViewItem):
parent._pull()
# Get our prim info.
# To avoid Python overhead, request data in batch from C++.
info = _GetPrimInfo(
self.prim, self._appController._dataModel.currentFrame)
self._extractInfo(info)
self.emitDataChanged()
@staticmethod
def _HasAuthoredDrawMode(prim):
modelAPI = UsdGeom.ModelAPI(prim)
drawModeAttr = modelAPI.GetModelDrawModeAttr()
return drawModeAttr and drawModeAttr.HasAuthoredValue()
def _isComputedDrawModeInherited(self, parentDrawModeIsInherited=None):
"""Returns true if the computed draw mode for this item is inherited
from an authored "model:drawMode" value on an ancestor prim.
"""
if PrimViewItem._HasAuthoredDrawMode(self.prim):
return False
parent = self.prim.GetParent()
while parent and parent.GetPath() != Sdf.Path.absoluteRootPath:
if PrimViewItem._HasAuthoredDrawMode(parent):
return True
# Stop the upward traversal if we know whether the parent's draw
# mode is inherited.
if parentDrawModeIsInherited is not None:
return parentDrawModeIsInherited
parent = parent.GetParent()
return False
def _extractInfo(self, info):
( self.hasArcs,
self.active,
self.imageable,
self.defined,
self.abstract,
self.isInMaster,
self.isInstance,
self.supportsDrawMode,
isVisibilityInherited,
self.visVaries,
self.name,
self.typeName ) = info
parent = self.parent()
parentIsPrimViewItem = isinstance(parent, PrimViewItem)
self.computedVis = parent.computedVis if parentIsPrimViewItem \
else UsdGeom.Tokens.inherited
if self.imageable and self.active:
if isVisibilityInherited:
self.vis = UsdGeom.Tokens.inherited
else:
self.vis = self.computedVis = UsdGeom.Tokens.invisible
# If this is the invisible root item, initialize fallback values for
# the drawMode related parameters.
if not parentIsPrimViewItem:
self.computedDrawMode = ''
self.isDrawModeInherited = False
return
# We don't need to compute drawMode related parameters for primViewItems
# that don't support draw mode.
if not self.supportsDrawMode:
return
self.computedDrawMode = UsdGeom.ModelAPI(self.prim).ComputeModelDrawMode(
parent.computedDrawMode) if parentIsPrimViewItem else ''
parentDrawModeIsInherited = parent.isDrawModeInherited if \
parentIsPrimViewItem else None
self.isDrawModeInherited = self._isComputedDrawModeInherited(
parentDrawModeIsInherited)
def addChildren(self, children):
"""Adds children to the end of this item. This is the only
method clients should call to manage an item's children."""
self._needsChildrenPopulated = False
super(PrimViewItem, self).addChildren(children)
def data(self, column, role):
# All Qt queries that affect the display of this item (label, font,
# color, etc) will come through this method. We set that data
# lazily because it's expensive to do and (for the most part) Qt
# only needs the data for items that are visible.
self.push()
# We report data directly rather than use set...() and letting
# super().data() return it because Qt can be pathological during
# calls to set...() when the item hierarchy is attached to a view,
# making thousands of calls to data().
result = None
if column == 0:
result = self._nameData(role)
elif column == 1:
result = self._typeData(role)
elif column == 2:
result = self._visData(role)
elif column == 3 and self.supportsDrawMode:
result = self._drawModeData(role)
if not result:
result = super(PrimViewItem, self).data(column, role)
return result
def _GetForegroundColor(self):
self.push()
if self.isInstance:
color = UIPrimTypeColors.INSTANCE
elif self.hasArcs:
color = UIPrimTypeColors.HAS_ARCS
elif self.isInMaster:
color = UIPrimTypeColors.MASTER
else:
color = UIPrimTypeColors.NORMAL
return color.color() if self.active else color.color().darker(HALF_DARKER)
def _nameData(self, role):
if role == QtCore.Qt.DisplayRole:
return self.name
elif role == QtCore.Qt.FontRole:
# Abstract prims are also considered defined; since we want
# to distinguish abstract defined prims from non-abstract
# defined prims, we check for abstract first.
if self.abstract:
return UIFonts.ABSTRACT_PRIM
elif not self.defined:
return UIFonts.OVER_PRIM
else:
return UIFonts.DEFINED_PRIM
elif role == QtCore.Qt.ForegroundRole:
return self._GetForegroundColor()
elif role == QtCore.Qt.ToolTipRole:
toolTip = 'Prim'
if len(self.typeName) > 0:
toolTip = self.typeName + ' ' + toolTip
if self.isInMaster:
toolTip = 'Master ' + toolTip
if not self.defined:
toolTip = 'Undefined ' + toolTip
elif self.abstract:
toolTip = 'Abstract ' + toolTip
else:
toolTip = 'Defined ' + toolTip
if not self.active:
toolTip = 'Inactive ' + toolTip
elif self.isInstance:
toolTip = 'Instanced ' + toolTip
if self.hasArcs:
toolTip = toolTip + "<br>Has composition arcs"
return toolTip
else:
return None
def _drawModeData(self, role):
if role == QtCore.Qt.DisplayRole:
return self.computedDrawMode
elif role == QtCore.Qt.FontRole:
return UIFonts.BOLD_ITALIC if self.isDrawModeInherited else \
UIFonts.DEFINED_PRIM
elif role == QtCore.Qt.ForegroundRole:
color = self._GetForegroundColor()
return color.darker(110) if self.isDrawModeInherited else \
color
def _typeData(self, role):
if role == QtCore.Qt.DisplayRole:
return self.typeName
else:
return self._nameData(role)
def _isVisInherited(self):
return self.imageable and self.active and \
self.vis != UsdGeom.Tokens.invisible and \
self.computedVis == UsdGeom.Tokens.invisible
def _visData(self, role):
if role == QtCore.Qt.DisplayRole:
if self.imageable and self.active:
return "I" if self.vis == UsdGeom.Tokens.invisible else "V"
else:
return ""
elif role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
elif role == QtCore.Qt.FontRole:
return UIFonts.BOLD_ITALIC if self._isVisInherited() \
else UIFonts.BOLD
elif role == QtCore.Qt.ForegroundRole:
fgColor = self._GetForegroundColor()
return fgColor.darker() if self._isVisInherited() \
else fgColor
else:
return None
def needsChildrenPopulated(self):
return self._needsChildrenPopulated
def canChangeVis(self):
if not self.imageable:
print("WARNING: The prim <" + str(self.prim.GetPath()) + \
"> is not imageable. Cannot change visibility.")
return False
elif self.isInMaster:
print("WARNING: The prim <" + str(self.prim.GetPath()) + \
"> is in a master. Cannot change visibility.")
return False
return True
def loadVis(self, inheritedVis, visHasBeenAuthored):
if not (self.imageable and self.active):
return inheritedVis
time = self._appController._dataModel.currentFrame
# If visibility-properties have changed on the stage, then
# we must re-evaluate our variability before deciding whether
# we can avoid re-reading our visibility
visAttr = UsdGeom.Imageable(self.prim).GetVisibilityAttr()
if visHasBeenAuthored:
self.visVaries = visAttr.ValueMightBeTimeVarying()
if not self.visVaries:
self.vis = visAttr.Get(time)
if self.visVaries:
self.vis = visAttr.Get(time)
self.computedVis = UsdGeom.Tokens.invisible \
if self.vis == UsdGeom.Tokens.invisible \
else inheritedVis
self.emitDataChanged()
return self.computedVis
@staticmethod
def propagateDrawMode(item, primView, parentDrawMode='',
parentDrawModeIsInherited=None):
# If this item does not support draw mode, none of its descendants
# can support it. Hence, stop recursion here.
#
# Call push() here to ensure that supportsDrawMode has been populated
# for the item.
item.push()
if not item.supportsDrawMode:
return
from .primTreeWidget import DrawModeWidget
drawModeWidget = item.drawModeWidget
if drawModeWidget:
drawModeWidget.RefreshDrawMode()
else:
modelAPI = UsdGeom.ModelAPI(item.prim)
item.computedDrawMode = modelAPI.ComputeModelDrawMode(parentDrawMode)
item.isDrawModeInherited = item._isComputedDrawModeInherited(
parentDrawModeIsInherited=parentDrawModeIsInherited)
item.emitDataChanged()
# Traverse down to children to update their drawMode.
for child in [item.child(i) for i in range(item.childCount())]:
PrimViewItem.propagateDrawMode(child, primView,
parentDrawMode=item.computedDrawMode,
parentDrawModeIsInherited=item.isDrawModeInherited)
@staticmethod
def propagateVis(item, authoredVisHasChanged=True):
parent = item.parent()
inheritedVis = parent._resetAncestorsRecursive(authoredVisHasChanged) \
if isinstance(parent, PrimViewItem) \
else UsdGeom.Tokens.inherited
# This may be called on the "InvisibleRootItem" that is an ordinary
# QTreeWidgetItem, in which case we need to process its children
# individually
if isinstance(item, PrimViewItem):
item._pushVisRecursive(inheritedVis, authoredVisHasChanged)
else:
for child in [item.child(i) for i in range(item.childCount())]:
child._pushVisRecursive(inheritedVis, authoredVisHasChanged)
def _resetAncestorsRecursive(self, authoredVisHasChanged):
parent = self.parent()
inheritedVis = parent._resetAncestorsRecursive(authoredVisHasChanged) \
if isinstance(parent, PrimViewItem) \
else UsdGeom.Tokens.inherited
return self.loadVis(inheritedVis, authoredVisHasChanged)
def _pushVisRecursive(self, inheritedVis, authoredVisHasChanged):
myComputedVis = self.loadVis(inheritedVis, authoredVisHasChanged)
for child in [self.child(i) for i in range(self.childCount())]:
child._pushVisRecursive(myComputedVis, authoredVisHasChanged)
def setLoaded(self, loaded):
if self.prim.IsMaster():
print("WARNING: The prim <" + str(self.prim.GetPath()) + \
"> is a master prim. Cannot change load state.")
return
if self.prim.IsActive():
if loaded:
self.prim.Load()
else:
self.prim.Unload()
def setVisible(self, visible):
if self.canChangeVis():
UsdGeom.Imageable(self.prim).GetVisibilityAttr().Set(UsdGeom.Tokens.inherited
if visible else UsdGeom.Tokens.invisible)
self.visChanged()
def makeVisible(self):
if self.canChangeVis():
# It is in general not kosher to use an Sdf.ChangeBlock around
# operations at the Usd API level. We have carefully arranged
# (with insider knowledge) to have only "safe" mutations
# happening inside the ChangeBlock. We do this because
# UsdImaging updates itself independently for each
# Usd.Notice.ObjectsChanged it receives. We hope to eliminate
# the performance need for this by addressing bug #121992
from pxr import Sdf
with Sdf.ChangeBlock():
UsdGeom.Imageable(self.prim).MakeVisible()
self.visChanged()
def visChanged(self):
# called when user authors a new visibility value
# we must re-determine if visibility is varying over time
self.loadVis(self.parent().computedVis, True)
def toggleVis(self):
"""Return True if the the prim's visibility state was toggled. """
if self.imageable and self.active:
self.setVisible(self.vis == UsdGeom.Tokens.invisible)
return True
return False
| 16,874 | Python | 38.0625 | 89 | 0.619237 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/adjustClipping.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .adjustClippingUI import Ui_AdjustClipping
from .common import FixableDoubleValidator
class AdjustClipping(QtWidgets.QDialog):
"""The dataModel provided to this VC must conform to the following
interface:
Editable properties:
overrideNear (float or None, which indicates the override is disabled)
overrideFar (float or None, which indicates the override is disabled)
Readable properties:
cameraFrustum (Gf.Frustum, or struct that has a Gf.Range1d 'nearFar' member)
Signals:
signalFrustumChanged() - whenever the near/far clipping values
may have changed.
"""
def __init__(self, parent, dataModel):
QtWidgets.QDialog.__init__(self,parent)
self._ui = Ui_AdjustClipping()
self._ui.setupUi(self)
self._dataModel = dataModel
clipRange = self._dataModel.cameraFrustum.nearFar
self._nearCache = self._dataModel.overrideNear or clipRange.min
self._farCache = self._dataModel.overrideFar or clipRange.max
self._dataModel.signalFrustumChanged.connect(self.update)
# When the checkboxes change, we want to update instantly
self._ui.overrideNear.stateChanged.connect(self._overrideNearToggled)
self._ui.overrideFar.stateChanged.connect(self._overrideFarToggled)
# we also want to update the clipping planes as the user is typing
self._ui.nearEdit.textChanged.connect(self._nearChanged)
self._ui.farEdit.textChanged.connect(self._farChanged)
def AddValidation(lineEdit):
dv = FixableDoubleValidator(lineEdit)
dv.setDecimals(3)
dv.setBottom(0)
lineEdit.setValidator(dv)
# Make sure only human-readable doubles can be typed in the text boxes
AddValidation(self._ui.nearEdit)
AddValidation(self._ui.farEdit)
# Set the checkboxes to their initial state
self._ui.overrideNear.setChecked(self._dataModel.overrideNear \
is not None)
self._ui.overrideFar.setChecked(self._dataModel.overrideFar \
is not None)
# load the initial values for the text boxes, but first deactivate them
# if their corresponding checkbox is off.
self._ui.nearEdit.setEnabled(self._ui.overrideNear.isChecked())
self._ui.nearEdit.validator().fixup(str(self._nearCache))
self._ui.farEdit.setEnabled(self._ui.overrideFar.isChecked())
self._ui.farEdit.validator().fixup(str(self._farCache))
def _updateEditorsFromDataModel(self):
"""Read the dataModel-computed clipping planes and put them
in the text boxes when they are deactivated."""
clipRange = self._dataModel.cameraFrustum.nearFar
if (not self._ui.overrideNear.isChecked()) and \
self._nearCache != clipRange.min :
self._nearCache = clipRange.min
nearStr = str(self._nearCache)
self._ui.nearEdit.validator().fixup(nearStr)
if (not self._ui.overrideFar.isChecked()) and \
self._farCache != clipRange.max :
self._farCache = clipRange.max
farStr = str(self._farCache)
self._ui.farEdit.validator().fixup(farStr)
def paintEvent(self, paintEvent):
"""Overridden from base class so we can perform JIT updating
of editors to limit the number of redraws we perform"""
self._updateEditorsFromDataModel()
super(AdjustClipping, self).paintEvent(paintEvent)
def _overrideNearToggled(self, state):
"""Called when the "Override Near" checkbox is toggled"""
self._ui.nearEdit.setEnabled(state)
if state:
self._dataModel.overrideNear = self._nearCache
else:
self._dataModel.overrideNear = None
def _overrideFarToggled(self, state):
"""Called when the "Override Far" checkbox is toggled"""
self._ui.farEdit.setEnabled(state)
if state:
self._dataModel.overrideFar = self._farCache
else:
self._dataModel.overrideFar = None
def _nearChanged(self, text):
"""Called when the Near text box changed. This can happen when we
are updating the value but the widget is actually inactive - don't
do anything in that case."""
if len(text) == 0 or not self._ui.nearEdit.isEnabled():
return
try:
self._dataModel.overrideNear = float(text)
except ValueError:
pass
def _farChanged(self, text):
"""Called when the Far text box changed. This can happen when we
are updating the value but the widget is actually inactive - don't
do anything in that case."""
if len(text) == 0 or not self._ui.farEdit.isEnabled():
return
try:
self._dataModel.overrideFar = float(text)
except ValueError:
pass
def closeEvent(self, event):
# Ensure that even if the dialog doesn't get destroyed right away,
# we'll stop doing work.
self._dataModel.signalFrustumChanged.disconnect(self.update)
event.accept()
# Since the dialog is the immediate-edit kind, we consider
# window-close to be an accept, so our clients can know the dialog is
# done by listening for the finished(int) signal
self.accept()
| 6,576 | Python | 39.850931 | 83 | 0.660128 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/adjustClippingUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'adjustClippingUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AdjustClipping(object):
def setupUi(self, AdjustClipping):
if not AdjustClipping.objectName():
AdjustClipping.setObjectName(u"AdjustClipping")
AdjustClipping.resize(331, 86)
self.verticalLayout = QVBoxLayout(AdjustClipping)
self.verticalLayout.setObjectName(u"verticalLayout")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.verticalLayout_2 = QVBoxLayout()
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.overrideNear = QCheckBox(AdjustClipping)
self.overrideNear.setObjectName(u"overrideNear")
self.overrideNear.setFocusPolicy(Qt.NoFocus)
self.verticalLayout_2.addWidget(self.overrideNear)
self.overrideFar = QCheckBox(AdjustClipping)
self.overrideFar.setObjectName(u"overrideFar")
self.overrideFar.setFocusPolicy(Qt.NoFocus)
self.verticalLayout_2.addWidget(self.overrideFar)
self.horizontalLayout.addLayout(self.verticalLayout_2)
self.verticalLayout_3 = QVBoxLayout()
self.verticalLayout_3.setObjectName(u"verticalLayout_3")
self.nearEdit = QLineEdit(AdjustClipping)
self.nearEdit.setObjectName(u"nearEdit")
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.nearEdit.sizePolicy().hasHeightForWidth())
self.nearEdit.setSizePolicy(sizePolicy)
self.verticalLayout_3.addWidget(self.nearEdit)
self.farEdit = QLineEdit(AdjustClipping)
self.farEdit.setObjectName(u"farEdit")
sizePolicy.setHeightForWidth(self.farEdit.sizePolicy().hasHeightForWidth())
self.farEdit.setSizePolicy(sizePolicy)
self.verticalLayout_3.addWidget(self.farEdit)
self.horizontalLayout.addLayout(self.verticalLayout_3)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(AdjustClipping)
QMetaObject.connectSlotsByName(AdjustClipping)
# setupUi
def retranslateUi(self, AdjustClipping):
AdjustClipping.setProperty("comment", QCoreApplication.translate("AdjustClipping", u"\n"
" Copyright 2016 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
AdjustClipping.setWindowTitle(QCoreApplication.translate("AdjustClipping", u"Adjust Clipping Planes", None))
self.overrideNear.setText(QCoreApplication.translate("AdjustClipping", u"Override Near", None))
self.overrideFar.setText(QCoreApplication.translate("AdjustClipping", u"Override Far", None))
# retranslateUi
| 5,182 | Python | 49.320388 | 116 | 0.578155 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primLegendUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'primLegendUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_PrimLegend(object):
def setupUi(self, PrimLegend):
if not PrimLegend.objectName():
PrimLegend.setObjectName(u"PrimLegend")
PrimLegend.resize(438, 131)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(PrimLegend.sizePolicy().hasHeightForWidth())
PrimLegend.setSizePolicy(sizePolicy)
self.primLegendLayoutContainer = QVBoxLayout(PrimLegend)
self.primLegendLayoutContainer.setObjectName(u"primLegendLayoutContainer")
self.primLegendLayout = QGridLayout()
self.primLegendLayout.setObjectName(u"primLegendLayout")
self.primLegendColorHasArcs = QGraphicsView(PrimLegend)
self.primLegendColorHasArcs.setObjectName(u"primLegendColorHasArcs")
self.primLegendColorHasArcs.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorHasArcs, 0, 0, 1, 1)
self.primLegendLabelHasArcs = QLabel(PrimLegend)
self.primLegendLabelHasArcs.setObjectName(u"primLegendLabelHasArcs")
font = QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.primLegendLabelHasArcs.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelHasArcs, 0, 1, 1, 1)
self.primLegendColorInstance = QGraphicsView(PrimLegend)
self.primLegendColorInstance.setObjectName(u"primLegendColorInstance")
self.primLegendColorInstance.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorInstance, 0, 2, 1, 1)
self.primLegendLabelInstance = QLabel(PrimLegend)
self.primLegendLabelInstance.setObjectName(u"primLegendLabelInstance")
self.primLegendLabelInstance.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelInstance, 0, 3, 1, 1)
self.primLegendColorMaster = QGraphicsView(PrimLegend)
self.primLegendColorMaster.setObjectName(u"primLegendColorMaster")
self.primLegendColorMaster.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorMaster, 0, 4, 1, 1)
self.primLegendLabelMaster = QLabel(PrimLegend)
self.primLegendLabelMaster.setObjectName(u"primLegendLabelMaster")
self.primLegendLabelMaster.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelMaster, 0, 5, 1, 1)
self.primLegendColorNormal = QGraphicsView(PrimLegend)
self.primLegendColorNormal.setObjectName(u"primLegendColorNormal")
self.primLegendColorNormal.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorNormal, 0, 6, 1, 1)
self.primLegendLabelNormal = QLabel(PrimLegend)
self.primLegendLabelNormal.setObjectName(u"primLegendLabelNormal")
self.primLegendLabelNormal.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelNormal, 0, 7, 1, 1)
self.primLegendLayoutContainer.addLayout(self.primLegendLayout)
self.primLegendLabelContainer = QVBoxLayout()
self.primLegendLabelContainer.setObjectName(u"primLegendLabelContainer")
self.primLegendLabelDimmed = QLabel(PrimLegend)
self.primLegendLabelDimmed.setObjectName(u"primLegendLabelDimmed")
self.primLegendLabelContainer.addWidget(self.primLegendLabelDimmed)
self.primLegendLabelFontsAbstract = QLabel(PrimLegend)
self.primLegendLabelFontsAbstract.setObjectName(u"primLegendLabelFontsAbstract")
self.primLegendLabelContainer.addWidget(self.primLegendLabelFontsAbstract)
self.primLegendLabelFontsUndefined = QLabel(PrimLegend)
self.primLegendLabelFontsUndefined.setObjectName(u"primLegendLabelFontsUndefined")
self.primLegendLabelContainer.addWidget(self.primLegendLabelFontsUndefined)
self.primLegendLabelFontsDefined = QLabel(PrimLegend)
self.primLegendLabelFontsDefined.setObjectName(u"primLegendLabelFontsDefined")
self.primLegendLabelContainer.addWidget(self.primLegendLabelFontsDefined)
self.primLegendLayoutContainer.addLayout(self.primLegendLabelContainer)
self.retranslateUi(PrimLegend)
QMetaObject.connectSlotsByName(PrimLegend)
# setupUi
def retranslateUi(self, PrimLegend):
PrimLegend.setProperty("comment", QCoreApplication.translate("PrimLegend", u"\n"
" Copyright 2017 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
self.primLegendLabelHasArcs.setText(QCoreApplication.translate("PrimLegend", u"HasArcs", None))
self.primLegendLabelInstance.setText(QCoreApplication.translate("PrimLegend", u"Instance", None))
self.primLegendLabelMaster.setText(QCoreApplication.translate("PrimLegend", u"Master", None))
self.primLegendLabelNormal.setText(QCoreApplication.translate("PrimLegend", u"Normal", None))
self.primLegendLabelDimmed.setText(QCoreApplication.translate("PrimLegend", u"Dimmed colors denote inactive prims", None))
self.primLegendLabelFontsAbstract.setText(QCoreApplication.translate("PrimLegend", u"Normal font indicates abstract prims(class and children)", None))
self.primLegendLabelFontsUndefined.setText(QCoreApplication.translate("PrimLegend", u"Italic font indicates undefined prims(declared with over)", None))
self.primLegendLabelFontsDefined.setText(QCoreApplication.translate("PrimLegend", u"Bold font indicates defined prims(declared with def)", None))
# retranslateUi
| 8,092 | Python | 52.596026 | 160 | 0.652373 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/usdviewContextMenuItem.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
#
# A base class for all context menu items.
# This provides a simple behavior to ensure that a chosen
# context menu item is valid. This helps us avoid a situation
# in which a user right-clicks in an area with no item but still
# receives a context menu.
#
class UsdviewContextMenuItem():
def isValid(self):
''' Menu items which have an invalid internal item are considered invalid.
Header menus don't contain an internal _item attribute, so we
return true in the case of the attribute being undefined.
We use this function to give this state a clearer name.
'''
return not hasattr(self, "_item") or self._item is not None
| 1,748 | Python | 43.846153 | 82 | 0.736842 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primContextMenu.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtWidgets
from .primContextMenuItems import _GetContextMenuItems
#
# Specialized context menu for prim selection.
#
# It uses the per-prim context menus referenced by the _GetContextMenuItems
# function in primContextMenuItems. To add a new context menu item,
# see comments in that file.
#
class PrimContextMenu(QtWidgets.QMenu):
def __init__(self, parent, item, appController):
QtWidgets.QMenu.__init__(self, parent)
self._menuItems = _GetContextMenuItems(appController, item)
for menuItem in self._menuItems:
if menuItem.IsSeparator():
self.addSeparator()
continue
elif not menuItem.isValid():
continue
action = self.addAction(menuItem.GetText(),
menuItem.RunCommand)
if not menuItem.IsEnabled():
action.setEnabled( False )
| 1,984 | Python | 36.45283 | 75 | 0.703629 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/customAttributes.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd, UsdGeom, UsdShade
from .constantGroup import ConstantGroup
class ComputedPropertyNames(ConstantGroup):
"""Names of all available computed properties."""
WORLD_BBOX = "World Bounding Box"
LOCAL_WORLD_XFORM = "Local to World Xform"
RESOLVED_PREVIEW_MATERIAL = "Resolved Preview Material"
RESOLVED_FULL_MATERIAL = "Resolved Full Material"
#
# Edit the following to alter the set of custom attributes.
#
# Every entry should be an object derived from CustomAttribute,
# defined below.
#
def _GetCustomAttributes(currentPrim, rootDataModel):
currentPrimIsImageable = currentPrim.IsA(UsdGeom.Imageable)
# If the currentPrim is imageable or if it is a typeless def, it
# participates in imageable computations.
currentPrimGetsImageableComputations = currentPrim.IsA(UsdGeom.Imageable) \
or not currentPrim.GetTypeName()
if currentPrimGetsImageableComputations:
return [BoundingBoxAttribute(currentPrim, rootDataModel),
LocalToWorldXformAttribute(currentPrim,
rootDataModel),
ResolvedPreviewMaterial(currentPrim, rootDataModel),
ResolvedFullMaterial(currentPrim, rootDataModel)]
return []
#
# The base class for per-prim custom attributes.
#
class CustomAttribute:
def __init__(self, currentPrim, rootDataModel):
self._currentPrim = currentPrim
self._rootDataModel = rootDataModel
def IsVisible(self):
return True
# GetName function to match UsdAttribute API
def GetName(self):
return ""
# Get function to match UsdAttribute API
def Get(self, frame):
return ""
# convenience function to make this look more like a UsdAttribute
def GetTypeName(self):
return ""
# GetPrimPath function to match UsdAttribute API
def GetPrimPath(self):
return self._currentPrim.GetPath()
#
# Displays the bounding box of a prim
#
class BoundingBoxAttribute(CustomAttribute):
def __init__(self, currentPrim, rootDataModel):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
def GetName(self):
return ComputedPropertyNames.WORLD_BBOX
def Get(self, frame):
try:
bbox = self._rootDataModel.computeWorldBound(self._currentPrim)
bbox = bbox.ComputeAlignedRange()
except RuntimeError as err:
bbox = "Invalid: " + str(err)
return bbox
#
# Displays the Local to world xform of a prim
#
class LocalToWorldXformAttribute(CustomAttribute):
def __init__(self, currentPrim, rootDataModel):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
def GetName(self):
return ComputedPropertyNames.LOCAL_WORLD_XFORM
def Get(self, frame):
try:
pwt = self._rootDataModel.getLocalToWorldTransform(self._currentPrim)
except RuntimeError as err:
pwt = "Invalid: " + str(err)
return pwt
class ResolvedBoundMaterial(CustomAttribute):
def __init__(self, currentPrim, rootDataModel, purpose):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
self._purpose = purpose
def GetName(self):
if self._purpose == UsdShade.Tokens.full:
return ComputedPropertyNames.RESOLVED_FULL_MATERIAL
elif self._purpose == UsdShade.Tokens.preview:
return ComputedPropertyNames.RESOLVED_PREVIEW_MATERIAL
else:
raise ValueError("Invalid purpose '{}'.".format(self._purpose))
def Get(self, frame):
try:
(boundMaterial, bindingRel) = \
self._rootDataModel.computeBoundMaterial(self._currentPrim,
self._purpose)
boundMatPath = boundMaterial.GetPrim().GetPath() if boundMaterial \
else "<unbound>"
except RuntimeError as err:
boundMatPath = "Invalid: " + str(err)
return boundMatPath
class ResolvedFullMaterial(ResolvedBoundMaterial):
def __init__(self, currentPrim, rootDataModel):
ResolvedBoundMaterial.__init__(self, currentPrim, rootDataModel,
UsdShade.Tokens.full)
class ResolvedPreviewMaterial(ResolvedBoundMaterial):
def __init__(self, currentPrim, rootDataModel):
ResolvedBoundMaterial.__init__(self, currentPrim, rootDataModel,
UsdShade.Tokens.preview)
class ComputedPropertyFactory:
"""Creates computed properties."""
def __init__(self, rootDataModel):
self._rootDataModel = rootDataModel
def getComputedProperty(self, prim, propName):
"""Create a new computed property from a prim and property name."""
if propName == ComputedPropertyNames.WORLD_BBOX:
return BoundingBoxAttribute(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.LOCAL_WORLD_XFORM:
return LocalToWorldXformAttribute(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.RESOLVED_FULL_MATERIAL:
return ResolvedFullMaterial(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.RESOLVED_PREVIEW_MATERIAL:
return ResolvedPreviewMaterial(prim, self._rootDataModel)
else:
raise ValueError("Cannot create computed property '{}'.".format(
propName))
| 6,465 | Python | 35.325842 | 81 | 0.685538 |
USwampertor/OmniverseJS/ov/python/pxr/Tf/__init__.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
"""
Tf -- Tools Foundation
"""
def PrepareModule(module, result):
"""PrepareModule(module, result) -- Prepare an extension module at import
time. Generally, this should only be called by the __init__.py script for a
module upon loading a boost python module (generally '_LibName.so')."""
# inject into result.
ignore = frozenset(['__name__', '__builtins__',
'__doc__', '__file__', '__path__'])
newModuleName = result.get('__name__')
for key, value in list(module.__dict__.items()):
if not key in ignore:
result[key] = value
# Lie about the module from which value came.
if newModuleName and hasattr(value, '__module__'):
try:
setattr(value, '__module__', newModuleName)
except AttributeError as e:
# The __module__ attribute of Boost.Python.function
# objects is not writable, so we get this exception
# a lot. Just ignore it. We're really only concerned
# about the data objects like enum values and such.
#
pass
def GetCodeLocation(framesUp):
"""Returns a tuple (moduleName, functionName, fileName, lineNo).
To trace the current location of python execution, use GetCodeLocation().
By default, the information is returned at the current stack-frame; thus
info = GetCodeLocation()
will return information about the line that GetCodeLocation() was called
from. One can write:
def genericDebugFacility():
info = GetCodeLocation(1)
# print out data
def someCode():
...
if bad:
genericDebugFacility()
and genericDebugFacility() will get information associated with its caller,
i.e. the function someCode()."""
import sys
f_back = sys._getframe(framesUp).f_back
return (f_back.f_globals['__name__'], f_back.f_code.co_name,
f_back.f_code.co_filename, f_back.f_lineno)
# for some strange reason, this errors out when we try to reload it,
# which is odd since _tf is a DSO and can't be reloaded anyway:
import sys
if "pxr.Tf._tf" not in sys.modules:
from . import _tf
PrepareModule(_tf, locals())
del _tf
del sys
# Need to provide an exception type that tf errors will show up as.
class ErrorException(RuntimeError):
def __init__(self, *args):
RuntimeError.__init__(self, *args)
self.__TfException = True
def __str__(self):
return '\n\t' + '\n\t'.join([str(e) for e in self.args])
__SetErrorExceptionClass(ErrorException)
try:
from . import __DOC
__DOC.Execute(locals())
del __DOC
except Exception:
pass
def Warn(msg, template=""):
"""Issue a warning via the TfDiagnostic system.
At this time, template is ignored.
"""
codeInfo = GetCodeLocation(framesUp=1)
_Warn(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def Status(msg, verbose=True):
"""Issues a status update to the Tf diagnostic system.
If verbose is True (the default) then information about where in the code
the status update was issued from is included.
"""
if verbose:
codeInfo = GetCodeLocation(framesUp=1)
_Status(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
else:
_Status(msg, "", "", "", 0)
def RaiseCodingError(msg):
"""Raise a coding error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_RaiseCodingError(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def RaiseRuntimeError(msg):
"""Raise a runtime error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_RaiseRuntimeError(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def Fatal(msg):
"""Raise a fatal error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_Fatal(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
class NamedTemporaryFile(object):
"""A named temporary file which keeps the internal file handle closed.
A class which constructs a temporary file(that isn't open) on __enter__,
provides its name as an attribute, and deletes it on __exit__.
Note: The constructor args for this object match those of
python's tempfile.mkstemp() function, and will have the same effect on
the underlying file created."""
def __init__(self, suffix='', prefix='', dir=None, text=False):
# Note that we defer creation until the enter block to
# prevent users from unintentionally creating a bunch of
# temp files that don't get cleaned up.
self._args = (suffix, prefix, dir, text)
def __enter__(self):
from tempfile import mkstemp
from os import close
fd, path = mkstemp(*self._args)
close(fd)
# XXX: We currently only expose the name attribute
# more can be added based on client needs in the future.
self._name = path
return self
def __exit__(self, *args):
import os
os.remove(self.name)
@property
def name(self):
"""The path for the temporary file created."""
return self._name
| 6,386 | Python | 34.681564 | 80 | 0.644065 |
USwampertor/OmniverseJS/ov/python/pxr/Tf/testenv/testTfScriptModuleLoader_Unknown.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Tf
# Register this library with a new, previously unknown dependency. Note, we're
# just using 'sys' as the module to load here, which is a lie. It should really
# be this module, but it doesn't matter, and it's not trivial to come up with a
# robust, correct module name for this module.
Tf.ScriptModuleLoader()._RegisterLibrary('Unknown', 'sys',
['NewDynamicDependency'])
# Register the dependency. In this case we use 'sys' just because it saves us
# from creating a real module called NewDynamicDependency.
Tf.ScriptModuleLoader()._RegisterLibrary('NewDynamicDependency', 'sys', [])
# Load dependencies for this module, which includes the
# NewDynamicDependency. This is a reentrant load that will be handled
# immediately by TfScriptModuleLoader.
Tf.ScriptModuleLoader()._LoadModulesForLibrary('Unknown')
| 1,934 | Python | 43.999999 | 80 | 0.751293 |
USwampertor/OmniverseJS/ov/python/pxr/UsdUtils/complianceChecker.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from pxr import Ar
def _IsPackageOrPackagedLayer(layer):
return layer.GetFileFormat().IsPackage() or \
Ar.IsPackageRelativePath(layer.identifier)
class BaseRuleChecker(object):
"""This is Base class for all the rule-checkers."""
def __init__(self, verbose):
self._verbose = verbose
self._failedChecks = []
self._errors = []
def _AddFailedCheck(self, msg):
self._failedChecks.append(msg)
def _AddError(self, msg):
self._errors.append(msg)
def _Msg(self, msg):
if self._verbose:
print(msg)
def GetFailedChecks(self):
return self._failedChecks
def GetErrors(self):
return self._errors
# -------------------------------------------------------------------------
# Virtual methods that any derived rule-checker may want to override.
# Default implementations do nothing.
#
# A rule-checker may choose to override one or more of the virtual methods.
# The callbacks are invoked in the order they are defined here (i.e.
# CheckStage is invoked first, followed by CheckDiagnostics, followed by
# CheckUnresolvedPaths and so on until CheckPrim). Some of the callbacks may
# be invoked multiple times per-rule with different parameters, for example,
# CheckLayer, CheckPrim and CheckZipFile.
def CheckStage(self, usdStage):
""" Check the given usdStage. """
pass
def CheckDiagnostics(self, diagnostics):
""" Check the diagnostic messages that were generated when opening the
USD stage. The diagnostic messages are collected using a
UsdUtilsCoalescingDiagnosticDelegate.
"""
pass
def CheckUnresolvedPaths(self, unresolvedPaths):
""" Check or process any unresolved asset paths that were found when
analysing the dependencies.
"""
pass
def CheckDependencies(self, usdStage, layerDeps, assetDeps):
""" Check usdStage's layer and asset dependencies that were gathered
using UsdUtils.ComputeAllDependencies().
"""
pass
def CheckLayer(self, layer):
""" Check the given SdfLayer. """
pass
def CheckZipFile(self, zipFile, packagePath):
""" Check the zipFile object created by opening the package at path
packagePath.
"""
pass
def CheckPrim(self, prim):
""" Check the given prim, which may only exist is a specific combination
of variant selections on the UsdStage.
"""
pass
# -------------------------------------------------------------------------
class ByteAlignmentChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "Files within a usdz package must be laid out properly, "\
"i.e. they should be aligned to 64 bytes."
def __init__(self, verbose):
super(ByteAlignmentChecker, self).__init__(verbose)
def CheckZipFile(self, zipFile, packagePath):
fileNames = zipFile.GetFileNames()
for fileName in fileNames:
fileExt = Ar.GetResolver().GetExtension(fileName)
fileInfo = zipFile.GetFileInfo(fileName)
offset = fileInfo.dataOffset
if offset % 64 != 0:
self._AddFailedCheck("File '%s' in package '%s' has an "
"invalid offset %s." %
(fileName, packagePath, offset))
class CompressionChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "Files withing a usdz package should not be compressed or "\
"encrypted."
def __init__(self, verbose):
super(CompressionChecker, self).__init__(verbose)
def CheckZipFile(self, zipFile, packagePath):
fileNames = zipFile.GetFileNames()
for fileName in fileNames:
fileExt = Ar.GetResolver().GetExtension(fileName)
fileInfo = zipFile.GetFileInfo(fileName)
if fileInfo.compressionMethod != 0:
self._AddFailedCheck("File '%s' in package '%s' has "
"compression. Compression method is '%s', actual size "
"is %s. Uncompressed size is %s." % (
fileName, packagePath, fileInfo.compressionMethod,
fileInfo.size, fileInfo.uncompressedSize))
class MissingReferenceChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "The composed USD stage should not contain any unresolvable"\
" asset dependencies (in every possible variation of the "\
"asset), when using the default asset resolver. "
def __init__(self, verbose):
super(MissingReferenceChecker, self).__init__(verbose)
def CheckDiagnostics(self, diagnostics):
for diag in diagnostics:
# "_ReportErrors" is the name of the function that issues
# warnings about unresolved references, sublayers and other
# composition arcs.
if '_ReportErrors' in diag.sourceFunction and \
'usd/stage.cpp' in diag.sourceFileName:
self._AddFailedCheck(diag.commentary)
def CheckUnresolvedPaths(self, unresolvedPaths):
for unresolvedPath in unresolvedPaths:
self._AddFailedCheck("Found unresolvable external dependency "
"'%s'." % unresolvedPath)
class TextureChecker(BaseRuleChecker):
# Allow just png and jpg for now.
_allowedImageFormats = ("jpg", "png")
# Include a list of "unsupported" image formats to provide better error
# messages whwn we find one of these.
_unsupportedImageFormats = ["bmp", "tga", "hdr", "exr", "tif", "zfile",
"tx"]
@staticmethod
def GetDescription():
return "Texture files should be .jpg or .png."
def __init__(self, verbose):
# Check if the prim has an allowed type.
super(TextureChecker, self).__init__(verbose)
def _CheckTexture(self, texAssetPath):
self._Msg("Checking texture <%s>." % texAssetPath)
texFileExt = Ar.GetResolver().GetExtension(texAssetPath).lower()
if texFileExt in \
TextureChecker._unsupportedImageFormats:
self._AddFailedCheck("Found texture file '%s' with unsupported "
"file format." % texAssetPath)
elif texFileExt not in \
TextureChecker._allowedImageFormats:
self._AddFailedCheck("Found texture file '%s' with unknown file "
"format." % texAssetPath)
def CheckPrim(self, prim):
# Right now, we find texture referenced by looking at the asset-valued
# shader inputs. However, it is entirely legal to feed the "fileName"
# input of a UsdUVTexture shader from a UsdPrimvarReader_string.
# Hence, ideally we would also check "the right" primvars on
# geometry prims here. However, identifying the right primvars is
# non-trivial. We probably need to pre-analyze all the materials.
# Not going to try to do this yet, but it raises an interesting
# validation pattern -
from pxr import Sdf, UsdShade
# Check if the prim is a shader.
if not prim.IsA(UsdShade.Shader):
return
shader = UsdShade.Shader(prim)
shaderInputs = shader.GetInputs()
for ip in shaderInputs:
if ip.GetTypeName() == Sdf.ValueTypeNames.Asset:
texFilePath = str(ip.Get()).strip('@')
self._CheckTexture(texFilePath)
elif ip.GetTypeName() == Sdf.ValueTypeNames.AssetArray:
texPathArray = ip.Get()
texPathArray = [str(i).strip('@') for i in texPathArray]
for texPath in texPathArray:
self._CheckTexture(texFilePath)
class ARKitPackageEncapsulationChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "If the root layer is a package, then the composed stage "\
"should not contain references to files outside the package. "\
"In other words, the package should be entirely self-contained."
def __init__(self, verbose):
super(ARKitPackageEncapsulationChecker, self).__init__(verbose)
def CheckDependencies(self, usdStage, layerDeps, assetDeps):
rootLayer = usdStage.GetRootLayer()
if not _IsPackageOrPackagedLayer(rootLayer):
return
packagePath = usdStage.GetRootLayer().realPath
if packagePath:
if Ar.IsPackageRelativePath(packagePath):
packagePath = Ar.SplitPackageRelativePathOuter(
packagePath)[0]
for layer in layerDeps:
# In-memory layers like session layers (which we must skip when
# doing this check) won't have a real path.
if layer.realPath:
if not layer.realPath.startswith(packagePath):
self._AddFailedCheck("Found loaded layer '%s' that "
"does not belong to the package '%s'." %
(layer.identifier, packagePath))
for asset in assetDeps:
if not asset.startswith(packagePath):
self._AddFailedCheck("Found asset reference '%s' that "
"does not belong to the package '%s'." %
(asset, packagePath))
class ARKitLayerChecker(BaseRuleChecker):
# Only core USD file formats are allowed.
_allowedLayerFormatIds = ('usd', 'usda', 'usdc', 'usdz')
@staticmethod
def GetDescription():
return "All included layers that participate in composition should"\
" have one of the core supported file formats."
def __init__(self, verbose):
# Check if the prim has an allowed type.
super(ARKitLayerChecker, self).__init__(verbose)
def CheckLayer(self, layer):
self._Msg("Checking layer <%s>." % layer.identifier)
formatId = layer.GetFileFormat().formatId
if not formatId in \
ARKitLayerChecker._allowedLayerFormatIds:
self._AddFailedCheck("Layer '%s' has unsupported formatId "
"'%s'." % (layer.identifier, formatId))
class ARKitPrimTypeChecker(BaseRuleChecker):
# All core prim types other than UsdGeomPointInstancers, Curve types, Nurbs,
# and the types in UsdLux are allowed.
_allowedPrimTypeNames = ('', 'Scope', 'Xform', 'Camera',
'Shader', 'Material',
'Mesh', 'Sphere', 'Cube', 'Cylinder', 'Cone',
'Capsule', 'GeomSubset', 'Points',
'SkelRoot', 'Skeleton', 'SkelAnimation',
'BlendShape', 'SpatialAudio')
@staticmethod
def GetDescription():
return "UsdGeomPointInstancers and custom schemas not provided by "\
"core USD are not allowed."
def __init__(self, verbose):
# Check if the prim has an allowed type.
super(ARKitPrimTypeChecker, self).__init__(verbose)
def CheckPrim(self, prim):
self._Msg("Checking prim <%s>." % prim.GetPath())
if prim.GetTypeName() not in \
ARKitPrimTypeChecker._allowedPrimTypeNames:
self._AddFailedCheck("Prim <%s> has unsupported type '%s'." %
(prim.GetPath(), prim.GetTypeName()))
class ARKitStageYupChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "The stage and all fo the assets referenced within it "\
"should be Y-up.",
def __init__(self, verbose):
# Check if the prim has an allowed type.
super(ARKitStageYupChecker, self).__init__(verbose)
def CheckStage(self, usdStage):
from pxr import UsdGeom
upAxis = UsdGeom.GetStageUpAxis(usdStage)
if upAxis != UsdGeom.Tokens.y:
self._AddFailedCheck("Stage has upAxis '%s'. upAxis should be "
"'%s'." % (upAxis, UsdGeom.Tokens.y))
class ARKitShaderChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "Shader nodes must have \"id\" as the implementationSource, " \
"with id values that begin with \"Usd*\". Also, shader inputs "\
"with connections must each have a single, valid connection " \
"source."
def __init__(self, verbose):
super(ARKitShaderChecker, self).__init__(verbose)
def CheckPrim(self, prim):
from pxr import UsdShade
if not prim.IsA(UsdShade.Shader):
return
shader = UsdShade.Shader(prim)
if not shader:
self._AddError("Invalid shader prim <%s>." % prim.GetPath())
return
self._Msg("Checking shader <%s>." % prim.GetPath())
implSource = shader.GetImplementationSource()
if implSource != UsdShade.Tokens.id:
self._AddFailedCheck("Shader <%s> has non-id implementation "
"source '%s'." % (prim.GetPath(), implSource))
shaderId = shader.GetShaderId()
if not shaderId or \
not (shaderId in ['UsdPreviewSurface', 'UsdUVTexture'] or
shaderId.startswith('UsdPrimvarReader')) :
self._AddFailedCheck("Shader <%s> has unsupported info:id '%s'."
% (prim.GetPath(), shaderId))
# Check shader input connections
shaderInputs = shader.GetInputs()
for shdInput in shaderInputs:
connections = shdInput.GetAttr().GetConnections()
# If an input has one or more connections, ensure that the
# connections are valid.
if len(connections) > 0:
if len(connections) > 1:
self._AddFailedCheck("Shader input <%s> has %s connection "
"sources, but only one is allowed." %
(shdInput.GetAttr.GetPath(), len(connections)))
connectedSource = shdInput.GetConnectedSource()
if connectedSource is None:
self._AddFailedCheck("Connection source <%s> for shader "
"input <%s> is missing." % (connections[0],
shdInput.GetAttr().GetPath()))
else:
# The source must be a valid shader or material prim.
source = connectedSource[0]
if not source.GetPrim().IsA(UsdShade.Shader) and \
not source.GetPrim().IsA(UsdShade.Material):
self._AddFailedCheck("Shader input <%s> has an invalid "
"connection source prim of type '%s'." %
(shdInput.GetAttr().GetPath(),
source.GetPrim().GetTypeName()))
class ARKitMaterialBindingChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "All material binding relationships must have valid targets."
def __init__(self, verbose):
super(ARKitMaterialBindingChecker, self).__init__(verbose)
def CheckPrim(self, prim):
from pxr import UsdShade
relationships = prim.GetRelationships()
bindingRels = [rel for rel in relationships if
rel.GetName().startswith(UsdShade.Tokens.materialBinding)]
for bindingRel in bindingRels:
targets = bindingRel.GetTargets()
if len(targets) == 1:
directBinding = UsdShade.MaterialBindingAPI.DirectBinding(
bindingRel)
if not directBinding.GetMaterial():
self._AddFailedCheck("Direct material binding <%s> targets "
"an invalid material <%s>." % (bindingRel.GetPath(),
directBinding.GetMaterialPath()))
elif len(targets) == 2:
collBinding = UsdShade.MaterialBindingAPI.CollectionBinding(
bindingRel)
if not collBinding.GetMaterial():
self._AddFailedCheck("Collection-based material binding "
"<%s> targets an invalid material <%s>." %
(bindingRel.GetPath(), collBinding.GetMaterialPath()))
if not collBinding.GetCollection():
self._AddFailedCheck("Collection-based material binding "
"<%s> targets an invalid collection <%s>." %
(bindingRel.GetPath(), collBinding.GetCollectionPath()))
class ARKitFileExtensionChecker(BaseRuleChecker):
_allowedFileExtensions = \
ARKitLayerChecker._allowedLayerFormatIds + \
TextureChecker._allowedImageFormats
@staticmethod
def GetDescription():
return "Only layer files and textures are allowed in a package."
def __init__(self, verbose):
super(ARKitFileExtensionChecker, self).__init__(verbose)
def CheckZipFile(self, zipFile, packagePath):
fileNames = zipFile.GetFileNames()
for fileName in fileNames:
fileExt = Ar.GetResolver().GetExtension(fileName)
if fileExt not in ARKitFileExtensionChecker._allowedFileExtensions:
self._AddFailedCheck("File '%s' in package '%s' has an "
"unknown or unsupported extension '%s'." %
(fileName, packagePath, fileExt))
class ARKitRootLayerChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "The root layer of the package must be a usdc file and " \
"must not include any external dependencies that participate in "\
"stage composition."
def __init__(self, verbose):
super(ARKitRootLayerChecker, self).__init__(verbose=verbose)
def CheckStage(self, usdStage):
usedLayers = usdStage.GetUsedLayers()
# This list excludes any session layers.
usedLayersOnDisk = [i for i in usedLayers if i.realPath]
if len(usedLayersOnDisk) > 1:
self._AddFailedCheck("The stage uses %s layers. It should "
"contain a single usdc layer to be compatible with ARKit's "
"implementation of usdz." % len(usedLayersOnDisk))
rootLayerRealPath = usdStage.GetRootLayer().realPath
if rootLayerRealPath.endswith(".usdz"):
# Check if the root layer in the package is a usdc.
from pxr import Usd
zipFile = Usd.ZipFile.Open(rootLayerRealPath)
if not zipFile:
self._AddError("Could not open package at path '%s'." %
resolvedPath)
return
fileNames = zipFile.GetFileNames()
if not fileNames[0].endswith(".usdc"):
self._AddFailedCheck("First file (%s) in usdz package '%s' "
"does not have the .usdc extension." % (fileNames[0],
rootLayerRealPath))
elif not rootLayerRealPath.endswith(".usdc"):
self._AddFailedCheck("Root layer of the stage '%s' does not "
"have the '.usdc' extension." % (rootLayerRealPath))
class ComplianceChecker(object):
""" A utility class for checking compliance of a given USD asset or a USDZ
package.
Since usdz files are zip files, someone could use generic zip tools to
create an archive and just change the extension, producing a .usdz file that
does not honor the additional constraints that usdz files require. Even if
someone does use our official archive creation tools, though, we
intentionally allow creation of usdz files that can be very "permissive" in
their contents for internal studio uses, where portability outside the
studio is not a concern. For content meant to be delivered over the web
(eg. ARKit assets), however, we must be much more restrictive.
This class provides two levels of compliance checking:
* "structural" validation that is represented by a set of base rules.
* "ARKit" compatibility validation, which includes many more restrictions.
Calling ComplianceChecker.DumpAllRules() will print an enumeration of the
various rules in the two categories of compliance checking.
"""
@staticmethod
def GetBaseRules():
return [ByteAlignmentChecker, CompressionChecker,
MissingReferenceChecker, TextureChecker]
@staticmethod
def GetARKitRules(skipARKitRootLayerCheck=False):
arkitRules = [ARKitLayerChecker, ARKitPrimTypeChecker,
ARKitStageYupChecker, ARKitShaderChecker,
ARKitMaterialBindingChecker,
ARKitFileExtensionChecker,
ARKitPackageEncapsulationChecker]
if not skipARKitRootLayerCheck:
arkitRules.append(ARKitRootLayerChecker)
return arkitRules
@staticmethod
def GetRules(arkit=False, skipARKitRootLayerCheck=False):
allRules = ComplianceChecker.GetBaseRules()
if arkit:
arkitRules = ComplianceChecker.GetARKitRules(
skipARKitRootLayerCheck=skipARKitRootLayerCheck)
allRules += arkitRules
return allRules
@staticmethod
def DumpAllRules():
print('Base rules:')
for ruleNum, rule in enumerate(GetBaseRules()):
print('[%s] %s' % (ruleNum + 1, rule.GetDescription()))
print('-' * 30)
print('ARKit rules: ')
for ruleNum, rule in enumerate(GetBaseRules()):
print('[%s] %s' % (ruleNum + 1, rule.GetDescription()))
print('-' * 30)
def __init__(self, arkit=False, skipARKitRootLayerCheck=False,
rootPackageOnly=False, skipVariants=False, verbose=False):
self._rootPackageOnly = rootPackageOnly
self._doVariants = not skipVariants
self._verbose = verbose
self._errors = []
# Once a package has been checked, it goes into this set.
self._checkedPackages = set()
# Instantiate an instance of every rule checker and store in a list.
self._rules = [Rule(self._verbose) for Rule in
ComplianceChecker.GetRules(arkit, skipARKitRootLayerCheck)]
def _Msg(self, msg):
if self._verbose:
print(msg)
def _AddError(self, errMsg):
self._errors.append(errMsg)
def GetErrors(self):
errors = self._errors
for rule in self._rules:
errs = rule.GetErrors()
for err in errs:
errors.append("Error checking rule '%s': %s" %
(type(rule).__name__, err))
return errors
def DumpRules(self):
descriptions = [rule.GetDescription() for rule in self._rules]
print('Checking rules: ')
for ruleNum, rule in enumerate(descriptions):
print('[%s] %s' % (ruleNum + 1, rule))
print('-' * 30)
def GetFailedChecks(self):
failedChecks = []
for rule in self._rules:
fcs = rule.GetFailedChecks()
for fc in fcs:
failedChecks.append("%s (fails '%s')" % (fc,
type(rule).__name__))
return failedChecks
def CheckCompliance(self, inputFile):
from pxr import Sdf, Usd, UsdUtils
if not Usd.Stage.IsSupportedFile(inputFile):
_AddError("Cannot open file '%s' on a USD stage." % args.inputFile)
return
# Collect all warnings using a diagnostic delegate.
delegate = UsdUtils.CoalescingDiagnosticDelegate()
usdStage = Usd.Stage.Open(inputFile)
stageOpenDiagnostics = delegate.TakeUncoalescedDiagnostics()
for rule in self._rules:
rule.CheckStage(usdStage)
rule.CheckDiagnostics(stageOpenDiagnostics)
with Ar.ResolverContextBinder(usdStage.GetPathResolverContext()):
# This recursively computes all of inputFiles's external
# dependencies.
(allLayers, allAssets, unresolvedPaths) = \
UsdUtils.ComputeAllDependencies(Sdf.AssetPath(inputFile))
for rule in self._rules:
rule.CheckUnresolvedPaths(unresolvedPaths)
rule.CheckDependencies(usdStage, allLayers, allAssets)
if self._rootPackageOnly:
rootLayer = usdStage.GetRootLayer()
if rootLayer.GetFileFormat().IsPackage():
packagePath = Ar.SplitPackageRelativePathInner(
rootLayer.identifier)[0]
self._CheckPackage(packagePath)
else:
self._AddError("Root layer of the USD stage (%s) doesn't belong to "
"a package, but 'rootPackageOnly' is True!" %
Usd.Describe(usdStage))
else:
# Process every package just once by storing them all in a set.
packages = set()
for layer in allLayers:
if _IsPackageOrPackagedLayer(layer):
packagePath = Ar.SplitPackageRelativePathInner(
layer.identifier)[0]
packages.add(packagePath)
self._CheckLayer(layer)
for package in packages:
self._CheckPackage(package)
# Traverse the entire stage and check every prim.
from pxr import Usd
# Author all variant switches in the session layer.
usdStage.SetEditTarget(usdStage.GetSessionLayer())
allPrimsIt = iter(Usd.PrimRange.Stage(usdStage,
Usd.TraverseInstanceProxies()))
self._TraverseRange(allPrimsIt, isStageRoot=True)
def _CheckPackage(self, packagePath):
self._Msg("Checking package <%s>." % packagePath)
# XXX: Should we open the package on a stage to ensure that it is valid
# and entirely self-contained.
from pxr import Usd
pkgExt = Ar.GetResolver().GetExtension(packagePath)
if pkgExt != "usdz":
self._AddError("Package at path %s has an invalid extension."
% packagePath)
return
# Check the parent package first.
if Ar.IsPackageRelativePath(packagePath):
parentPackagePath = Ar.SplitPackageRelativePathInner(packagePath)[0]
self._CheckPackage(parentPackagePath)
# Avoid checking the same parent package multiple times.
if packagePath in self._checkedPackages:
return
self._checkedPackages.add(packagePath)
resolvedPath = Ar.GetResolver().Resolve(packagePath)
if len(resolvedPath) == 0:
self._AddError("Failed to resolve package path '%s'." % packagePath)
return
zipFile = Usd.ZipFile.Open(resolvedPath)
if not zipFile:
self._AddError("Could not open package at path '%s'." %
resolvedPath)
return
for rule in self._rules:
rule.CheckZipFile(zipFile, packagePath)
def _CheckLayer(self, layer):
for rule in self._rules:
rule.CheckLayer(layer)
def _CheckPrim(self, prim):
for rule in self._rules:
rule.CheckPrim(prim)
def _TraverseRange(self, primRangeIt, isStageRoot):
primsWithVariants = []
rootPrim = primRangeIt.GetCurrentPrim()
for prim in primRangeIt:
# Skip variant set check on the root prim if it is the stage'.
if not self._doVariants or (not isStageRoot and prim == rootPrim):
self._CheckPrim(prim)
continue
vSets = prim.GetVariantSets()
vSetNames = vSets.GetNames()
if len(vSetNames) == 0:
self._CheckPrim(prim)
else:
primsWithVariants.append(prim)
primRangeIt.PruneChildren()
for prim in primsWithVariants:
self._TraverseVariants(prim)
def _TraverseVariants(self, prim):
from pxr import Usd
if prim.IsInstanceProxy():
return True
vSets = prim.GetVariantSets()
vSetNames = vSets.GetNames()
allVariantNames = []
for vSetName in vSetNames:
vSet = vSets.GetVariantSet(vSetName)
vNames = vSet.GetVariantNames()
allVariantNames.append(vNames)
import itertools
allVariations = itertools.product(*allVariantNames)
for variation in allVariations:
self._Msg("Testing variation %s of prim <%s>" %
(variation, prim.GetPath()))
for (idx, sel) in enumerate(variation):
vSets.SetSelection(vSetNames[idx], sel)
primRangeIt = iter(Usd.PrimRange(prim,
Usd.TraverseInstanceProxies()))
self._TraverseRange(primRangeIt, isStageRoot=False)
| 30,368 | Python | 40.715659 | 88 | 0.600797 |
USwampertor/OmniverseJS/ov/python/pxr/Sdr/shaderParserTestUtils.py | #!/pxrpythonsubst
#
# 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.
"""
Common utilities that shader-based parser plugins can use in their tests.
This is mostly focused on dealing with OSL and Args files. This may need to be
expanded/generalized to accommodate other types in the future.
"""
from __future__ import print_function
from pxr import Ndr
from pxr import Sdr
from pxr.Sdf import ValueTypeNames as SdfTypes
from pxr import Tf
def IsNodeOSL(node):
"""
Determines if the given node has an OSL source type.
"""
return node.GetSourceType() == "OSL"
# XXX Maybe rename this to GetSdfType (as opposed to the Sdr type)
def GetType(property):
"""
Given a property (SdrShaderProperty), return the SdfValueTypeName type.
"""
sdfTypeIndicator = property.GetTypeAsSdfType()
sdfValueTypeName = sdfTypeIndicator[0]
tfType = sdfValueTypeName.type
return tfType
def TestBasicProperties(node):
"""
Test the correctness of the properties on the specified node (only the
non-shading-specific aspects).
"""
isOSL = IsNodeOSL(node)
# Data that varies between OSL/Args
# --------------------------------------------------------------------------
metadata = {
"widget": "number",
"label": "inputA label",
"page": "inputs1",
"help": "inputA help message",
"uncategorized": "1"
}
if not isOSL:
metadata["name"] = "inputA"
metadata["default"] = "0.0"
metadata["type"] = "float"
# --------------------------------------------------------------------------
properties = {
"inputA": node.GetInput("inputA"),
"inputB": node.GetInput("inputB"),
"inputC": node.GetInput("inputC"),
"inputD": node.GetInput("inputD"),
"inputF2": node.GetInput("inputF2"),
"inputStrArray": node.GetInput("inputStrArray"),
"resultF": node.GetOutput("resultF"),
"resultI": node.GetOutput("resultI"),
}
assert properties["inputA"].GetName() == "inputA"
assert properties["inputA"].GetType() == "float"
assert properties["inputA"].GetDefaultValue() == 0.0
assert not properties["inputA"].IsOutput()
assert not properties["inputA"].IsArray()
assert not properties["inputA"].IsDynamicArray()
assert properties["inputA"].GetArraySize() == 0
assert properties["inputA"].GetInfoString() == "inputA (type: 'float'); input"
assert properties["inputA"].IsConnectable()
assert properties["inputA"].CanConnectTo(properties["resultF"])
assert not properties["inputA"].CanConnectTo(properties["resultI"])
assert properties["inputA"].GetMetadata() == metadata
# --------------------------------------------------------------------------
# Check some array variations
# --------------------------------------------------------------------------
assert properties["inputD"].IsDynamicArray()
assert properties["inputD"].GetArraySize() == 1 if isOSL else -1
assert properties["inputD"].IsArray()
assert list(properties["inputD"].GetDefaultValue()) == [1]
assert not properties["inputF2"].IsDynamicArray()
assert properties["inputF2"].GetArraySize() == 2
assert properties["inputF2"].IsArray()
assert not properties["inputF2"].IsConnectable()
assert list(properties["inputF2"].GetDefaultValue()) == [1.0, 2.0]
assert properties["inputStrArray"].GetArraySize() == 4
assert list(properties["inputStrArray"].GetDefaultValue()) == \
["test", "string", "array", "values"]
def TestShadingProperties(node):
"""
Test the correctness of the properties on the specified node (only the
shading-specific aspects).
"""
isOSL = IsNodeOSL(node)
properties = {
"inputA": node.GetShaderInput("inputA"),
"inputB": node.GetShaderInput("inputB"),
"inputC": node.GetShaderInput("inputC"),
"inputD": node.GetShaderInput("inputD"),
"inputF2": node.GetShaderInput("inputF2"),
"inputF3": node.GetShaderInput("inputF3"),
"inputF4": node.GetShaderInput("inputF4"),
"inputF5": node.GetShaderInput("inputF5"),
"inputInterp": node.GetShaderInput("inputInterp"),
"inputOptions": node.GetShaderInput("inputOptions"),
"inputPoint": node.GetShaderInput("inputPoint"),
"inputNormal": node.GetShaderInput("inputNormal"),
"inputStruct": node.GetShaderInput("inputStruct"),
"inputAssetIdentifier": node.GetShaderInput("inputAssetIdentifier"),
"resultF": node.GetShaderOutput("resultF"),
"resultF2": node.GetShaderOutput("resultF2"),
"resultF3": node.GetShaderOutput("resultF3"),
"resultI": node.GetShaderOutput("resultI"),
"vstruct1": node.GetShaderOutput("vstruct1"),
"vstruct1_bump": node.GetShaderOutput("vstruct1_bump"),
"outputPoint": node.GetShaderOutput("outputPoint"),
"outputNormal": node.GetShaderOutput("outputNormal"),
"outputColor": node.GetShaderOutput("outputColor"),
"outputVector": node.GetShaderOutput("outputVector"),
}
assert properties["inputA"].GetLabel() == "inputA label"
assert properties["inputA"].GetHelp() == "inputA help message"
assert properties["inputA"].GetPage() == "inputs1"
assert properties["inputA"].GetWidget() == "number"
assert properties["inputA"].GetHints() == {
"uncategorized": "1"
}
assert properties["inputA"].GetOptions() == []
assert properties["inputA"].GetVStructMemberOf() == ""
assert properties["inputA"].GetVStructMemberName() == ""
assert not properties["inputA"].IsVStructMember()
assert not properties["inputA"].IsVStruct()
assert properties["inputA"].IsConnectable()
assert properties["inputA"].GetValidConnectionTypes() == []
assert properties["inputA"].CanConnectTo(properties["resultF"])
assert not properties["inputA"].CanConnectTo(properties["resultI"])
# --------------------------------------------------------------------------
# Check correct options parsing
# --------------------------------------------------------------------------
assert set(properties["inputOptions"].GetOptions()) == {
("opt1", "opt1val"),
("opt2", "opt2val")
}
assert set(properties["inputInterp"].GetOptions()) == {
("linear", ""),
("catmull-rom", ""),
("bspline", ""),
("constant", ""),
}
# --------------------------------------------------------------------------
# Check cross-type connection allowances
# --------------------------------------------------------------------------
assert properties["inputPoint"].CanConnectTo(properties["outputNormal"])
assert properties["inputNormal"].CanConnectTo(properties["outputPoint"])
assert properties["inputNormal"].CanConnectTo(properties["outputColor"])
assert properties["inputNormal"].CanConnectTo(properties["outputVector"])
assert properties["inputNormal"].CanConnectTo(properties["resultF3"])
assert properties["inputF2"].CanConnectTo(properties["resultF2"])
assert properties["inputD"].CanConnectTo(properties["resultI"])
assert not properties["inputNormal"].CanConnectTo(properties["resultF2"])
assert not properties["inputF4"].CanConnectTo(properties["resultF2"])
assert not properties["inputF2"].CanConnectTo(properties["resultF3"])
# --------------------------------------------------------------------------
# Check clean and unclean mappings to Sdf types
# --------------------------------------------------------------------------
assert properties["inputB"].GetTypeAsSdfType() == (SdfTypes.Int, "")
assert properties["inputF2"].GetTypeAsSdfType() == (SdfTypes.Float2, "")
assert properties["inputF3"].GetTypeAsSdfType() == (SdfTypes.Float3, "")
assert properties["inputF4"].GetTypeAsSdfType() == (SdfTypes.Float4, "")
assert properties["inputF5"].GetTypeAsSdfType() == (SdfTypes.FloatArray, "")
assert properties["inputStruct"].GetTypeAsSdfType() == \
(SdfTypes.Token, Sdr.PropertyTypes.Struct)
# --------------------------------------------------------------------------
# Ensure asset identifiers are detected correctly
# --------------------------------------------------------------------------
assert properties["inputAssetIdentifier"].IsAssetIdentifier()
assert not properties["inputOptions"].IsAssetIdentifier()
assert properties["inputAssetIdentifier"].GetTypeAsSdfType() == \
(SdfTypes.Asset, "")
# Nested pages and VStructs are only possible in args files
if not isOSL:
# ----------------------------------------------------------------------
# Check nested page correctness
# ----------------------------------------------------------------------
assert properties["vstruct1"].GetPage() == "VStructs.Nested"
assert properties["vstruct1_bump"].GetPage() == "VStructs.Nested.More"
# ----------------------------------------------------------------------
# Check VStruct correctness
# ----------------------------------------------------------------------
assert properties["vstruct1"].IsVStruct()
assert properties["vstruct1"].GetVStructMemberOf() == ""
assert properties["vstruct1"].GetVStructMemberName() == ""
assert not properties["vstruct1"].IsVStructMember()
assert not properties["vstruct1_bump"].IsVStruct()
assert properties["vstruct1_bump"].GetVStructMemberOf() == "vstruct1"
assert properties["vstruct1_bump"].GetVStructMemberName() == "bump"
assert properties["vstruct1_bump"].IsVStructMember()
def TestBasicNode(node, nodeSourceType, nodeDefinitionURI, nodeImplementationURI):
"""
Test basic, non-shader-specific correctness on the specified node.
"""
# Implementation notes:
# ---
# The source type needs to be passed manually in order to ensure the utils
# do not have a dependency on the plugin (where the source type resides).
# The URIs are manually specified because the utils cannot know ahead of
# time where the node originated.
isOSL = IsNodeOSL(node)
nodeContext = "OSL" if isOSL else "pattern"
# Data that varies between OSL/Args
# --------------------------------------------------------------------------
nodeName = "TestNodeOSL" if isOSL else "TestNodeARGS"
numOutputs = 8 if isOSL else 10
outputNames = {
"resultF", "resultF2", "resultF3", "resultI", "outputPoint",
"outputNormal", "outputColor", "outputVector"
}
metadata = {
"category": "testing",
"departments": "testDept",
"help": "This is the test node",
"label": "TestNodeLabel",
"primvars": "primvar1|primvar2|primvar3|$primvarNamingProperty|"
"$invalidPrimvarNamingProperty",
"uncategorizedMetadata": "uncategorized"
}
if not isOSL:
metadata.pop("category")
metadata.pop("label")
metadata.pop("uncategorizedMetadata")
outputNames.add("vstruct1")
outputNames.add("vstruct1_bump")
# --------------------------------------------------------------------------
nodeInputs = {propertyName: node.GetShaderInput(propertyName)
for propertyName in node.GetInputNames()}
nodeOutputs = {propertyName: node.GetShaderOutput(propertyName)
for propertyName in node.GetOutputNames()}
assert node.GetName() == nodeName
assert node.GetContext() == nodeContext
assert node.GetSourceType() == nodeSourceType
assert node.GetFamily() == ""
assert node.GetResolvedDefinitionURI() == nodeDefinitionURI
assert node.GetResolvedImplementationURI() == nodeImplementationURI
assert node.IsValid()
assert len(nodeInputs) == 17
assert len(nodeOutputs) == numOutputs
assert nodeInputs["inputA"] is not None
assert nodeInputs["inputB"] is not None
assert nodeInputs["inputC"] is not None
assert nodeInputs["inputD"] is not None
assert nodeInputs["inputF2"] is not None
assert nodeInputs["inputF3"] is not None
assert nodeInputs["inputF4"] is not None
assert nodeInputs["inputF5"] is not None
assert nodeInputs["inputInterp"] is not None
assert nodeInputs["inputOptions"] is not None
assert nodeInputs["inputPoint"] is not None
assert nodeInputs["inputNormal"] is not None
assert nodeOutputs["resultF2"] is not None
assert nodeOutputs["resultI"] is not None
assert nodeOutputs["outputPoint"] is not None
assert nodeOutputs["outputNormal"] is not None
assert nodeOutputs["outputColor"] is not None
assert nodeOutputs["outputVector"] is not None
print(set(node.GetInputNames()))
assert set(node.GetInputNames()) == {
"inputA", "inputB", "inputC", "inputD", "inputF2", "inputF3", "inputF4",
"inputF5", "inputInterp", "inputOptions", "inputPoint", "inputNormal",
"inputStruct", "inputAssetIdentifier", "primvarNamingProperty",
"invalidPrimvarNamingProperty", "inputStrArray"
}
assert set(node.GetOutputNames()) == outputNames
# There may be additional metadata passed in via the NdrNodeDiscoveryResult.
# So, ensure that the bits we expect to see are there instead of doing
# an equality check.
nodeMetadata = node.GetMetadata()
for i,j in metadata.items():
assert i in nodeMetadata
assert nodeMetadata[i] == metadata[i]
# Test basic property correctness
TestBasicProperties(node)
def TestShaderSpecificNode(node):
"""
Test shader-specific correctness on the specified node.
"""
isOSL = IsNodeOSL(node)
# Data that varies between OSL/Args
# --------------------------------------------------------------------------
numOutputs = 8 if isOSL else 10
label = "TestNodeLabel" if isOSL else ""
category = "testing" if isOSL else ""
vstructNames = [] if isOSL else ["vstruct1"]
pages = {"", "inputs1", "inputs2", "results"} if isOSL else \
{"", "inputs1", "inputs2", "results", "VStructs.Nested",
"VStructs.Nested.More"}
# --------------------------------------------------------------------------
shaderInputs = {propertyName: node.GetShaderInput(propertyName)
for propertyName in node.GetInputNames()}
shaderOutputs = {propertyName: node.GetShaderOutput(propertyName)
for propertyName in node.GetOutputNames()}
assert len(shaderInputs) == 17
assert len(shaderOutputs) == numOutputs
assert shaderInputs["inputA"] is not None
assert shaderInputs["inputB"] is not None
assert shaderInputs["inputC"] is not None
assert shaderInputs["inputD"] is not None
assert shaderInputs["inputF2"] is not None
assert shaderInputs["inputF3"] is not None
assert shaderInputs["inputF4"] is not None
assert shaderInputs["inputF5"] is not None
assert shaderInputs["inputInterp"] is not None
assert shaderInputs["inputOptions"] is not None
assert shaderInputs["inputPoint"] is not None
assert shaderInputs["inputNormal"] is not None
assert shaderOutputs["resultF"] is not None
assert shaderOutputs["resultF2"] is not None
assert shaderOutputs["resultF3"] is not None
assert shaderOutputs["resultI"] is not None
assert shaderOutputs["outputPoint"] is not None
assert shaderOutputs["outputNormal"] is not None
assert shaderOutputs["outputColor"] is not None
assert shaderOutputs["outputVector"] is not None
assert node.GetLabel() == label
assert node.GetCategory() == category
assert node.GetHelp() == "This is the test node"
assert node.GetDepartments() == ["testDept"]
assert set(node.GetPages()) == pages
assert set(node.GetPrimvars()) == {"primvar1", "primvar2", "primvar3"}
assert set(node.GetAdditionalPrimvarProperties()) == {"primvarNamingProperty"}
assert set(node.GetPropertyNamesForPage("results")) == {
"resultF", "resultF2", "resultF3", "resultI"
}
assert set(node.GetPropertyNamesForPage("")) == {
"outputPoint", "outputNormal", "outputColor", "outputVector"
}
assert set(node.GetPropertyNamesForPage("inputs1")) == {"inputA"}
assert set(node.GetPropertyNamesForPage("inputs2")) == {
"inputB", "inputC", "inputD", "inputF2", "inputF3", "inputF4", "inputF5",
"inputInterp", "inputOptions", "inputPoint", "inputNormal",
"inputStruct", "inputAssetIdentifier", "primvarNamingProperty",
"invalidPrimvarNamingProperty", "inputStrArray"
}
assert node.GetAllVstructNames() == vstructNames
# Test shading-specific property correctness
TestShadingProperties(node)
def TestShaderPropertiesNode(node):
"""
Tests property correctness on the specified shader node, which must be
one of the following pre-defined nodes:
* 'TestShaderPropertiesNodeOSL'
* 'TestShaderPropertiesNodeARGS'
* 'TestShaderPropertiesNodeUSD'
These pre-defined nodes have a property of every type that Sdr supports.
Property correctness is defined as:
* The shader property has the expected SdrPropertyType
* The shader property has the expected SdfValueTypeName
* If the shader property has a default value, the default value's type
matches the shader property's type
"""
# This test should only be run on the following allowed node names
# --------------------------------------------------------------------------
allowedNodeNames = ["TestShaderPropertiesNodeOSL",
"TestShaderPropertiesNodeARGS",
"TestShaderPropertiesNodeUSD"]
# If this assertion on the name fails, then this test was called with the
# wrong node.
assert node.GetName() in allowedNodeNames
# If we have the correct node name, double check that the source type is
# also correct
if node.GetName() == "TestShaderPropertiesNodeOSL":
assert node.GetSourceType() == "OSL"
elif node.GetName() == "TestShaderPropertiesNodeARGS":
assert node.GetSourceType() == "RmanCpp"
elif node.GetName() == "TestShaderPropertiesNodeUSD":
assert node.GetSourceType() == "glslfx"
nodeInputs = {propertyName: node.GetShaderInput(propertyName)
for propertyName in node.GetInputNames()}
nodeOutputs = {propertyName: node.GetShaderOutput(propertyName)
for propertyName in node.GetOutputNames()}
# For each property, we test that:
# * The property has the expected SdrPropertyType
# * The property has the expected TfType (from SdfValueTypeName)
# * The property's type and default value's type match
property = nodeInputs["inputInt"]
assert property.GetType() == Sdr.PropertyTypes.Int
assert GetType(property) == Tf.Type.FindByName("int")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputString"]
assert property.GetType() == Sdr.PropertyTypes.String
assert GetType(property) == Tf.Type.FindByName("string")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloat"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("float")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputColor"]
assert property.GetType() == Sdr.PropertyTypes.Color
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputPoint"]
assert property.GetType() == Sdr.PropertyTypes.Point
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputNormal"]
assert property.GetType() == Sdr.PropertyTypes.Normal
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputVector"]
assert property.GetType() == Sdr.PropertyTypes.Vector
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputMatrix"]
assert property.GetType() == Sdr.PropertyTypes.Matrix
assert GetType(property) == Tf.Type.FindByName("GfMatrix4d")
assert Ndr._ValidateProperty(node, property)
if node.GetName() != "TestShaderPropertiesNodeUSD":
# XXX Note that 'struct' and 'vstruct' types are currently unsupported
# by the UsdShadeShaderDefParserPlugin, which parses shaders defined in
# usd files. Please see UsdShadeShaderDefParserPlugin implementation for
# details.
property = nodeInputs["inputStruct"]
assert property.GetType() == Sdr.PropertyTypes.Struct
assert GetType(property) == Tf.Type.FindByName("TfToken")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputVstruct"]
assert property.GetType() == Sdr.PropertyTypes.Vstruct
assert GetType(property) == Tf.Type.FindByName("TfToken")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputIntArray"]
assert property.GetType() == Sdr.PropertyTypes.Int
assert GetType(property) == Tf.Type.FindByName("VtArray<int>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputStringArray"]
assert property.GetType() == Sdr.PropertyTypes.String
assert GetType(property) == Tf.Type.FindByName("VtArray<string>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloatArray"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("VtArray<float>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputColorArray"]
assert property.GetType() == Sdr.PropertyTypes.Color
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec3f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputPointArray"]
assert property.GetType() == Sdr.PropertyTypes.Point
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec3f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputNormalArray"]
assert property.GetType() == Sdr.PropertyTypes.Normal
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec3f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputVectorArray"]
assert property.GetType() == Sdr.PropertyTypes.Vector
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec3f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputMatrixArray"]
assert property.GetType() == Sdr.PropertyTypes.Matrix
assert GetType(property) == Tf.Type.FindByName("VtArray<GfMatrix4d>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloat2"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec2f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloat3"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloat4"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec4f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputAsset"]
assert property.GetType() == Sdr.PropertyTypes.String
assert GetType(property) == Tf.Type.FindByName("SdfAssetPath")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputAssetArray"]
assert property.GetType() == Sdr.PropertyTypes.String
assert GetType(property) == Tf.Type.FindByName("VtArray<SdfAssetPath>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputColorRoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputPointRoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputNormalRoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputVectorRoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeOutputs["outputSurface"]
assert property.GetType() == Sdr.PropertyTypes.Terminal
assert GetType(property) == Tf.Type.FindByName("TfToken")
assert Ndr._ValidateProperty(node, property)
# Specific test of implementationName feature, we can skip type-tests
property = nodeInputs["normal"]
assert property.GetImplementationName() == "aliasedNormalInput"
assert Ndr._ValidateProperty(node, property)
| 26,416 | Python | 42.165033 | 82 | 0.649758 |
USwampertor/OmniverseJS/ov/python/pxr/Vt/__init__.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
"""Vt Value Types library
This package defines classes for creating objects that behave like value
types. It contains facilities for creating simple copy-on-write
implicitly shared types.
"""
from . import _vt
from pxr import Tf
Tf.PrepareModule(_vt, locals())
del _vt, Tf
try:
from . import __DOC
__DOC.Execute(locals())
del __DOC
except Exception:
pass
# For ease-of-use, put each XXXArrayFromBuffer method on its corresponding array
# wrapper class, also alias it as 'FromNumpy' for compatibility.
def _CopyArrayFromBufferFuncs(moduleContents):
funcs = dict([(key, val) for (key, val) in moduleContents.items()
if key.endswith('FromBuffer')])
classes = dict([(key, val) for (key, val) in moduleContents.items()
if key.endswith('Array') and isinstance(val, type)])
for funcName, func in funcs.items():
className = funcName[:-len('FromBuffer')]
cls = classes.get(className)
if cls:
setattr(cls, 'FromBuffer', staticmethod(func))
setattr(cls, 'FromNumpy', staticmethod(func))
_CopyArrayFromBufferFuncs(dict(vars()))
del _CopyArrayFromBufferFuncs
| 2,226 | Python | 36.116666 | 80 | 0.720126 |
USwampertor/OmniverseJS/ov/python/pxr/UsdMdl/__init__.py | #******************************************************************************
# * Copyright 2019 NVIDIA Corporation. All rights reserved.
# *****************************************************************************
#
# NVIDIA Material Definition Language (MDL) USD plugins.
#
# MDL Search Paths
# ================
# At startup (i.e. when the MDL SDK is loaded) MDL search path is set in this order:
# 1/ Dedicated environement variable
# If it is set, PXR_USDMDL_PLUGIN_SEARCH_PATHS overwrites any MDL search path.
# PXR_USDMDL_PLUGIN_SEARCH_PATHS can be set to a list of paths.
# 2/ System and User Path
# if PXR_USDMDL_PLUGIN_SEARCH_PATHS is not set:
# a/ If set, add MDL_SYSTEM_PATH to the MDL search path
# b/ If set, add MDL_USER_PATH to the MDL search path
#
# Discovery plugin
# ================
# MDL discovery plugin is derived from NdrDiscoveryPlugin interface.
# This plugin finds MDL functions and materials from all the modules found in the
# MDL search paths.
# This discovery plugin is executed as soon as the registry is instantiated,
# for example in Python:
#
# >>> from pxr import Sdr
# >>> reg = Sdr.Registry()
#
# MDL discovery plugin creates a discovery result (NdrNodeDiscoveryResult)
# for each material and each function that is found.
#
# Parser plugin
# ================
# MDL parser plugin is derived from NdrParserPlugin interface.
# This plugin is responsible to parse a given MDL function or material and
# create an NdrNode instance.
# The parser plugin which is run is decided based on the discovery result discoveryType.
# The parser plugin is invoked whenever a shader node is requested, for example in Python:
#
# >>> from pxr import Sdr
# >>> MDLQualifiedName = "::material_examples::architectural::architectural"
# >>> Sdr.Registry().GetShaderNodeByIdentifierAndType(MDLQualifiedName, "mdl")
#
# NdrNodes which is created contains a list of properties which are translated
# from MDL parameters.
#
from . import _usdMdl
from pxr import Tf
Tf.PrepareModule(_usdMdl, locals())
del Tf
try:
import __DOC
__DOC.Execute(locals())
del __DOC
except Exception:
try:
import __tmpDoc
__tmpDoc.Execute(locals())
del __tmpDoc
except:
pass
| 2,253 | Python | 34.777777 | 90 | 0.656458 |
USwampertor/OmniverseJS/ov/python/pxr/Trace/__init__.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
"""
Trace -- Utilities for counting and recording events.
"""
from . import _trace
from pxr import Tf
Tf.PrepareModule(_trace, locals())
del _trace, Tf
import contextlib
@contextlib.contextmanager
def TraceScope(label):
"""A context manager that calls BeginEvent on the global collector on enter
and EndEvent on exit."""
try:
collector = Collector()
eventId = collector.BeginEvent(label)
yield
finally:
collector.EndEvent(label)
del contextlib
def TraceFunction(obj):
"""A decorator that enables tracing the function that it decorates.
If you decorate with 'TraceFunction' the function will be traced in the
global collector."""
collector = Collector()
def decorate(func):
import inspect
if inspect.ismethod(func):
callableTypeLabel = 'method'
classLabel = func.__self__.__class__.__name__+'.'
else:
callableTypeLabel = 'func'
classLabel = ''
module = inspect.getmodule(func)
if module is not None:
moduleLabel = module.__name__+'.'
else:
moduleLabel = ''
label = 'Python {0}: {1}{2}{3}'.format(
callableTypeLabel,
moduleLabel,
classLabel,
func.__name__)
def invoke(*args, **kwargs):
with TraceScope(label):
return func(*args, **kwargs)
invoke.__name__ = func.__name__
# Make sure wrapper function gets attributes of wrapped function.
import functools
return functools.update_wrapper(invoke, func)
return decorate(obj)
def TraceMethod(obj):
"""A convenience. Same as TraceFunction but changes the recorded
label to use the term 'method' rather than 'function'."""
return TraceFunction(obj)
# Remove any private stuff, like test classes, if we are not being
# imported from a test.
try:
from . import __DOC
__DOC.Execute(locals())
del __DOC
except Exception:
pass
| 3,092 | Python | 29.323529 | 80 | 0.664618 |
USwampertor/OmniverseJS/ov/python/pxr/Trace/__main__.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Execute a script with tracing enabled.
# Usage: python -m pxr.Trace [-o OUTPUT] [-c "command" | FILE]
from __future__ import print_function
import argparse, sys
parser = argparse.ArgumentParser(description='Trace script execution.')
parser.add_argument('-o', dest='output', metavar='OUTPUT',
type=str, default=None,
help='trace output; defaults to stdout')
parser.add_argument('-c', dest='cmd',
type=str,
help='trace <cmd> as a Python script')
parser.add_argument('file', metavar="FILE",
nargs='?',
default=None,
help='script to trace')
args = parser.parse_args()
if not args.cmd and not args.file:
print("Must specify a command or script to trace", file=sys.stderr)
sys.exit(1)
if args.cmd and args.file:
print("Only one of -c or FILE may be specified", file=sys.stderr)
sys.exit(1)
from pxr import Trace
env = {}
# Create a Main function that is traced so we always capture a useful
# top-level scope.
if args.file:
@Trace.TraceFunction
def Main():
exec(compile(open(args.file).read(), args.file, 'exec'), env)
else:
@Trace.TraceFunction
def Main():
exec(args.cmd, env)
try:
Trace.Collector().enabled = True
Main()
finally:
Trace.Collector().enabled = False
if args.output is not None:
Trace.Reporter.globalReporter.Report(args.output)
else:
Trace.Reporter.globalReporter.Report()
| 2,580 | Python | 31.670886 | 74 | 0.68062 |
USwampertor/OmniverseJS/ov/python/pxr/UsdAppUtils/cameraArgs.py | #
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
def AddCmdlineArgs(argsParser, defaultValue=None, altHelpText=''):
"""
Adds camera-related command line arguments to argsParser.
The resulting 'camera' argument will be an Sdf.Path. If no value is given
and defaultValue is not overridden, 'camera' will be a single-element path
containing the primary camera name.
"""
from pxr import Sdf
from pxr import UsdUtils
if defaultValue is None:
defaultValue = UsdUtils.GetPrimaryCameraName()
helpText = altHelpText
if not helpText:
helpText = (
'Which camera to use - may be given as either just the '
'camera\'s prim name (i.e. 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 that name, which '
'one is used will effectively be random (default=%(default)s)')
# This avoids an Sdf warning if an empty string is given, which someone
# might do for example with usdview to open the app using the 'Free' camera
# instead of the primary camera.
def _ToSdfPath(inputArg):
if not inputArg:
return Sdf.Path.emptyPath
return Sdf.Path(inputArg)
argsParser.add_argument('--camera', '-cam', action='store',
type=_ToSdfPath, default=defaultValue, help=helpText)
| 2,434 | Python | 40.982758 | 79 | 0.708299 |
USwampertor/OmniverseJS/ov/python/pxr/UsdAppUtils/colorArgs.py | #
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
def AddCmdlineArgs(argsParser, defaultValue='sRGB', altHelpText=''):
"""
Adds color-related command line arguments to argsParser.
The resulting 'colorCorrectionMode' argument will be a Python string.
"""
helpText = altHelpText
if not helpText:
helpText = (
'the color correction mode to use (default=%(default)s)')
argsParser.add_argument('--colorCorrectionMode', '-color', action='store',
type=str, default=defaultValue,
choices=['disabled', 'sRGB', 'openColorIO'], help=helpText)
| 1,608 | Python | 40.256409 | 78 | 0.731343 |
USwampertor/OmniverseJS/ov/python/pxr/UsdAppUtils/complexityArgs.py | #
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
class RefinementComplexities(object):
"""
An enum-like container of standard complexity settings.
"""
class _RefinementComplexity(object):
"""
Class which represents a level of mesh refinement complexity. Each
level has a string identifier, a display name, and a float complexity
value.
"""
def __init__(self, compId, name, value):
self._id = compId
self._name = name
self._value = value
def __repr__(self):
return self.id
@property
def id(self):
return self._id
@property
def name(self):
return self._name
@property
def value(self):
return self._value
LOW = _RefinementComplexity("low", "Low", 1.0)
MEDIUM = _RefinementComplexity("medium", "Medium", 1.1)
HIGH = _RefinementComplexity("high", "High", 1.2)
VERY_HIGH = _RefinementComplexity("veryhigh", "Very High", 1.3)
_ordered = (LOW, MEDIUM, HIGH, VERY_HIGH)
@classmethod
def ordered(cls):
"""
Get a tuple of all complexity levels in order.
"""
return cls._ordered
@classmethod
def fromId(cls, compId):
"""
Get a complexity from its identifier.
"""
matches = [comp for comp in cls._ordered if comp.id == compId]
if len(matches) == 0:
raise ValueError("No complexity with id '{}'".format(compId))
return matches[0]
@classmethod
def fromName(cls, name):
"""
Get a complexity from its display name.
"""
matches = [comp for comp in cls._ordered if comp.name == name]
if len(matches) == 0:
raise ValueError("No complexity with name '{}'".format(name))
return matches[0]
@classmethod
def next(cls, comp):
"""
Get the next highest level of complexity. If already at the highest
level, return it.
"""
if comp not in cls._ordered:
raise ValueError("Invalid complexity: {}".format(comp))
nextIndex = min(
len(cls._ordered) - 1,
cls._ordered.index(comp) + 1)
return cls._ordered[nextIndex]
@classmethod
def prev(cls, comp):
"""
Get the next lowest level of complexity. If already at the lowest
level, return it.
"""
if comp not in cls._ordered:
raise ValueError("Invalid complexity: {}".format(comp))
prevIndex = max(0, cls._ordered.index(comp) - 1)
return cls._ordered[prevIndex]
def AddCmdlineArgs(argsParser, defaultValue=RefinementComplexities.LOW,
altHelpText=''):
"""
Adds complexity-related command line arguments to argsParser.
The resulting 'complexity' argument will be one of the standard
RefinementComplexities.
"""
helpText = altHelpText
if not helpText:
helpText = ('level of refinement to use (default=%(default)s)')
argsParser.add_argument('--complexity', '-c', action='store',
type=RefinementComplexities.fromId,
default=defaultValue,
choices=[c for c in RefinementComplexities.ordered()],
help=helpText)
| 4,297 | Python | 31.315789 | 77 | 0.62788 |
USwampertor/OmniverseJS/ov/python/pxr/UsdAppUtils/framesArgs.py | #
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
def _GetFloatStringPrecision(floatString):
"""
Gets the floating point precision specified by floatString.
floatString can either contain an actual float in string form, or it can be
a frame placeholder. We simply split the string on the dot (.) and return
the length of the part after the dot, if any.
If there is no dot in the string, a precision of zero is assumed.
"""
floatPrecision = 0
if not floatString:
return floatPrecision
floatStringParts = floatString.split('.')
if len(floatStringParts) > 1:
floatPrecision = len(floatStringParts[1])
return floatPrecision
class FrameSpecIterator(object):
"""
A simple iterator object that handles splitting multiple comma-separated
FrameSpecs into their equivalent UsdUtils.TimeCodeRanges, and then yields
all of the time codes in all of those ranges sequentially when iterated.
This object also stores the minimum floating point precision required to
disambiguate any neighboring time codes in the FrameSpecs given. This can
be used to validate that the frame placeholder in a frame format string has
enough precision to uniquely identify every frame without collisions.
"""
from pxr import UsdUtils
FRAMESPEC_SEPARATOR = ','
def __init__(self, frameSpec):
from pxr import UsdUtils
# Assume all frames are integral until we find a frame spec with a
# non-integral stride.
self._minFloatPrecision = 0
self._timeCodeRanges = []
subFrameSpecs = frameSpec.split(self.FRAMESPEC_SEPARATOR)
for subFrameSpec in subFrameSpecs:
timeCodeRange = UsdUtils.TimeCodeRange.CreateFromFrameSpec(
subFrameSpec)
self._timeCodeRanges.append(timeCodeRange)
specParts = subFrameSpec.split(
UsdUtils.TimeCodeRange.Tokens.StrideSeparator)
if len(specParts) == 2:
stride = specParts[1]
stridePrecision = _GetFloatStringPrecision(stride)
self._minFloatPrecision = max(self._minFloatPrecision,
stridePrecision)
def __iter__(self):
for timeCodeRange in self._timeCodeRanges:
for timeCode in timeCodeRange:
yield timeCode
@property
def minFloatPrecision(self):
return self._minFloatPrecision
def AddCmdlineArgs(argsParser, altDefaultTimeHelpText='', altFramesHelpText=''):
"""
Adds frame-related command line arguments to argsParser.
The resulting 'frames' argument will be an iterable of UsdTimeCodes.
If no command-line arguments are given, 'frames' will be a list containing
only Usd.TimeCode.EarliestTime(). If '--defaultTime' is given, 'frames'
will be a list containing only Usd.TimeCode.Default(). Otherwise,
'--frames' must be given a FrameSpec (or a comma-separated list of
multiple FrameSpecs), and 'frames' will be a FrameSpecIterator which when
iterated will yield the time codes specified by the FrameSpec(s).
"""
timeGroup = argsParser.add_mutually_exclusive_group()
helpText = altDefaultTimeHelpText
if not helpText:
helpText = (
'explicitly operate at the Default time code (the default '
'behavior is to operate at the Earliest time code)')
timeGroup.add_argument('--defaultTime', '-d', action='store_true',
dest='defaultTime', help=helpText)
helpText = altFramesHelpText
if not helpText:
helpText = (
'specify FrameSpec(s) of the time codes to operate on - A '
'FrameSpec consists of up to three floating point values for the '
'start time code, end time code, and stride of a time code range. '
'A single time code can be specified, or a start and end time '
'code can be specified separated by a colon (:). When a start '
'and end time code are specified, the stride may optionally be '
'specified as well, separating it from the start and end time '
'codes with (x). Multiple FrameSpecs can be combined as a '
'comma-separated list. The following are examples of valid '
'FrameSpecs: 123 - 101:105 - 105:101 - 101:109x2 - 101:110x2 - '
'101:104x0.5')
timeGroup.add_argument('--frames', '-f', action='store', type=str,
dest='frames', metavar='FRAMESPEC[,FRAMESPEC...]',
help=helpText)
def GetFramePlaceholder(frameFormat):
"""
Gets the frame placeholder in a frame format string.
This function expects the input frameFormat string to contain exactly one
frame placeholder. The placeholder must be composed of exactly one or two
groups of one or more hashes ('#'), and if there are two, they must be
separated by a dot ('.').
If no such placeholder exists in the frame format string, None is returned.
"""
if not frameFormat:
return None
import re
PLACEHOLDER_PATTERN = r'^[^#]*(?P<placeholder>#+(\.#+)?)[^#]*$'
matches = re.search(PLACEHOLDER_PATTERN, frameFormat)
if not matches:
return None
placeholder = matches.group(1)
return placeholder
def ConvertFramePlaceholderToFloatSpec(frameFormat):
"""
Converts the frame placeholder in a frame format string to a Python
{}-style float specifier for use with string.format().
This function expects the input frameFormat string to contain exactly one
frame placeholder. The placeholder must be composed of exactly one or two
groups of one or more hashes ('#'), and if there are two, they must be
separated by a dot ('.').
The hashes after the dot indicate the floating point precision to use in
the frame numbers inserted into the frame format string. If there is only
a single group of hashes, the precision is zero and the inserted frame
numbers will be integer values.
The overall width of the frame placeholder specifies the minimum width to
use when inserting frame numbers into the frame format string. Formatted
frame numbers smaller than the minimum width will be zero-padded on the
left until they reach the minimum width.
If the input frame format string does not contain exactly one frame
placeholder, this function will return None, indicating that this frame
format string cannot be used when operating with a frame range.
"""
placeholder = GetFramePlaceholder(frameFormat)
if not placeholder:
return None
# Frame numbers are zero-padded up to the field width.
specFill = 0
# The full width of the placeholder determines the minimum field width.
specWidth = len(placeholder)
# The hashes after the dot, if any, determine the precision. If there are
# none, integer frame numbers are used.
specPrecision = 0
parts = placeholder.split('.')
if len(parts) > 1:
specPrecision = len(parts[1])
floatSpec = ('{frame:' +
'{fill}{width}.{precision}f'.format(fill=specFill,
width=specWidth, precision=specPrecision) +
'}')
return frameFormat.replace(placeholder, floatSpec)
def ValidateCmdlineArgs(argsParser, args, frameFormatArgName=None):
"""
Validates the frame-related arguments in args parsed by argsParser.
This populates 'frames' with the appropriate iterable based on the
command-line arguments given, so it should be called after parse_args() is
called on argsParser.
When working with frame ranges, particularly when writing out images for
each frame, it is common to also have command-line arguments such as an
output image path for specifying where those images should be written. The
value given to this argument should include a frame placeholder so that it
can have the appropriate time code inserted. If the application has such an
argument, its name can be specified using frameFormatArgName. That arg will
be checked to ensure that it has a frame placeholder and it will be given
a value with that placeholder replaced with a Python format specifier so
that the value is ready to use with the str.format(frame=<timeCode>)
method. If a frame range is not provided as an argument, then it is an
error to include a frame placeholder in the frame format string.
"""
from pxr import Usd
framePlaceholder = None
frameFormat = None
if frameFormatArgName is not None:
frameFormat = getattr(args, frameFormatArgName)
framePlaceholder = GetFramePlaceholder(frameFormat)
frameFormat = ConvertFramePlaceholderToFloatSpec(frameFormat)
if args.frames:
args.frames = FrameSpecIterator(args.frames)
if frameFormatArgName is not None:
if not frameFormat:
argsParser.error('%s must contain exactly one frame number '
'placeholder of the form "###"" or "###.###". Note that '
'the number of hash marks is variable in each group.' %
frameFormatArgName)
placeholderPrecision = _GetFloatStringPrecision(framePlaceholder)
if placeholderPrecision < args.frames.minFloatPrecision:
argsParser.error('The given FrameSpecs require a minimum '
'floating point precision of %d, but the frame '
'placeholder in %s only specified a precision of %d (%s). '
'The precision of the frame placeholder must be equal to '
'or greater than %d.' % (args.frames.minFloatPrecision,
frameFormatArgName, placeholderPrecision,
framePlaceholder,args.frames.minFloatPrecision))
setattr(args, frameFormatArgName, frameFormat)
else:
if frameFormat:
argsParser.error('%s cannot contain a frame number placeholder '
'when not operating on a frame range.' % frameFormatArgName)
if args.defaultTime:
args.frames = [Usd.TimeCode.Default()]
else:
args.frames = [Usd.TimeCode.EarliestTime()]
return args
| 11,231 | Python | 40.6 | 80 | 0.685691 |
USwampertor/OmniverseJS/ov/python/pxr/UsdAppUtils/rendererArgs.py | #
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
class RendererPlugins(object):
"""
An enum-like container of the available Hydra renderer plugins.
"""
class _RendererPlugin(object):
"""
Class which represents a Hydra renderer plugin. Each one has a plugin
identifier and a display name.
"""
def __init__(self, pluginId, displayName):
self._pluginId = pluginId
self._displayName = displayName
def __repr__(self):
return self.displayName
@property
def id(self):
return self._pluginId
@property
def displayName(self):
return self._displayName
@classmethod
def allPlugins(cls):
"""
Get a tuple of all available renderer plugins.
"""
if not hasattr(cls, '_allPlugins'):
from pxr import UsdImagingGL
cls._allPlugins = tuple(cls._RendererPlugin(pluginId,
UsdImagingGL.Engine.GetRendererDisplayName(pluginId))
for pluginId in UsdImagingGL.Engine.GetRendererPlugins())
return cls._allPlugins
@classmethod
def fromId(cls, pluginId):
"""
Get a renderer plugin from its identifier.
"""
matches = [plugin for plugin in cls.allPlugins() if plugin.id == pluginId]
if len(matches) == 0:
raise ValueError("No renderer plugin with id '{}'".format(pluginId))
return matches[0]
@classmethod
def fromDisplayName(cls, displayName):
"""
Get a renderer plugin from its display name.
"""
matches = [plugin for plugin in cls.allPlugins() if plugin.displayName == displayName]
if len(matches) == 0:
raise ValueError("No renderer plugin with display name '{}'".format(displayName))
return matches[0]
def AddCmdlineArgs(argsParser, altHelpText=''):
"""
Adds Hydra renderer-related command line arguments to argsParser.
The resulting 'rendererPlugin' argument will be a _RendererPlugin instance
representing one of the available Hydra renderer plugins.
"""
from pxr import UsdImagingGL
helpText = altHelpText
if not helpText:
helpText = (
'Hydra renderer plugin to use when generating images')
argsParser.add_argument('--renderer', '-r', action='store',
type=RendererPlugins.fromDisplayName,
dest='rendererPlugin',
choices=[p for p in RendererPlugins.allPlugins()],
help=helpText)
| 3,564 | Python | 33.61165 | 94 | 0.660494 |
USwampertor/OmniverseJS/ov/usd/usd/resources/codegenTemplates/schemaClass.cpp | //
// 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.
//
#include "{{ libraryPath }}/{{ cls.GetHeaderFile() }}"
#include "pxr/usd/usd/schemaRegistry.h"
#include "pxr/usd/usd/typed.h"
{% if cls.isApi %}
#include "pxr/usd/usd/tokens.h"
{% endif %}
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/assetPath.h"
{% if useExportAPI %}
{{ namespaceOpen }}
{% endif %}
// Register the schema with the TfType system.
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<{{ cls.cppClassName }},
TfType::Bases< {{ cls.parentCppClassName }} > >();
{% if cls.isConcrete %}
// Register the usd prim typename as an alias under UsdSchemaBase. This
// enables one to call
// TfType::Find<UsdSchemaBase>().FindDerivedByName("{{ cls.usdPrimTypeName }}")
// to find TfType<{{ cls.cppClassName }}>, which is how IsA queries are
// answered.
TfType::AddAlias<UsdSchemaBase, {{ cls.cppClassName }}>("{{ cls.usdPrimTypeName }}");
{% endif %}
}
{% if cls.isApi %}
TF_DEFINE_PRIVATE_TOKENS(
_schemaTokens,
({{ cls.primName }})
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
({{ cls.propertyNamespacePrefix }})
{% endif %}
);
{% endif %}
/* virtual */
{{ cls.cppClassName }}::~{{ cls.cppClassName }}()
{
}
{% if not cls.isAPISchemaBase %}
/* static */
{{ cls.cppClassName }}
{{ cls.cppClassName }}::Get(const UsdStagePtr &stage, const SdfPath &path)
{
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return {{ cls.cppClassName }}();
}
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
TfToken name;
if (!Is{{ cls.usdPrimTypeName }}Path(path, &name)) {
TF_CODING_ERROR("Invalid {{ cls.propertyNamespacePrefix }} path <%s>.", path.GetText());
return {{ cls.cppClassName }}();
}
return {{ cls.cppClassName }}(stage->GetPrimAtPath(path.GetPrimPath()), name);
{% else %}
return {{ cls.cppClassName }}(stage->GetPrimAtPath(path));
{% endif %}
}
{% if cls.isMultipleApply %}
{{ cls.cppClassName }}
{{ cls.cppClassName }}::Get(const UsdPrim &prim, const TfToken &name)
{
return {{ cls.cppClassName }}(prim, name);
}
{% endif %}
{% endif %}
{% if cls.isConcrete %}
/* static */
{{ cls.cppClassName }}
{{ cls.cppClassName }}::Define(
const UsdStagePtr &stage, const SdfPath &path)
{
static TfToken usdPrimTypeName("{{ cls.usdPrimTypeName }}");
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return {{ cls.cppClassName }}();
}
return {{ cls.cppClassName }}(
stage->DefinePrim(path, usdPrimTypeName));
}
{% endif %}
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
/* static */
bool
{{ cls.cppClassName }}::IsSchemaPropertyBaseName(const TfToken &baseName)
{
static TfTokenVector attrsAndRels = {
{% for attrName in cls.attrOrder %}
{% set attr = cls.attrs[attrName] %}
{{ tokensPrefix }}Tokens->{{ attr.name }},
{% endfor %}
{% for relName in cls.relOrder %}
{% set rel = cls.rels[relName] %}
{{ tokensPrefix }}Tokens->{{ rel.name }},
{% endfor %}
};
return find(attrsAndRels.begin(), attrsAndRels.end(), baseName)
!= attrsAndRels.end();
}
/* static */
bool
{{ cls.cppClassName }}::Is{{ cls.usdPrimTypeName }}Path(
const SdfPath &path, TfToken *name)
{
if (!path.IsPropertyPath()) {
return false;
}
std::string propertyName = path.GetName();
TfTokenVector tokens = SdfPath::TokenizeIdentifierAsTokens(propertyName);
// The baseName of the {{ cls.usdPrimTypename }} path can't be one of the
// schema properties. We should validate this in the creation (or apply)
// API.
TfToken baseName = *tokens.rbegin();
if (IsSchemaPropertyBaseName(baseName)) {
return false;
}
if (tokens.size() >= 2
&& tokens[0] == _schemaTokens->{{ cls.propertyNamespacePrefix }}) {
*name = TfToken(propertyName.substr(
_schemaTokens->{{ cls.propertyNamespacePrefix }}.GetString().size() + 1));
return true;
}
return false;
}
{% endif %}
/* virtual */
UsdSchemaType {{ cls.cppClassName }}::_GetSchemaType() const {
return {{ cls.cppClassName }}::schemaType;
}
{% if cls.isAppliedAPISchema %}
/* static */
{{ cls.cppClassName }}
{% if cls.isPrivateApply %}
{% if not cls.isMultipleApply %}
{{ cls.cppClassName }}::_Apply(const UsdPrim &prim)
{% else %}
{{ cls.cppClassName }}::_Apply(const UsdPrim &prim, const TfToken &name)
{% endif %}
{% else %}
{% if not cls.isMultipleApply %}
{{ cls.cppClassName }}::Apply(const UsdPrim &prim)
{% else %}
{{ cls.cppClassName }}::Apply(const UsdPrim &prim, const TfToken &name)
{% endif %}
{% endif %}
{
{% if cls.isMultipleApply %}
if (prim.ApplyAPI<{{ cls.cppClassName }}>(name)) {
return {{ cls.cppClassName }}(prim, name);
}
{% else %}
if (prim.ApplyAPI<{{ cls.cppClassName }}>()) {
return {{ cls.cppClassName }}(prim);
}
{% endif %}
return {{ cls.cppClassName }}();
}
{% endif %}
/* static */
const TfType &
{{ cls.cppClassName }}::_GetStaticTfType()
{
static TfType tfType = TfType::Find<{{ cls.cppClassName }}>();
return tfType;
}
/* static */
bool
{{ cls.cppClassName }}::_IsTypedSchema()
{
static bool isTyped = _GetStaticTfType().IsA<UsdTyped>();
return isTyped;
}
/* virtual */
const TfType &
{{ cls.cppClassName }}::_GetTfType() const
{
return _GetStaticTfType();
}
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
/// Returns the property name prefixed with the correct namespace prefix, which
/// is composed of the the API's propertyNamespacePrefix metadata and the
/// instance name of the API.
static inline
TfToken
_GetNamespacedPropertyName(const TfToken instanceName, const TfToken propName)
{
TfTokenVector identifiers =
{_schemaTokens->{{ cls.propertyNamespacePrefix }}, instanceName, propName};
return TfToken(SdfPath::JoinIdentifier(identifiers));
}
{% endif %}
{% for attrName in cls.attrOrder %}
{% set attr = cls.attrs[attrName] %}
{# Only emit Create/Get API and doxygen if apiName is not empty string. #}
{% if attr.apiName != '' %}
{% if attr.apiGet != "custom" %}
UsdAttribute
{{ cls.cppClassName }}::Get{{ Proper(attr.apiName) }}Attr() const
{
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
return GetPrim().GetAttribute(
_GetNamespacedPropertyName(
GetName(),
{{ tokensPrefix }}Tokens->{{ attr.name }}));
{% else %}
return GetPrim().GetAttribute({{ tokensPrefix }}Tokens->{{ attr.name }});
{% endif %}
}
{% endif %}
UsdAttribute
{{ cls.cppClassName }}::Create{{ Proper(attr.apiName) }}Attr(VtValue const &defaultValue, bool writeSparsely) const
{
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
return UsdSchemaBase::_CreateAttr(
_GetNamespacedPropertyName(
GetName(),
{{ tokensPrefix }}Tokens->{{ attr.name }}),
{% else %}
return UsdSchemaBase::_CreateAttr({{ tokensPrefix }}Tokens->{{ attr.name }},
{% endif %}
{{ attr.usdType }},
/* custom = */ {{ "true" if attr.custom else "false" }},
{{ attr.variability }},
defaultValue,
writeSparsely);
}
{% endif %}
{% endfor %}
{% for relName in cls.relOrder %}
{% set rel = cls.rels[relName] %}
{# Only emit Create/Get API and doxygen if apiName is not empty string. #}
{% if rel.apiName != '' %}
{% if rel.apiGet != "custom" %}
UsdRelationship
{{ cls.cppClassName }}::Get{{ Proper(rel.apiName) }}Rel() const
{
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
return GetPrim().GetRelationship(
_GetNamespacedPropertyName(
GetName(),
{{ tokensPrefix }}Tokens->{{ rel.name }}));
{% else %}
return GetPrim().GetRelationship({{ tokensPrefix }}Tokens->{{ rel.name }});
{% endif %}
}
{% endif %}
UsdRelationship
{{ cls.cppClassName }}::Create{{ Proper(rel.apiName) }}Rel() const
{
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
return GetPrim().CreateRelationship(
_GetNamespacedPropertyName(
GetName(),
{{ tokensPrefix }}Tokens->{{ rel.name }}),
{% else %}
return GetPrim().CreateRelationship({{ tokensPrefix }}Tokens->{{rel.name}},
{% endif %}
/* custom = */ {{ "true" if rel.custom else "false" }});
}
{% endif %}
{% endfor %}
{% if cls.attrOrder|length > 0 %}
namespace {
static inline TfTokenVector
{% if cls.isMultipleApply %}
_ConcatenateAttributeNames(
const TfToken instanceName,
const TfTokenVector& left,
const TfTokenVector& right)
{% else %}
_ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right)
{% endif %}
{
TfTokenVector result;
result.reserve(left.size() + right.size());
result.insert(result.end(), left.begin(), left.end());
{% if cls.isMultipleApply %}
for (const TfToken attrName : right) {
result.push_back(
_GetNamespacedPropertyName(instanceName, attrName));
}
{% endif %}
result.insert(result.end(), right.begin(), right.end());
return result;
}
}
{% endif %}
/*static*/
const TfTokenVector&
{% if cls.isMultipleApply %}
{{ cls.cppClassName }}::GetSchemaAttributeNames(
bool includeInherited, const TfToken instanceName)
{% else %}
{{ cls.cppClassName }}::GetSchemaAttributeNames(bool includeInherited)
{% endif %}
{
{% if cls.attrOrder|length > 0 %}
static TfTokenVector localNames = {
{% for attrName in cls.attrOrder %}
{% set attr = cls.attrs[attrName] %}
{{ tokensPrefix }}Tokens->{{ attr.name }},
{% endfor %}
};
{% if cls.isMultipleApply %}
static TfTokenVector allNames =
_ConcatenateAttributeNames(
instanceName,
{# The schema generator has already validated whether our parent is #}
{# a multiple apply schema or UsdSchemaBaseAPI, choose the correct function #}
{# depending on the situation #}
{% if cls.parentCppClassName == "UsdAPISchemaBase" %}
{{ cls.parentCppClassName }}::GetSchemaAttributeNames(true),
{% else %}
{{ cls.parentCppClassName }}::GetSchemaAttributeNames(true, instanceName),
{% endif %}
localNames);
{% else %}
static TfTokenVector allNames =
_ConcatenateAttributeNames(
{{ cls.parentCppClassName }}::GetSchemaAttributeNames(true),
localNames);
{% endif %}
{% else %}
static TfTokenVector localNames;
static TfTokenVector allNames =
{{ cls.parentCppClassName }}::GetSchemaAttributeNames(true);
{% endif %}
if (includeInherited)
return allNames;
else
return localNames;
}
{% if useExportAPI %}
{{ namespaceClose }}
{% endif %}
// ===================================================================== //
// Feel free to add custom code below this line. It will be preserved by
// the code generator.
{% if useExportAPI %}
//
// Just remember to wrap code in the appropriate delimiters:
// '{{ namespaceOpen }}', '{{ namespaceClose }}'.
{% endif %}
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
| 12,227 | C++ | 29.41791 | 115 | 0.63278 |
USwampertor/OmniverseJS/ov/usd/usd/resources/codegenTemplates/tokens.h | //
// 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.
//
#ifndef {{ Upper(tokensPrefix) }}_TOKENS_H
#define {{ Upper(tokensPrefix) }}_TOKENS_H
/// \file {{ libraryName }}/tokens.h
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
//
// This is an automatically generated file (by usdGenSchema.py).
// Do not hand-edit!
//
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
{% if useExportAPI %}
#include "pxr/pxr.h"
#include "{{ libraryPath }}/api.h"
{% endif %}
#include "pxr/base/tf/staticData.h"
#include "pxr/base/tf/token.h"
#include <vector>
{% if useExportAPI %}
{{ namespaceOpen }}
{% endif %}
/// \class {{ tokensPrefix }}TokensType
///
/// \link {{ tokensPrefix }}Tokens \endlink provides static, efficient
/// \link TfToken TfTokens\endlink for use in all public USD API.
///
/// These tokens are auto-generated from the module's schema, representing
/// property names, for when you need to fetch an attribute or relationship
/// directly by name, e.g. UsdPrim::GetAttribute(), in the most efficient
/// manner, and allow the compiler to verify that you spelled the name
/// correctly.
///
/// {{ tokensPrefix }}Tokens also contains all of the \em allowedTokens values
/// declared for schema builtin attributes of 'token' scene description type.
{% if tokens %}
/// Use {{ tokensPrefix }}Tokens like so:
///
/// \code
/// gprim.GetMyTokenValuedAttr().Set({{ tokensPrefix }}Tokens->{{ tokens[0].id }});
/// \endcode
{% endif %}
struct {{ tokensPrefix }}TokensType {
{% if useExportAPI %}{{ Upper(libraryName) }}_API {% endif %}{{ tokensPrefix }}TokensType();
{% for token in tokens %}
/// \brief "{{ token.value }}"
///
/// {{ token.desc }}
const TfToken {{ token.id }};
{% endfor %}
/// A vector of all of the tokens listed above.
const std::vector<TfToken> allTokens;
};
/// \var {{ tokensPrefix }}Tokens
///
/// A global variable with static, efficient \link TfToken TfTokens\endlink
/// for use in all public USD API. \sa {{ tokensPrefix }}TokensType
extern{% if useExportAPI %} {{ Upper(libraryName) }}_API{% endif %} TfStaticData<{{ tokensPrefix }}TokensType> {{ tokensPrefix }}Tokens;
{% if useExportAPI %}
{{ namespaceClose }}
{% endif %}
#endif
| 3,255 | C | 34.391304 | 136 | 0.701382 |
USwampertor/OmniverseJS/ov/usd/usd/resources/codegenTemplates/wrapSchemaClass.cpp | //
// 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.
//
#include "{{ libraryPath }}/{{ cls.GetHeaderFile() }}"
#include "pxr/usd/usd/schemaBase.h"
#include "pxr/usd/sdf/primSpec.h"
#include "pxr/usd/usd/pyConversions.h"
#include "pxr/base/tf/pyContainerConversions.h"
#include "pxr/base/tf/pyResultConversions.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/wrapTypeHelpers.h"
#include <boost/python.hpp>
#include <string>
using namespace boost::python;
{% if useExportAPI %}
{{ namespaceUsing }}
namespace {
{% endif %}
#define WRAP_CUSTOM \
template <class Cls> static void _CustomWrapCode(Cls &_class)
// fwd decl.
WRAP_CUSTOM;
{% for attrName in cls.attrOrder -%}
{% set attr = cls.attrs[attrName] %}
{# Only emit Create/Get API if apiName is not empty string. #}
{% if attr.apiName != '' %}
static UsdAttribute
_Create{{ Proper(attr.apiName) }}Attr({{ cls.cppClassName }} &self,
object defaultVal, bool writeSparsely) {
return self.Create{{ Proper(attr.apiName) }}Attr(
UsdPythonToSdfType(defaultVal, {{ attr.usdType }}), writeSparsely);
}
{% endif %}
{% endfor %}
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
static bool _WrapIs{{ cls.usdPrimTypeName }}Path(const SdfPath &path) {
TfToken collectionName;
return {{ cls.cppClassName }}::Is{{ cls.usdPrimTypeName }}Path(
path, &collectionName);
}
{% endif %}
{% if not cls.isAPISchemaBase %}
static std::string
_Repr(const {{ cls.cppClassName }} &self)
{
std::string primRepr = TfPyRepr(self.GetPrim());
{% if cls.isMultipleApply %}
std::string instanceName = self.GetName();
return TfStringPrintf(
"{{ libraryName[0]|upper }}{{ libraryName[1:] }}.{{ cls.className }}(%s, '%s')",
primRepr.c_str(), instanceName.c_str());
{% else %}
return TfStringPrintf(
"{{ libraryName[0]|upper }}{{ libraryName[1:] }}.{{ cls.className }}(%s)",
primRepr.c_str());
{% endif %}
}
{% endif %}
{% if useExportAPI %}
} // anonymous namespace
{% endif %}
void wrap{{ cls.cppClassName }}()
{
typedef {{ cls.cppClassName }} This;
{% if cls.isAPISchemaBase %}
class_< This , bases<{{ cls.parentCppClassName }}>, boost::noncopyable> cls ("APISchemaBase", "", no_init);
{% else %}
class_<This, bases<{{ cls.parentCppClassName }}> >
cls("{{ cls.className }}");
{% endif %}
cls
{% if not cls.isAPISchemaBase %}
{% if cls.isMultipleApply %}
.def(init<UsdPrim, TfToken>())
.def(init<UsdSchemaBase const&, TfToken>())
{% else %}
.def(init<UsdPrim>(arg("prim")))
.def(init<UsdSchemaBase const&>(arg("schemaObj")))
{% endif %}
{% endif %}
.def(TfTypePythonClass())
{% if not cls.isAPISchemaBase %}
{% if cls.isMultipleApply %}
.def("Get",
({{ cls.cppClassName }}(*)(const UsdStagePtr &stage,
const SdfPath &path))
&This::Get,
(arg("stage"), arg("path")))
.def("Get",
({{ cls.cppClassName }}(*)(const UsdPrim &prim,
const TfToken &name))
&This::Get,
(arg("prim"), arg("name")))
{% else %}
.def("Get", &This::Get, (arg("stage"), arg("path")))
{% endif %}
.staticmethod("Get")
{% endif %}
{% if cls.isConcrete %}
.def("Define", &This::Define, (arg("stage"), arg("path")))
.staticmethod("Define")
{% endif %}
{% if cls.isAppliedAPISchema and not cls.isMultipleApply and not cls.isPrivateApply %}
.def("Apply", &This::Apply, (arg("prim")))
.staticmethod("Apply")
{% endif %}
{% if cls.isAppliedAPISchema and cls.isMultipleApply and not cls.isPrivateApply %}
.def("Apply", &This::Apply, (arg("prim"), arg("name")))
.staticmethod("Apply")
{% endif %}
.def("GetSchemaAttributeNames",
&This::GetSchemaAttributeNames,
arg("includeInherited")=true,
{% if cls.isMultipleApply %}
arg("instanceName")=TfToken(),
{% endif %}
return_value_policy<TfPySequenceToList>())
.staticmethod("GetSchemaAttributeNames")
.def("_GetStaticTfType", (TfType const &(*)()) TfType::Find<This>,
return_value_policy<return_by_value>())
.staticmethod("_GetStaticTfType")
.def(!self)
{% for attrName in cls.attrOrder -%}
{% set attr = cls.attrs[attrName] %}
{# Only emit Create/Get API if apiName is not empty string. #}
{% if attr.apiName != '' %}
.def("Get{{ Proper(attr.apiName) }}Attr",
&This::Get{{ Proper(attr.apiName) }}Attr)
.def("Create{{ Proper(attr.apiName) }}Attr",
&_Create{{ Proper(attr.apiName) }}Attr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
{% endif %}
{% endfor %}
{% for relName in cls.relOrder -%}
{# Only emit Create/Get API and doxygen if apiName is not empty string. #}
{% set rel = cls.rels[relName] %}
{% if rel.apiName != '' %}
.def("Get{{ Proper(rel.apiName) }}Rel",
&This::Get{{ Proper(rel.apiName) }}Rel)
.def("Create{{ Proper(rel.apiName) }}Rel",
&This::Create{{ Proper(rel.apiName) }}Rel)
{% endif %}
{% endfor %}
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
.def("Is{{ cls.usdPrimTypeName }}Path", _WrapIs{{ cls.usdPrimTypeName }}Path)
.staticmethod("Is{{ cls.usdPrimTypeName }}Path")
{% endif %}
{% if not cls.isAPISchemaBase %}
.def("__repr__", ::_Repr)
{% endif %}
;
_CustomWrapCode(cls);
}
// ===================================================================== //
// Feel free to add custom code below this line, it will be preserved by
// the code generator. The entry point for your custom code should look
// minimally like the following:
//
// WRAP_CUSTOM {
// _class
// .def("MyCustomMethod", ...)
// ;
// }
//
// Of course any other ancillary or support code may be provided.
{% if useExportAPI %}
//
// Just remember to wrap code in the appropriate delimiters:
// 'namespace {', '}'.
//
{% endif %}
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
| 7,316 | C++ | 31.376106 | 111 | 0.597184 |
USwampertor/OmniverseJS/ov/usd/usd/resources/codegenTemplates/wrapTokens.cpp | //
// 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.
//
// GENERATED FILE. DO NOT EDIT.
#include <boost/python/class.hpp>
#include "{{ libraryPath }}/tokens.h"
{% if useExportAPI %}
{{ namespaceUsing }}
{% endif %}
namespace {
// Helper to return a static token as a string. We wrap tokens as Python
// strings and for some reason simply wrapping the token using def_readonly
// bypasses to-Python conversion, leading to the error that there's no
// Python type for the C++ TfToken type. So we wrap this functor instead.
class _WrapStaticToken {
public:
_WrapStaticToken(const TfToken* token) : _token(token) { }
std::string operator()() const
{
return _token->GetString();
}
private:
const TfToken* _token;
};
template <typename T>
void
_AddToken(T& cls, const char* name, const TfToken& token)
{
cls.add_static_property(name,
boost::python::make_function(
_WrapStaticToken(&token),
boost::python::return_value_policy<
boost::python::return_by_value>(),
boost::mpl::vector1<std::string>()));
}
} // anonymous
void wrap{{ tokensPrefix }}Tokens()
{
boost::python::class_<{{ tokensPrefix }}TokensType, boost::noncopyable>
cls("Tokens", boost::python::no_init);
{% for token in tokens %}
_AddToken(cls, "{{ token.id }}", {{ tokensPrefix }}Tokens->{{ token.id }});
{% endfor %}
}
| 2,521 | C++ | 33.547945 | 79 | 0.662436 |
USwampertor/OmniverseJS/ov/usd/usd/resources/codegenTemplates/schemaClass.h | //
// 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.
//
#ifndef {{ Upper(libraryName) }}_GENERATED_{{ Upper(cls.className) }}_H
#define {{ Upper(libraryName) }}_GENERATED_{{ Upper(cls.className) }}_H
/// \file {{ libraryName }}/{{ cls.GetHeaderFile() }}
{% if useExportAPI %}
#include "pxr/pxr.h"
#include "{{ libraryPath }}/api.h"
{% endif %}
#include "{{ cls.parentLibPath }}/{{ cls.GetParentHeaderFile() }}"
#include "pxr/usd/usd/prim.h"
#include "pxr/usd/usd/stage.h"
{% if cls.tokens -%}
#include "{{ libraryPath }}/tokens.h"
{% endif %}
{% if cls.extraIncludes -%}
{{ cls.extraIncludes }}
{% endif %}
#include "pxr/base/vt/value.h"
#include "pxr/base/gf/vec3d.h"
#include "pxr/base/gf/vec3f.h"
#include "pxr/base/gf/matrix4d.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/type.h"
{% if useExportAPI %}
{{ namespaceOpen }}
{% endif %}
class SdfAssetPath;
// -------------------------------------------------------------------------- //
// {{ Upper(cls.usdPrimTypeName) }}{{' ' * (74 - cls.usdPrimTypeName|count)}} //
// -------------------------------------------------------------------------- //
/// \class {{ cls.cppClassName }}
///
{% if cls.doc -%}
/// {{ cls.doc }}
{% endif %}
{% if cls.doc and hasTokenAttrs -%}
///
{%endif%}
{% if hasTokenAttrs -%}
/// For any described attribute \em Fallback \em Value or \em Allowed \em Values below
/// that are text/tokens, the actual token is published and defined in \ref {{ tokensPrefix }}Tokens.
/// So to set an attribute to the value "rightHanded", use {{ tokensPrefix }}Tokens->rightHanded
/// as the value.
{% endif %}
///
class {{ cls.cppClassName }} : public {{ cls.parentCppClassName }}
{
public:
/// Compile time constant representing what kind of schema this class is.
///
/// \sa UsdSchemaType
static const UsdSchemaType schemaType = {{cls.schemaType }};
{% if cls.isMultipleApply %}
/// Construct a {{ cls.cppClassName }} on UsdPrim \p prim with
/// name \p name . Equivalent to
/// {{ cls.cppClassName }}::Get(
/// prim.GetStage(),
/// prim.GetPath().AppendProperty(
/// "{{ cls.propertyNamespacePrefix }}:name"));
///
/// for a \em valid \p prim, but will not immediately throw an error for
/// an invalid \p prim
explicit {{ cls.cppClassName }}(
const UsdPrim& prim=UsdPrim(), const TfToken &name=TfToken())
: {{ cls.parentCppClassName }}(prim, /*instanceName*/ name)
{ }
/// Construct a {{ cls.cppClassName }} on the prim held by \p schemaObj with
/// name \p name. Should be preferred over
/// {{ cls.cppClassName }}(schemaObj.GetPrim(), name), as it preserves
/// SchemaBase state.
explicit {{ cls.cppClassName }}(
const UsdSchemaBase& schemaObj, const TfToken &name)
: {{ cls.parentCppClassName }}(schemaObj, /*instanceName*/ name)
{ }
{% else %}
/// Construct a {{ cls.cppClassName }} on UsdPrim \p prim .
/// Equivalent to {{ cls.cppClassName }}::Get(prim.GetStage(), prim.GetPath())
/// for a \em valid \p prim, but will not immediately throw an error for
/// an invalid \p prim
explicit {{ cls.cppClassName }}(const UsdPrim& prim=UsdPrim())
: {{ cls.parentCppClassName }}(prim)
{
}
/// Construct a {{ cls.cppClassName }} on the prim held by \p schemaObj .
/// Should be preferred over {{ cls.cppClassName }}(schemaObj.GetPrim()),
/// as it preserves SchemaBase state.
explicit {{ cls.cppClassName }}(const UsdSchemaBase& schemaObj)
: {{ cls.parentCppClassName }}(schemaObj)
{
}
{% endif %}
/// Destructor.
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
virtual ~{{ cls.cppClassName }}() {%- if cls.isAPISchemaBase %} = 0{% endif %};
{% if cls.isMultipleApply %}
/// Return a vector of names of all pre-declared attributes for this schema
/// class and all its ancestor classes for a given instance name. Does not
/// include attributes that may be authored by custom/extended methods of
/// the schemas involved. The names returned will have the proper namespace
/// prefix.
{% else %}
/// Return a vector of names of all pre-declared attributes for this schema
/// class and all its ancestor classes. Does not include attributes that
/// may be authored by custom/extended methods of the schemas involved.
{% endif %}
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static const TfTokenVector &
{% if cls.isMultipleApply %}
GetSchemaAttributeNames(
bool includeInherited=true, const TfToken instanceName=TfToken());
{% else %}
GetSchemaAttributeNames(bool includeInherited=true);
{% endif %}
{% if cls.isMultipleApply %}
/// Returns the name of this multiple-apply schema instance
TfToken GetName() const {
return _GetInstanceName();
}
{% endif %}
{% if not cls.isAPISchemaBase %}
/// Return a {{ cls.cppClassName }} holding the prim adhering to this
/// schema at \p path on \p stage. If no prim exists at \p path on
/// \p stage, or if the prim at that path does not adhere to this schema,
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
/// return an invalid schema object. \p path must be of the format
/// <path>.{{ cls.propertyNamespacePrefix }}:name .
///
/// This is shorthand for the following:
///
/// \code
/// TfToken name = SdfPath::StripNamespace(path.GetToken());
/// {{ cls.cppClassName }}(
/// stage->GetPrimAtPath(path.GetPrimPath()), name);
/// \endcode
{% else %}
/// return an invalid schema object. This is shorthand for the following:
///
/// \code
/// {{ cls.cppClassName }}(stage->GetPrimAtPath(path));
/// \endcode
{% endif %}
///
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static {{ cls.cppClassName }}
Get(const UsdStagePtr &stage, const SdfPath &path);
{% if cls.isMultipleApply %}
/// Return a {{ cls.cppClassName }} with name \p name holding the
/// prim \p prim. Shorthand for {{ cls.cppClassName }}(prim, name);
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static {{ cls.cppClassName }}
Get(const UsdPrim &prim, const TfToken &name);
{% endif %}
{% endif %}
{% if cls.isConcrete %}
/// Attempt to ensure a \a UsdPrim adhering to this schema at \p path
/// is defined (according to UsdPrim::IsDefined()) on this stage.
///
/// If a prim adhering to this schema at \p path is already defined on this
/// stage, return that prim. Otherwise author an \a SdfPrimSpec with
/// \a specifier == \a SdfSpecifierDef and this schema's prim type name for
/// the prim at \p path at the current EditTarget. Author \a SdfPrimSpec s
/// with \p specifier == \a SdfSpecifierDef and empty typeName at the
/// current EditTarget for any nonexistent, or existing but not \a Defined
/// ancestors.
///
/// The given \a path must be an absolute prim path that does not contain
/// any variant selections.
///
/// If it is impossible to author any of the necessary PrimSpecs, (for
/// example, in case \a path cannot map to the current UsdEditTarget's
/// namespace) issue an error and return an invalid \a UsdPrim.
///
/// Note that this method may return a defined prim whose typeName does not
/// specify this schema class, in case a stronger typeName opinion overrides
/// the opinion at the current EditTarget.
///
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static {{ cls.cppClassName }}
Define(const UsdStagePtr &stage, const SdfPath &path);
{% endif %}
{% if cls.isMultipleApply and cls.propertyNamespacePrefix %}
/// Checks if the given name \p baseName is the base name of a property
/// of {{ cls.usdPrimTypeName }}.
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static bool
IsSchemaPropertyBaseName(const TfToken &baseName);
/// Checks if the given path \p path is of an API schema of type
/// {{ cls.usdPrimTypeName }}. If so, it stores the instance name of
/// the schema in \p name and returns true. Otherwise, it returns false.
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static bool
Is{{ cls.usdPrimTypeName }}Path(const SdfPath &path, TfToken *name);
{% endif %}
{% if cls.isPrivateApply %}
private:
{% endif %}
{% if cls.isAppliedAPISchema and not cls.isMultipleApply %}
/// Applies this <b>single-apply</b> API schema to the given \p prim.
/// This information is stored by adding "{{ cls.primName }}" to the
/// token-valued, listOp metadata \em apiSchemas on the prim.
///
/// \return A valid {{ cls.cppClassName }} object is returned upon success.
/// An invalid (or empty) {{ cls.cppClassName }} object is returned upon
/// failure. See \ref UsdPrim::ApplyAPI() for conditions
/// resulting in failure.
///
/// \sa UsdPrim::GetAppliedSchemas()
/// \sa UsdPrim::HasAPI()
/// \sa UsdPrim::ApplyAPI()
/// \sa UsdPrim::RemoveAPI()
///
{% if useExportAPI and not cls.isPrivateApply -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static {{ cls.cppClassName }}
{% if cls.isPrivateApply %}
_Apply(const UsdPrim &prim);
{% else %}
Apply(const UsdPrim &prim);
{% endif %}
{% endif %}
{% if cls.isAppliedAPISchema and cls.isMultipleApply %}
/// Applies this <b>multiple-apply</b> API schema to the given \p prim
/// along with the given instance name, \p name.
///
/// This information is stored by adding "{{ cls.primName }}:<i>name</i>"
/// to the token-valued, listOp metadata \em apiSchemas on the prim.
/// For example, if \p name is 'instance1', the token
/// '{{ cls.primName }}:instance1' is added to 'apiSchemas'.
///
/// \return A valid {{ cls.cppClassName }} object is returned upon success.
/// An invalid (or empty) {{ cls.cppClassName }} object is returned upon
/// failure. See \ref UsdPrim::ApplyAPI() for
/// conditions resulting in failure.
///
/// \sa UsdPrim::GetAppliedSchemas()
/// \sa UsdPrim::HasAPI()
/// \sa UsdPrim::ApplyAPI()
/// \sa UsdPrim::RemoveAPI()
///
{% if useExportAPI and not cls.isPrivateApply -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static {{ cls.cppClassName }}
{% if cls.isPrivateApply %}
_Apply(const UsdPrim &prim, const TfToken &name);
{% else %}
Apply(const UsdPrim &prim, const TfToken &name);
{% endif %}
{% endif %}
protected:
/// Returns the type of schema this class belongs to.
///
/// \sa UsdSchemaType
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
UsdSchemaType _GetSchemaType() const override;
private:
// needs to invoke _GetStaticTfType.
friend class UsdSchemaRegistry;
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
static const TfType &_GetStaticTfType();
static bool _IsTypedSchema();
// override SchemaBase virtuals.
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
const TfType &_GetTfType() const override;
{% for attrName in cls.attrOrder %}
{% set attr = cls.attrs[attrName]%}
{# Only emit Create/Get API and doxygen if apiName is not empty string. #}
{% if attr.apiName != '' %}
public:
// --------------------------------------------------------------------- //
// {{ Upper(attr.apiName) }}
// --------------------------------------------------------------------- //
/// {{ attr.doc }}
///
{% if attr.details %}
/// | ||
/// | -- | -- |
{% for detail in attr.details %}
/// | {{ detail[0] }} | {{ detail[1] }} |
{% endfor %}
{% endif %}
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
UsdAttribute Get{{ Proper(attr.apiName) }}Attr() const;
/// See Get{{ Proper(attr.apiName) }}Attr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
UsdAttribute Create{{ Proper(attr.apiName) }}Attr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
{% endif %}
{% endfor %}
{% for relName in cls.relOrder %}
{% set rel = cls.rels[relName]%}
{# Only emit Create/Get API and doxygen if apiName is not empty string. #}
{% if rel.apiName != '' %}
public:
// --------------------------------------------------------------------- //
// {{ Upper(rel.apiName) }}
// --------------------------------------------------------------------- //
/// {{ rel.doc }}
///
{% for detail in rel.details %}
/// \n {{ detail[0] }}: {{ detail[1] }}
{% endfor %}
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
UsdRelationship Get{{ Proper(rel.apiName) }}Rel() const;
/// See Get{{ Proper(rel.apiName) }}Rel(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create
{% if useExportAPI -%}
{{ Upper(libraryName) }}_API
{% endif -%}
UsdRelationship Create{{ Proper(rel.apiName) }}Rel() const;
{% endif %}
{% endfor %}
public:
// ===================================================================== //
// Feel free to add custom code below this line, it will be preserved by
// the code generator.
//
// Just remember to:
// - Close the class declaration with };
{% if useExportAPI %}
// - Close the namespace with {{ namespaceClose }}
{% endif %}
// - Close the include guard with #endif
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
| 15,039 | C | 35.772616 | 127 | 0.605093 |
USwampertor/OmniverseJS/ov/usd/usd/resources/codegenTemplates/tokens.cpp | //
// 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.
//
#include "{{ libraryPath }}/tokens.h"
{% if useExportAPI %}
{{ namespaceOpen }}
{% endif %}
{{ tokensPrefix }}TokensType::{{ tokensPrefix }}TokensType() :
{% for token in tokens %}
{{ token.id }}("{{ token.value }}", TfToken::Immortal),
{% endfor %}
allTokens({
{% for token in tokens %}
{{ token.id }}{% if not loop.last %},{% endif %}
{% endfor %}
})
{
}
TfStaticData<{{ tokensPrefix }}TokensType> {{ tokensPrefix }}Tokens;
{% if useExportAPI %}
{{ namespaceClose }}
{% endif %}
| 1,588 | C++ | 32.104166 | 75 | 0.696474 |
Motionverse/MV-omniverse-extension/README.md | # Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "motionverse.engine.decoder" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable company.hello.world
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
| 2,050 | Markdown | 37.698112 | 258 | 0.758049 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/config/extension.toml | [package]
version = "1.0.0"
authors = ["Guowei Zhou <[email protected]>"]
title = "Motionverse"
description = "#"
readme = "docs/README.md"
# URL of the extension source repository.
repository = "https://github.com/Motionverse/MV-omniverse-extension.git"
# One of categories for UI.
category = "Animation"
# Keywords for the extension
keywords = ["Ai", "Text","Audio","Animation"]
# Icon to show in the extension manager
icon = "data/logo.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import motionverse.engine.coder".
[[python.module]]
name = "motionverse.engine.coder"
| 777 | TOML | 22.575757 | 113 | 0.727156 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/docs/CHANGELOG.md | # Changelog
Motionverse Extension changelog
===========================================
## [1.0.0] - 2022-07-15 | 113 | Markdown | 21.799996 | 43 | 0.433628 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/docs/README.md | # Motionverse Extension
| 24 | Markdown | 11.499994 | 23 | 0.833333 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/motionverse/engine/coder/constants.py | # Copyright (c) 2022 Motionverse Inc. All rights reserved.
# UI constants
WINDOW_NAME = "Motionverse"
CS_HOSTNAME_TEXT = "Host/IP"
CS_PORT_TEXT = "PORT"
CS_GOTO_BTN_TEXT = "Contact us"
CS_START_BTN_TEXT = "Start streaming"
CS_STOP_BTN_TEXT = "Stop streaming"
CS_URL = "http://motionverse.io/omniverse"
SKEL_SOURCE_EDIT_TEXT = "Target skeleton"
SKEL_SOURCE_BTN_TEXT = "Use highlighted skeleton"
SKEL_INVALID_TEXT = "No skeleton selected"
RIG_DROPDOWN_TEXT = "Rig Type"
RIG_UNSUPPORTED_TEXT = "Unsupported rig"
# UI image filepaths
LOGO_FILEPATH = "/data/logo-white.png"
# UI widget spacing
CS_H_SPACING = 5
# general constants
DEFAULT_PORT = 4188 | 648 | Python | 27.21739 | 58 | 0.736111 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/motionverse/engine/coder/extension.py | from email import message
from operator import le
import carb
import omni.ext
import omni.ui as ui
import omni.timeline
import omni.usd
import omni.kit.window.file
from pxr import Vt, Gf, UsdSkel, Usd, Sdf, UsdGeom
import struct
import asyncio
import pathlib
from typing import cast, Union, List
import traceback
import webbrowser
from .constants import *
import json
import glob
import numpy as np
def get_rig_index(model_joint_names, rig_mappings):
candidates = [mapping["joint_mappings"].keys() for mapping in rig_mappings]
index = None
for i in range(len(candidates)):
if all([(joint in model_joint_names) for joint in candidates[i]]):
index = i
return index
def get_all_descendents(prim: Usd.Prim, result: List[Usd.Prim] = []):
if len(result) == 0:
result.append(prim)
children = prim.GetChildren()
result.extend(list(children))
for child in children:
get_all_descendents(child, result)
def find_skeleton(path):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(path)
descendants = []
get_all_descendents(prim, descendants)
skeleton = next(filter(lambda x: x.IsA(UsdSkel.Skeleton), descendants), None)
assert skeleton is not None, "Could not find skeleton"
print(UsdSkel.Skeleton(skeleton))
return UsdSkel.Skeleton(skeleton)
def find_blendShapes(path):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(path)
descendants = []
get_all_descendents(prim, descendants)
blendShapePrims = list(filter(lambda x: x.IsA(UsdSkel.BlendShape), descendants))
blendShapes = [UsdSkel.BlendShape(blendShape) for blendShape in blendShapePrims]
return blendShapes
def get_this_files_path():
return pathlib.Path(__file__).parent.absolute().as_posix()
#
# styles for UIController class
#
style_btn_enabled = {
"Button": {"border_radius": 5.0,"margin": 5.0,"padding": 10.0,"background_color": 0xFFFF7E09,"border_color": 0xFFFD761D},
"Button:hovered": {"background_color": 0xFFFF4F00},
"Button:pressed": {"background_color": 0xFFFAE26F},
"Button.Label": {"color": 0xFFFFFFFF},
}
style_btn_disabled = {
"Button": {"border_radius": 3.0,"margin": 5.0,"padding": 10.0,"background_color": 0xFFC0E0C0,"border_color": 0xFFFD7F1D},
"Button:hovered": {"background_color": 0xFFC0C0C0, "background_gradient_color": 0xFFFFAE5A},
"Button:pressed": {"background_color": 0xFFC0C0C0, "background_gradient_color": 0xFFFAB26D},
"Button.Label": {"color": 0xFF808080},
}
style_status_circle_green = {"background_color": 0xFF00FF00, "border_width": 0}
style_status_circle_red = {"background_color": 0xFF0000FF, "border_width": 0}
style_btn_goto_motionverse = {"Button": {"border_width": 0.0, "border_radius": 3.0, "margin": 5.0, "padding": 10.0}}
#
# UIController class
#
class UIController:
def __init__(self, ext):
self.ext = ext
self.extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext.ext_id)
self._streaming_active = False
self._window = ui.Window(WINDOW_NAME,width=600, height=260)
self.build_ui()
def build_ui(self):
with self._window.frame:
with ui.VStack(height=0):
with ui.HStack():
#logo
logo_path = f"{self.extension_path}{LOGO_FILEPATH}"
ui.Image(logo_path, width=50,height=50,fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,alignment=ui.Alignment.CENTER)
ui.Spacer()
ui.Button(
CS_GOTO_BTN_TEXT,width=ui.Percent(10), style=style_btn_goto_motionverse,alignment=ui.Alignment.RIGHT_CENTER, clicked_fn=self.launch_motionverse_website)
with ui.HStack():
# green/red status
with ui.VStack(width=50, alignment=ui.Alignment.TOP):
self._status_circle = ui.Circle(
radius = 8,size_policy=ui.CircleSizePolicy.FIXED, style=style_status_circle_red
)
ui.Spacer()
with ui.VStack():
# CaptureStream device selection drop-down
with ui.HStack():
ui.Label(
CS_HOSTNAME_TEXT, width=ui.Percent(20), alignment=ui.Alignment.RIGHT_CENTER
)
ui.Spacer(width=CS_H_SPACING)
with ui.VStack(width=ui.Percent(50)):
ui.Spacer()
self.source_ip_field = ui.StringField(
model=ui.SimpleStringModel("192.168.10.113"), height=0, visible=True
)
ui.Spacer()
ui.Label(
CS_PORT_TEXT, width=ui.Percent(10), alignment=ui.Alignment.RIGHT_CENTER
)
with ui.VStack(width=ui.Percent(10)):
ui.Spacer()
self.source_port_field = ui.StringField(
model=ui.SimpleStringModel("4188"), height=0, visible=True
)
ui.Spacer()
# skeleton selection
with ui.HStack():
ui.Label(
SKEL_SOURCE_EDIT_TEXT, width=ui.Percent(20), alignment=ui.Alignment.RIGHT_CENTER
)
ui.Spacer(width=CS_H_SPACING)
with ui.VStack(width=ui.Percent(50)):
ui.Spacer()
self._skeleton_to_drive_stringfield = ui.StringField(
model=ui.SimpleStringModel(SKEL_INVALID_TEXT), height=0, enabled=False
)
ui.Spacer()
ui.Spacer(width=CS_H_SPACING)
self._skel_select_button = ui.Button(
SKEL_SOURCE_BTN_TEXT, width=0, clicked_fn=self.select_skeleton
)
# rig selection
with ui.HStack():
ui.Label(RIG_DROPDOWN_TEXT, width=ui.Percent(20), alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=CS_H_SPACING)
with ui.VStack(width=ui.Percent(75)):
ui.Spacer()
self._selected_rig_label = ui.Label("")
ui.Spacer()
# start/stop stream buttons
with ui.HStack():
ui.Spacer(width=ui.Percent(20))
self._start_button = ui.Button(
CS_START_BTN_TEXT,
width=0,
clicked_fn=self.start_streaming,
enabled=not self.streaming_active,
style=style_btn_disabled if self.streaming_active else style_btn_enabled,
)
ui.Spacer(width=CS_H_SPACING)
self._stop_button = ui.Button(
CS_STOP_BTN_TEXT,
width=0,
clicked_fn=self.stop_streaming,
enabled=self.streaming_active,
style=style_btn_enabled if self.streaming_active else style_btn_disabled,
)
ui.Spacer(height=5)
def select_skeleton(self):
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
if paths:
path = paths[0]
try:
self.ext.init_skeletons(path)
except Exception as ex:
self._skeleton_to_drive_stringfield.model.set_value(SKEL_INVALID_TEXT)
self._selected_rig_label.text = self.ext.selected_rig_name or RIG_UNSUPPORTED_TEXT
def launch_motionverse_website(self):
webbrowser.open_new_tab(CS_URL)
def update_ui(self):
if self.streaming_active:
self._start_button.enabled = False
self._start_button.set_style(style_btn_disabled)
self._stop_button.enabled = True
self._stop_button.set_style(style_btn_enabled)
else:
self._start_button.enabled = self.ext.ready_to_stream
self._start_button.set_style(
style_btn_enabled if self.ext.ready_to_stream else style_btn_disabled
)
self._stop_button.enabled = False
self._stop_button.set_style(style_btn_disabled)
if self.streaming_active:
self._status_circle.set_style(style_status_circle_green)
else:
self._status_circle.set_style(style_status_circle_red)
self._skeleton_to_drive_stringfield.model.set_value(self.ext.target_skeleton_path)
def start_streaming(self):
self.ext.connect()
def stop_streaming(self):
self.ext.disconnect("User cancelled")
@property
def streaming_active(self):
return self._streaming_active
@streaming_active.setter
def streaming_active(self, value):
self._streaming_active = value
class MotionverseExtension(omni.ext.IExt):
def __init__(self):
self._net_io_task = None
self._update_skeleton_task = None
self.target_skeleton = None
self.skel_cache = UsdSkel.Cache()
def on_startup(self, ext_id):
self.import_rig_mappings_from_json_files()
self.ext_id = ext_id
stream = omni.kit.app.get_app().get_update_event_stream()
self.update_sub = stream.create_subscription_to_pop(self.update_ui, name="update frame")
self.ui_controller = UIController(self)
def connect(self):
self.disconnect("Resetting connection")
host = self.ui_controller.source_ip_field.model.as_string
port = self.ui_controller.source_port_field.model.as_int
loop = asyncio.get_event_loop()
queue = asyncio.Queue(maxsize=10, loop=loop)
if self._net_io_task:
loop.run_until_complete(asyncio.wait({self._net_io_task}, timeout=1.0))
if self._update_skeleton_task:
loop.run_until_complete(asyncio.wait({self._update_skeleton_task}, timeout=1.0))
self._net_io_task = loop.create_task(self._do_net_io(host, port, queue))
self._update_skeleton_task = loop.create_task(self._update_skeleton_loop(queue))
self._net_io_task.add_done_callback(self.on_task_complete)
self._update_skeleton_task.add_done_callback(self.on_task_complete)
def on_task_complete(self, fut=None):
if fut is self._net_io_task:
self._update_skeleton_task.cancel()
elif fut is self._update_skeleton_task:
self._net_io_task.cancel()
self.ui_controller.streaming_active = False
async def _do_net_io(self, host, port, queue):
self.ui_controller.streaming_active = True
writer = None
try:
reader, writer = await asyncio.open_connection(host, port)
writer.write(b"ov")
await self._read_client(reader, queue)
except asyncio.CancelledError:
print("Network streaming cancelled")
except:
carb.log_error(traceback.format_exc())
finally:
if writer is not None:
writer.close()
await writer.wait_closed()
print("TCP connection closed")
print("Net I/O task stopped")
async def _read_client(self, reader, queue):
while True:
message_data = await reader.readexactly(1660)
await queue.put(message_data)
async def _update_skeleton_loop(self, queue):
try:
while True:
message = await queue.get()
fd = FrameDetections()
fd.ParseFromString(message)
self.update_skeleton(fd)
except asyncio.CancelledError:
print("Skeleton update task cancelled")
except:
carb.log_error(traceback.format_exc())
def disconnect(self, reason=str()):
streaming_active = False
if self._net_io_task is not None:
self._net_io_task.cancel()
def import_rig_mappings_from_json_files(self):
self.rig_mappings = []
rig_filenames = glob.glob(get_this_files_path() + "/xform_*.json")
if rig_filenames is not None:
for filename in rig_filenames:
rig_mapfile = open(filename, "r")
if rig_mapfile is not None:
self.rig_mappings.append(json.load(rig_mapfile))
else:
print("error - could not load file %s" % filename)
def init_skeletons(self, skel_root_path):
self.selected_rig_index = None
self.motion_skel_anim = None
self.selected_joints = None
stage = omni.usd.get_context().get_stage()
selected_skeleton = find_skeleton(skel_root_path)
blendShapes = find_blendShapes(skel_root_path)
print("skel_cache =====",self.skel_cache)
skel_query = self.skel_cache.GetSkelQuery(selected_skeleton)
print("selected_skeleton ====",selected_skeleton)
print("blendShapes[0] ====",blendShapes[0])
# blendShape_query = UsdSkel.BlendShapeQuery(blendShapes[0])
# print("blendShape_query",blendShape_query)
joint_tokens = skel_query.GetJointOrder()
jointPaths = [Sdf.Path(jointToken) for jointToken in joint_tokens]
all_joint_names = [jointPath.name for jointPath in jointPaths]
# all_blendshape_names = [blendShapePath.name for blendShapePath in blendShapePaths]
self.selected_rig_index = get_rig_index(all_joint_names, self.rig_mappings)
assert self.selected_rig_index is not None, "Unsupported rig"
self.target_skeleton = selected_skeleton
self.target_skel_root = UsdSkel.Root.Find(self.target_skeleton.GetPrim())
# print("target_skeleton = ",self.target_skeleton.GetPrim())
# skel_root_rotate_xyz is a set of rotations in XYZ order used to align the rest pose
# with wrnch's axes (+Y up, +Z forward)
skel_root_rotate_xyz = self.rig_mappings[self.selected_rig_index]["skel_root_rotate_xyz"]
rot_x = Gf.Rotation(Gf.Vec3d(1, 0, 0), skel_root_rotate_xyz[0])
rot_y = Gf.Rotation(Gf.Vec3d(0, 1, 0), skel_root_rotate_xyz[1])
rot_z = Gf.Rotation(Gf.Vec3d(0, 0, 1), skel_root_rotate_xyz[2])
self.rest_xform_adjust = Gf.Matrix4d()
self.rest_xform_adjust.SetRotate(rot_x * rot_y * rot_z)
self.rest_xform_adjust_inverse = self.rest_xform_adjust.GetInverse()
if not skel_query.HasRestPose():
xforms = skel_query.ComputeJointLocalTransforms()
self.target_skeleton.GetRestTransformsAttr().Set(xforms)
self.skel_cache.Clear()
def update_skeleton(self, fd):
if self.selected_joints is None:
self._init_animation(fd.body_pose_names)
num_joints = len(self.rest_xforms_anim_global)
root_index = self.motion_to_anim_index["Hips"]
motion_xforms_global = Vt.Matrix4dArray(num_joints)
for i, pose in enumerate(fd.body_poses):
name = fd.body_pose_names[i]
if name in self.motion_to_anim_index:
anim_index = self.motion_to_anim_index[name]
q = pose['rotation']
t = pose['position']
rot = Gf.Rotation(Gf.Quatd(q[3], q[0], q[1], q[2]))
trans = Gf.Vec3d(t[0], t[1], t[2])
xform = Gf.Matrix4d()
xform.SetTransform(rot, trans)
motion_xforms_global[anim_index] = xform
target_pose_xforms_global = Vt.Matrix4dArray(
[
base_xform * motion_xform
for motion_xform, base_xform in zip(motion_xforms_global, self.rest_xforms_anim_global)
]
)
root_xform = self.rest_xform_adjust_inverse
target_xforms_local = UsdSkel.ComputeJointLocalTransforms(
self.anim_topology, target_pose_xforms_global, root_xform
)
anim_rotations = Vt.QuatfArray([Gf.Quatf(xform.ExtractRotationQuat()) for xform in target_xforms_local])
height_offset = 0
# Apply root motion to the animation attr
local_translations_attr = self.motion_skel_anim.GetTranslationsAttr()
local_translations = local_translations_attr.Get(0)
local_translations[root_index] = Gf.Vec3f(
root_xform.Transform(
Gf.Vec3d(0, 1, 0) * height_offset + motion_xforms_global[root_index].ExtractTranslation()
)
)
local_translations_attr.Set(local_translations, 0)
# Apply joint rotations to animation attr
self.motion_skel_anim.GetRotationsAttr().Set(anim_rotations, 0)
def _init_animation(self,selected_joints):
stage = omni.usd.get_context().get_stage()
rig_mapping = self.rig_mappings[self.selected_rig_index]["joint_mappings"]
skel_query = self.skel_cache.GetSkelQuery(self.target_skeleton)
joint_tokens = skel_query.GetJointOrder()
joint_names = {Sdf.Path(token).name: token for token in joint_tokens}
print(joint_names)
# Lookup index of joint by token
joint_token_indices = {token: index for index, token in enumerate(joint_tokens)}
motion_to_token = {
value: joint_names[key] for key, value in rig_mapping.items() if value in selected_joints
}
anim_tokens = Vt.TokenArray(motion_to_token.values())
assert len(anim_tokens) > 0
anim_token_indices = {token: index for index, token in enumerate(anim_tokens)}
active_token_indices = [joint_token_indices[token] for token in anim_tokens]
self.motion_to_anim_index = {
motion_name: anim_token_indices[token] for motion_name, token in motion_to_token.items()
}
self.anim_topology = UsdSkel.Topology([Sdf.Path(token) for token in anim_tokens])
assert self.anim_topology.Validate()
anim_path = self.target_skeleton.GetPath().AppendChild("SkelRoot")
self.motion_skel_anim = UsdSkel.Animation.Define(stage, anim_path)
print("anim_tokens=",anim_tokens)
self.motion_skel_anim.GetJointsAttr().Set(anim_tokens)
self.motion_skel_anim.GetBlendShapesAttr().Set(anim_tokens)
# Set our UsdSkelAnimation as the animationSource of the UsdSkelSkeleton
binding = UsdSkel.BindingAPI.Apply(self.target_skeleton.GetPrim())
binding.CreateAnimationSourceRel().SetTargets([self.motion_skel_anim.GetPrim().GetPath()])
# Set initial the scale, translation, and rotation attributes for the UsdSkelAnimation.
# Note that these attributes need to be in the UsdSkelSkeleton's Local Space.
root_xform = Gf.Matrix4d()
root_xform.SetIdentity()
root_xform = self.rest_xform_adjust
identity_xform = Gf.Matrix4d()
identity_xform.SetIdentity()
rest_xforms_local = self.target_skeleton.GetRestTransformsAttr().Get()
assert rest_xforms_local, "Skeleton has no restTransforms"
skel_topology = skel_query.GetTopology()
anim_start_index = active_token_indices[0]
xform_accum = Gf.Matrix4d()
xform_accum.SetIdentity()
index = skel_topology.GetParent(anim_start_index)
while index >= 0:
xform_accum = rest_xforms_local[index] * xform_accum
rest_xforms_local[index] = identity_xform
index = skel_topology.GetParent(index)
rest_xforms_local[anim_start_index] = xform_accum * rest_xforms_local[anim_start_index]
# Set the rest pose transforms
self.target_skeleton.GetRestTransformsAttr().Set(rest_xforms_local)
# Joint transforms in world coordinates such that the t-pose is aligned with wrnch's
# base t-pose (+Y up, +Z forward)
rest_xforms_global = UsdSkel.ConcatJointTransforms(skel_topology, rest_xforms_local, root_xform)
# Get the subset of the rest transforms that correspond to our UsdSkelAnimation attrs.
# We're going to concatenate these to the wrx transforms to get the desired
# pose
self.rest_xforms_anim_global = Vt.Matrix4dArray([rest_xforms_global[i] for i in active_token_indices])
base_xforms_anim_local = UsdSkel.ComputeJointLocalTransforms(
self.anim_topology, self.rest_xforms_anim_global, identity_xform
)
self.motion_skel_anim.SetTransforms(base_xforms_anim_local, 0)
self.selected_joints = set(selected_joints)
def update_ui(self, dt):
try:
self.ui_controller.update_ui()
except:
self.disconnect("Error updating UI")
raise
def on_shutdown(self):
self.ext = None
self._window = None
@property
def ready_to_stream(self):
has_skeleton_target = self.target_skeleton is not None and self.target_skeleton.GetPrim()
return has_skeleton_target
@property
def target_skeleton_path(self):
if not self.target_skeleton or not self.target_skeleton.GetPrim():
return ""
else:
return str(self.target_skeleton.GetPath())
@property
def selected_rig_name(self):
if self.selected_rig_index is not None:
return self.rig_mappings[self.selected_rig_index]["display_name"]
else:
return None
class FrameDetections():
def __init__(self):
self.body_poses = None
self.faces = None
self.body_pose_names = ("Hips","LeftUpLeg","RightUpLeg","LeftLeg","RightLeg","LeftFoot","RightFoot","Spine","Spine1","Neck","Head","LeftShoulder","RightShoulder","LeftArm",
"RightArm","LeftForeArm","RightForeArm","LeftHand","RightHand","LeftToeBase","RightToeBase","LeftHandThumb1","LeftHandThumb2","LeftHandThumb3",
"LeftHandIndex1","LeftHandIndex2","LeftHandIndex3","LeftHandMiddle1","LeftHandMiddle2","LeftHandMiddle3","LeftHandRing1","LeftHandRing2","LeftHandRing3","LeftHandPinky1",
"LeftHandPinky2","LeftHandPinky3","RightHandThumb1","RightHandThumb2","RightHandThumb3","RightHandIndex1","RightHandIndex2","RightHandIndex3","RightHandMiddle1",
"RightHandMiddle2","RightHandMiddle3","RightHandRing1","RightHandRing2","RightHandRing3","RightHandPinky1","RightHandPinky2","RightHandPinky3")
def ParseFromString(self,value):
message_list=struct.unpack("415f",value)
self.faces = message_list[:51]
body_data = np.array(message_list[51:]).reshape(-1, 7) #joints num, 4+3
self.body_poses = [{'rotation': body_data[idx][:4], 'position': body_data[idx][4:]}
for idx in range(len(self.body_pose_names))]
| 23,616 | Python | 39.302048 | 180 | 0.588626 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/motionverse/engine/coder/scripts/styles.py | #
# styles
#
style_btn_enabled = {
"Button": {"border_radius": 5.0,"margin": 5.0,"padding": 10.0,"background_color": 0xFFFF7E09,"border_color": 0xFFFD761D},
"Button:hovered": {"background_color": 0xFFFF4F00},
"Button:pressed": {"background_color": 0xFFFAE26F},
"Button.Label": {"color": 0xFFFFFFFF},
}
style_btn_disabled = {
"Button": {"border_radius": 3.0,"margin": 5.0,"padding": 10.0,"background_color": 0xFFC0E0C0,"border_color": 0xFFFD7F1D},
"Button:hovered": {"background_color": 0xFFC0C0C0, "background_gradient_color": 0xFFFFAE5A},
"Button:pressed": {"background_color": 0xFFC0C0C0, "background_gradient_color": 0xFFFAB26D},
"Button.Label": {"color": 0xFF808080},
}
style_status_circle_green = {"background_color": 0xFF00FF00, "border_width": 0}
style_status_circle_red = {"background_color": 0xFF0000FF, "border_width": 0}
style_btn_goto_motionverse = {"Button": {"border_width": 0.0, "border_radius": 3.0, "margin": 5.0, "padding": 10.0}} | 982 | Python | 53.611108 | 125 | 0.677189 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/motionverse/engine/coder/scripts/extension.py | import carb
import omni.ext
import omni.timeline
import omni.usd
import omni.kit.window.file
import traceback
import json
import glob
import asyncio
from email import message
from operator import le
from pxr import Vt, Gf, UsdSkel, Usd, Sdf, UsdGeom
from typing import cast, Union, List
from .constants import *
from .ui import *
from .styles import *
from .utils import *
class MotionverseExtension(omni.ext.IExt):
def __init__(self):
self._net_io_task = None
self._update_skeleton_task = None
self.target_skeleton = None
self.skel_root_path = None
self.skel_cache = UsdSkel.Cache()
def on_startup(self, ext_id):
self.import_rig_mappings_from_json_files()
self.ext_id = ext_id
stream = omni.kit.app.get_app().get_update_event_stream()
self.update_sub = stream.create_subscription_to_pop(self.update_ui, name="update frame")
self.ui_controller = UIController(self)
def connect(self):
self.disconnect("Resetting connection")
host = self.ui_controller.source_ip_field.model.as_string
port = self.ui_controller.source_port_field.model.as_int
loop = asyncio.get_event_loop()
queue = asyncio.Queue(maxsize=10, loop=loop)
if self._net_io_task:
loop.run_until_complete(asyncio.wait({self._net_io_task}, timeout=1.0))
if self._update_skeleton_task:
loop.run_until_complete(asyncio.wait({self._update_skeleton_task}, timeout=1.0))
self._net_io_task = loop.create_task(self._do_net_io(host, port, queue))
self._update_skeleton_task = loop.create_task(self._update_skeleton_loop(queue))
self._net_io_task.add_done_callback(self.on_task_complete)
self._update_skeleton_task.add_done_callback(self.on_task_complete)
def on_task_complete(self, fut=None):
if fut is self._net_io_task:
self._update_skeleton_task.cancel()
elif fut is self._update_skeleton_task:
self._net_io_task.cancel()
self.ui_controller.streaming_active = False
async def _do_net_io(self, host, port, queue):
self.ui_controller.streaming_active = True
writer = None
try:
reader, writer = await asyncio.open_connection(host, port)
writer.write(b"ov")
await self._read_client(reader, queue)
except asyncio.CancelledError:
log_info("Network streaming cancelled")
except:
carb.log_error(traceback.format_exc())
finally:
if writer is not None:
writer.close()
await writer.wait_closed()
log_info("TCP connection closed")
log_info("Net I/O task stopped")
async def _read_client(self, reader, queue):
while True:
message_data = await reader.readexactly(1660)
await queue.put(message_data)
async def _update_skeleton_loop(self, queue):
try:
while True:
message = await queue.get()
fd = FrameDetections()
fd.ParseFromString(message)
self.update_skeleton(fd)
except asyncio.CancelledError:
log_info("Skeleton update task cancelled")
except:
carb.log_error(traceback.format_exc())
def disconnect(self, reason=str()):
streaming_active = False
if self._net_io_task is not None:
self._net_io_task.cancel()
def import_rig_mappings_from_json_files(self):
self.rig_mappings = []
rig_filenames = glob.glob(get_this_files_path() + "/xform_*.json")
if rig_filenames is not None:
for filename in rig_filenames:
rig_mapfile = open(filename, "r")
if rig_mapfile is not None:
self.rig_mappings.append(json.load(rig_mapfile))
else:
log_info("error - could not load file %s" % filename)
def init_skeletons(self, skel_root_path):
self.selected_rig_index = None
self.motion_skel_anim = None
self.selected_joints = None
self.skel_root_path = skel_root_path
selected_skeleton = find_skeleton(skel_root_path)
skel_query = self.skel_cache.GetSkelQuery(selected_skeleton)
joint_tokens = skel_query.GetJointOrder()
jointPaths = [Sdf.Path(jointToken) for jointToken in joint_tokens]
all_joint_names = [jointPath.name for jointPath in jointPaths]
self.selected_rig_index = get_rig_index(all_joint_names, self.rig_mappings)
assert self.selected_rig_index is not None, "Unsupported rig"
self.target_skeleton = selected_skeleton
self.target_skel_root = UsdSkel.Root.Find(self.target_skeleton.GetPrim())
skel_root_rotate_xyz = self.rig_mappings[self.selected_rig_index]["skel_root_rotate_xyz"]
rot_x = Gf.Rotation(Gf.Vec3d(1, 0, 0), skel_root_rotate_xyz[0])
rot_y = Gf.Rotation(Gf.Vec3d(0, 1, 0), skel_root_rotate_xyz[1])
rot_z = Gf.Rotation(Gf.Vec3d(0, 0, 1), skel_root_rotate_xyz[2])
self.rest_xform_adjust = Gf.Matrix4d()
self.rest_xform_adjust.SetRotate(rot_x * rot_y * rot_z)
self.rest_xform_adjust_inverse = self.rest_xform_adjust.GetInverse()
if not skel_query.HasRestPose():
xforms = skel_query.ComputeJointLocalTransforms()
self.target_skeleton.GetRestTransformsAttr().Set(xforms)
self.skel_cache.Clear()
def update_skeleton(self, fd):
if self.selected_joints is None:
self._init_animation(fd.body_pose_names)
num_joints = len(self.rest_xforms_anim_global)
root_index = self.motion_to_anim_index["Hips"]
motion_xforms_global = Vt.Matrix4dArray(num_joints)
for i, pose in enumerate(fd.body_poses):
name = fd.body_pose_names[i]
if name in self.motion_to_anim_index:
anim_index = self.motion_to_anim_index[name]
q = pose['rotation']
t = pose['position']
rot = Gf.Rotation(Gf.Quatd(q[3], q[0], q[1], q[2]))
trans = Gf.Vec3d(t[0], t[1], t[2])
xform = Gf.Matrix4d()
xform.SetTransform(rot, trans)
motion_xforms_global[anim_index] = xform
target_pose_xforms_global = Vt.Matrix4dArray(
[
base_xform * motion_xform
for motion_xform, base_xform in zip(motion_xforms_global, self.rest_xforms_anim_global)
]
)
root_xform = self.rest_xform_adjust_inverse
target_xforms_local = UsdSkel.ComputeJointLocalTransforms(
self.anim_topology, target_pose_xforms_global, root_xform
)
anim_rotations = Vt.QuatfArray([Gf.Quatf(xform.ExtractRotationQuat()) for xform in target_xforms_local])
height_offset = 0
local_translations_attr = self.motion_skel_anim.GetTranslationsAttr()
local_translations = local_translations_attr.Get(0)
local_translations[root_index] = Gf.Vec3f(
root_xform.Transform(
Gf.Vec3d(0, 1, 0) * height_offset + motion_xforms_global[root_index].ExtractTranslation()
)
)
local_translations_attr.Set(local_translations, 0)
self.motion_skel_anim.GetRotationsAttr().Set(anim_rotations, 0)
# self.motion_skel_anim.GetBlendShapeWeightsAttr().Set(fd.faces,0)
def _init_animation(self,selected_joints):
stage = omni.usd.get_context().get_stage()
rig_mapping = self.rig_mappings[self.selected_rig_index]["joint_mappings"]
skel_query = self.skel_cache.GetSkelQuery(self.target_skeleton)
joint_tokens = skel_query.GetJointOrder()
joint_names = {Sdf.Path(token).name: token for token in joint_tokens}
joint_token_indices = {token: index for index, token in enumerate(joint_tokens)}
motion_to_token = {
value: joint_names[key] for key, value in rig_mapping.items() if value in selected_joints
}
anim_tokens = Vt.TokenArray(motion_to_token.values())
assert len(anim_tokens) > 0
anim_token_indices = {token: index for index, token in enumerate(anim_tokens)}
active_token_indices = [joint_token_indices[token] for token in anim_tokens]
self.motion_to_anim_index = {
motion_name: anim_token_indices[token] for motion_name, token in motion_to_token.items()
}
self.anim_topology = UsdSkel.Topology([Sdf.Path(token) for token in anim_tokens])
assert self.anim_topology.Validate()
anim_path = self.target_skeleton.GetPath().AppendChild("SkelRoot")
self.motion_skel_anim = UsdSkel.Animation.Define(stage, anim_path)
self.motion_skel_anim.GetJointsAttr().Set(anim_tokens)
# self.motion_skel_anim.GetBlendShapesAttr().Set(anim_tokens)
binding = UsdSkel.BindingAPI.Apply(self.target_skeleton.GetPrim())
binding.CreateAnimationSourceRel().SetTargets([self.motion_skel_anim.GetPrim().GetPath()])
root_xform = Gf.Matrix4d()
root_xform.SetIdentity()
root_xform = self.rest_xform_adjust
identity_xform = Gf.Matrix4d()
identity_xform.SetIdentity()
rest_xforms_local = self.target_skeleton.GetRestTransformsAttr().Get()
assert rest_xforms_local, "Skeleton has no restTransforms"
skel_topology = skel_query.GetTopology()
anim_start_index = active_token_indices[0]
xform_accum = Gf.Matrix4d()
xform_accum.SetIdentity()
index = skel_topology.GetParent(anim_start_index)
while index >= 0:
xform_accum = rest_xforms_local[index] * xform_accum
rest_xforms_local[index] = identity_xform
index = skel_topology.GetParent(index)
rest_xforms_local[anim_start_index] = xform_accum * rest_xforms_local[anim_start_index]
self.target_skeleton.GetRestTransformsAttr().Set(rest_xforms_local)
rest_xforms_global = UsdSkel.ConcatJointTransforms(skel_topology, rest_xforms_local, root_xform)
self.rest_xforms_anim_global = Vt.Matrix4dArray([rest_xforms_global[i] for i in active_token_indices])
base_xforms_anim_local = UsdSkel.ComputeJointLocalTransforms(
self.anim_topology, self.rest_xforms_anim_global, identity_xform
)
self.motion_skel_anim.SetTransforms(base_xforms_anim_local, 0)
self.selected_joints = set(selected_joints)
def update_ui(self, dt):
try:
self.ui_controller.update_ui()
except:
self.disconnect("Error updating UI")
raise
def on_shutdown(self):
log_info("on_shutdown")
self.ui_controller.shutdown()
self.ui_controller = None
self.disconnect("Extension is shutting down")
@property
def ready_to_stream(self):
has_skeleton_target = self.target_skeleton is not None and self.target_skeleton.GetPrim()
return has_skeleton_target
@property
def target_skeleton_path(self):
if not self.target_skeleton or not self.target_skeleton.GetPrim():
return ""
else:
return str(self.target_skeleton.GetPath())
@property
def selected_rig_name(self):
if self.selected_rig_index is not None:
return self.rig_mappings[self.selected_rig_index]["display_name"]
else:
return None | 11,565 | Python | 39.725352 | 112 | 0.626891 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/motionverse/engine/coder/scripts/utils.py | import pathlib
from typing import cast, Union, List
import carb
from pxr import Vt, Gf, UsdSkel, Usd, Sdf, UsdGeom
import omni.timeline
import omni.usd
import omni.kit.window.file
import struct
import numpy as np
def log_info(msg):
carb.log_info("{}".format(msg))
def log_warn(msg):
carb.log_warn("{}".format(msg))
def log_error(msg):
carb.log_error("{}".format(msg))
def get_rig_index(model_joint_names, rig_mappings):
candidates = [mapping["joint_mappings"].keys() for mapping in rig_mappings]
index = None
for i in range(len(candidates)):
if all([(joint in model_joint_names) for joint in candidates[i]]):
index = i
return index
def get_all_descendents(prim: Usd.Prim, result: List[Usd.Prim] = []):
if len(result) == 0:
result.append(prim)
children = prim.GetChildren()
result.extend(list(children))
for child in children:
get_all_descendents(child, result)
def find_skeleton(path):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(path)
descendants = []
get_all_descendents(prim, descendants)
skeleton = next(filter(lambda x: x.IsA(UsdSkel.Skeleton), descendants), None)
assert skeleton is not None, "Could not find skeleton"
return UsdSkel.Skeleton(skeleton)
def find_blendShapes(path):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(path)
descendants = []
get_all_descendents(prim, descendants)
blendShapePrims = list(filter(lambda x: x.IsA(UsdSkel.BlendShape), descendants))
blendShapes = [UsdSkel.BlendShape(blendShape) for blendShape in blendShapePrims]
return blendShapes
def get_this_files_path():
return pathlib.Path(__file__).parent.absolute().as_posix()
class FrameDetections():
def __init__(self):
self.body_poses = None
self.faces = None
self.body_pose_names = ("Hips","LeftUpLeg","RightUpLeg","LeftLeg","RightLeg","LeftFoot","RightFoot","Spine","Spine1","Neck","Head","LeftShoulder","RightShoulder","LeftArm",
"RightArm","LeftForeArm","RightForeArm","LeftHand","RightHand","LeftToeBase","RightToeBase","LeftHandThumb1","LeftHandThumb2","LeftHandThumb3",
"LeftHandIndex1","LeftHandIndex2","LeftHandIndex3","LeftHandMiddle1","LeftHandMiddle2","LeftHandMiddle3","LeftHandRing1","LeftHandRing2","LeftHandRing3","LeftHandPinky1",
"LeftHandPinky2","LeftHandPinky3","RightHandThumb1","RightHandThumb2","RightHandThumb3","RightHandIndex1","RightHandIndex2","RightHandIndex3","RightHandMiddle1",
"RightHandMiddle2","RightHandMiddle3","RightHandRing1","RightHandRing2","RightHandRing3","RightHandPinky1","RightHandPinky2","RightHandPinky3")
def ParseFromString(self,value):
message_list=struct.unpack("415f",value)
self.faces = message_list[:51]
body_data = np.array(message_list[51:]).reshape(-1, 7) #joints num, 4+3
self.body_poses = [{'rotation': body_data[idx][:4], 'position': body_data[idx][4:]}
for idx in range(len(self.body_pose_names))] | 3,083 | Python | 42.436619 | 180 | 0.687642 |
Motionverse/MV-omniverse-extension/exts/motionverse.engine.coder/motionverse/engine/coder/scripts/ui.py | import omni.ui as ui
import omni.kit.ui
import omni.kit.app
import omni.kit.window.filepicker
import webbrowser
from .styles import *
from .constants import *
#
# UIController class
#
class UIController:
def __init__(self, ext):
self.ext = ext
self.extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext.ext_id)
self._streaming_active = False
self._window = ui.Window(WINDOW_NAME,width=600, height=260)
self.build_ui()
def build_ui(self):
with self._window.frame:
with ui.VStack(height=0):
with ui.HStack():
#logo
logo_path = f"{self.extension_path}{LOGO_FILEPATH}"
ui.Image(logo_path, width=50,height=50,fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,alignment=ui.Alignment.CENTER)
ui.Spacer()
ui.Button(
CS_GOTO_BTN_TEXT,width=ui.Percent(10), style=style_btn_goto_motionverse,alignment=ui.Alignment.RIGHT_CENTER, clicked_fn=self.launch_motionverse_website)
with ui.HStack():
# green/red status
with ui.VStack(width=50, alignment=ui.Alignment.TOP):
self._status_circle = ui.Circle(
radius = 8,size_policy=ui.CircleSizePolicy.FIXED, style=style_status_circle_red
)
ui.Spacer()
with ui.VStack():
# CaptureStream device selection drop-down
with ui.HStack():
ui.Label(
CS_HOSTNAME_TEXT, width=ui.Percent(20), alignment=ui.Alignment.RIGHT_CENTER
)
ui.Spacer(width=CS_H_SPACING)
with ui.VStack(width=ui.Percent(50)):
ui.Spacer()
self.source_ip_field = ui.StringField(
model=ui.SimpleStringModel(DEFAULT_IP), height=0, visible=True
)
ui.Spacer()
ui.Label(
CS_PORT_TEXT, width=ui.Percent(10), alignment=ui.Alignment.RIGHT_CENTER
)
with ui.VStack(width=ui.Percent(10)):
ui.Spacer()
self.source_port_field = ui.StringField(
model=ui.SimpleStringModel(DEFAULT_PORT), height=0, visible=True
)
ui.Spacer()
# skeleton selection
with ui.HStack():
ui.Label(
SKEL_SOURCE_EDIT_TEXT, width=ui.Percent(20), alignment=ui.Alignment.RIGHT_CENTER
)
ui.Spacer(width=CS_H_SPACING)
with ui.VStack(width=ui.Percent(50)):
ui.Spacer()
self._skeleton_to_drive_stringfield = ui.StringField(
model=ui.SimpleStringModel(SKEL_INVALID_TEXT), height=0, enabled=False
)
ui.Spacer()
ui.Spacer(width=CS_H_SPACING)
self._skel_select_button = ui.Button(
SKEL_SOURCE_BTN_TEXT, width=0, clicked_fn=self.select_skeleton
)
# rig selection
with ui.HStack():
ui.Label(RIG_DROPDOWN_TEXT, width=ui.Percent(20), alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=CS_H_SPACING)
with ui.VStack(width=ui.Percent(75)):
ui.Spacer()
self._selected_rig_label = ui.Label("")
ui.Spacer()
# start/stop stream buttons
with ui.HStack():
ui.Spacer(width=ui.Percent(20))
self._start_button = ui.Button(
CS_START_BTN_TEXT,
width=0,
clicked_fn=self.start_streaming,
enabled=not self.streaming_active,
style=style_btn_disabled if self.streaming_active else style_btn_enabled,
)
ui.Spacer(width=CS_H_SPACING)
self._stop_button = ui.Button(
CS_STOP_BTN_TEXT,
width=0,
clicked_fn=self.stop_streaming,
enabled=self.streaming_active,
style=style_btn_enabled if self.streaming_active else style_btn_disabled,
)
ui.Spacer(height=5)
def shutdown(self):
self._window.frame.clear()
self._window = None
def select_skeleton(self):
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
if paths:
path = paths[0]
try:
self.ext.init_skeletons(path)
except Exception as ex:
self._skeleton_to_drive_stringfield.model.set_value(SKEL_INVALID_TEXT)
self._selected_rig_label.text = self.ext.selected_rig_name or RIG_UNSUPPORTED_TEXT
def launch_motionverse_website(self):
webbrowser.open_new_tab(CS_URL)
def update_ui(self):
if self.streaming_active:
self._start_button.enabled = False
self._start_button.set_style(style_btn_disabled)
self._stop_button.enabled = True
self._stop_button.set_style(style_btn_enabled)
else:
self._start_button.enabled = self.ext.ready_to_stream
self._start_button.set_style(
style_btn_enabled if self.ext.ready_to_stream else style_btn_disabled
)
self._stop_button.enabled = False
self._stop_button.set_style(style_btn_disabled)
if self.streaming_active:
self._status_circle.set_style(style_status_circle_green)
else:
self._status_circle.set_style(style_status_circle_red)
self._skeleton_to_drive_stringfield.model.set_value(self.ext.target_skeleton_path)
def start_streaming(self):
self.ext.connect()
def stop_streaming(self):
self.ext.disconnect("User cancelled")
@property
def streaming_active(self):
return self._streaming_active
@streaming_active.setter
def streaming_active(self, value):
self._streaming_active = value | 7,135 | Python | 40.730994 | 177 | 0.476524 |
matiascodesal/omni-camera-reticle/README.md | # Camera Reticle Omniverse Extension

The Camera Reticle extension adds a new menu button to all viewports. From this menu, users can enable and configure:
1. Composition Guidelines
2. Safe Area Guidelines
3. Letterbox

I created this to learn and test the Kit SDK. To have a clear design target, I designed the UI as a look-alike of
the similar Unreal Engine Cinematic Viewport control. Even though this was just a test, feel free to use this
extension to help compose your shots or as an example to learn from.
## Adding This Extension
To add a this extension to your Omniverse app:
1. Go into: Extension Manager -> Gear Icon -> Extension Search Path
2. Add this as a search path: `git://github.com/matiascodesal/omni-camera-reticle.git?branch=main&dir=exts` | 910 | Markdown | 46.947366 | 117 | 0.785714 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/maticodes/viewport/reticle/styles.py | from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("icons")
cl.action_safe_default = cl(1.0, 0.0, 0.0)
cl.title_safe_default = cl(1.0, 1.0, 0.0)
cl.custom_safe_default = cl(0.0, 1.0, 0.0)
cl.letterbox_default = cl(0.0, 0.0, 0.0, 0.75)
cl.comp_lines_default = cl(1.0, 1.0, 1.0, 0.6)
safe_areas_group_style = {
"Label:disabled": {
"color": cl(1.0, 1.0, 1.0, 0.2)
},
"FloatSlider:enabled": {
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl(0.75, 0.75, 0.75, 1),
"color": cl.black
},
"FloatSlider:disabled": {
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl(0.75, 0.75, 0.75, 0.2),
"color": cl(0.0, 0.0, 1.0, 0.2)
},
"CheckBox": {
"background_color": cl(0.75, 0.75, 0.75, 1),
"color": cl.black
},
"Rectangle::ActionSwatch": {
"background_color": cl.action_safe_default
},
"Rectangle::TitleSwatch": {
"background_color": cl.title_safe_default
},
"Rectangle::CustomSwatch": {
"background_color": cl.custom_safe_default
}
}
comp_group_style = {
"Button.Image::Off": {
"image_url": str(ICON_PATH / "off.png")
},
"Button.Image::Thirds": {
"image_url": str(ICON_PATH / "thirds.png")
},
"Button.Image::Quad": {
"image_url": str(ICON_PATH / "quad.png")
},
"Button.Image::Crosshair": {
"image_url": str(ICON_PATH / "crosshair.png")
},
"Button:checked": {
"background_color": cl(1.0, 1.0, 1.0, 0.2)
}
}
| 1,688 | Python | 26.688524 | 63 | 0.560427 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/maticodes/viewport/reticle/constants.py | """Constants used by the CameraReticleExtension"""
import enum
class CompositionGuidelines(enum.IntEnum):
"""Enum representing all of the composition modes."""
OFF = 0
THIRDS = 1
QUAD = 2
CROSSHAIR = 3
DEFAULT_ACTION_SAFE_PERCENTAGE = 93
DEFAULT_TITLE_SAFE_PERCENTAGE = 90
DEFAULT_CUSTOM_SAFE_PERCENTAGE = 85
DEFAULT_LETTERBOX_RATIO = 2.35
DEFAULT_COMPOSITION_MODE = CompositionGuidelines.OFF
SETTING_RESOLUTION_WIDTH = "/app/renderer/resolution/width"
SETTING_RESOLUTION_HEIGHT = "/app/renderer/resolution/height"
SETTING_RESOLUTION_FILL = "/app/runLoops/rendering_0/fillResolution"
| 609 | Python | 26.727272 | 68 | 0.760263 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/maticodes/viewport/reticle/extension.py | import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
from . import constants
from .models import ReticleModel
from .views import ReticleOverlay
class CameraReticleExtension(omni.ext.IExt):
def on_startup(self, ext_id):
carb.log_info("[maticodes.viewport.reticle] CameraReticleExtension startup")
# Reticle should ideally be used with "Fill Viewport" turned off.
settings = carb.settings.get_settings()
settings.set(constants.SETTING_RESOLUTION_FILL, False)
viewport_window = get_active_viewport_window()
if viewport_window is not None:
reticle_model = ReticleModel()
self.reticle = ReticleOverlay(reticle_model, viewport_window, ext_id)
self.reticle.build_viewport_overlay()
def on_shutdown(self):
""" Executed when the extension is disabled."""
carb.log_info("[maticodes.viewport.reticle] CameraReticleExtension shutdown")
self.reticle.destroy()
| 1,010 | Python | 33.862068 | 85 | 0.70495 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/maticodes/viewport/reticle/__init__.py | from .extension import CameraReticleExtension
| 46 | Python | 22.499989 | 45 | 0.891304 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/maticodes/viewport/reticle/models.py | """Models used by the CameraReticleExtension"""
import omni.ui as ui
from . import constants
class ReticleModel:
"""Model containing all of the data used by the ReticleOverlay and ReticleMenu
The ReticleOverlay and ReticleMenu classes need to share the same data and stay
in sync with updates from user input. This is achieve by passing the same
ReticleModel object to both classes.
"""
def __init__(self):
self.composition_mode = ui.SimpleIntModel(constants.DEFAULT_COMPOSITION_MODE)
self.action_safe_enabled = ui.SimpleBoolModel(False)
self.action_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_ACTION_SAFE_PERCENTAGE, min=0, max=100)
self.title_safe_enabled = ui.SimpleBoolModel(False)
self.title_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_TITLE_SAFE_PERCENTAGE, min=0, max=100)
self.custom_safe_enabled = ui.SimpleBoolModel(False)
self.custom_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_CUSTOM_SAFE_PERCENTAGE, min=0, max=100)
self.letterbox_enabled = ui.SimpleBoolModel(False)
self.letterbox_ratio = ui.SimpleFloatModel(constants.DEFAULT_LETTERBOX_RATIO, min=0.001)
self._register_submodel_callbacks()
self._callbacks = []
def _register_submodel_callbacks(self):
"""Register to listen to when any submodel values change."""
self.composition_mode.add_value_changed_fn(self._reticle_changed)
self.action_safe_enabled.add_value_changed_fn(self._reticle_changed)
self.action_safe_percentage.add_value_changed_fn(self._reticle_changed)
self.title_safe_enabled.add_value_changed_fn(self._reticle_changed)
self.title_safe_percentage.add_value_changed_fn(self._reticle_changed)
self.custom_safe_enabled.add_value_changed_fn(self._reticle_changed)
self.custom_safe_percentage.add_value_changed_fn(self._reticle_changed)
self.letterbox_enabled.add_value_changed_fn(self._reticle_changed)
self.letterbox_ratio.add_value_changed_fn(self._reticle_changed)
def _reticle_changed(self, model):
"""Executes all registered callbacks of this model.
Args:
model (Any): The submodel that has changed. [Unused]
"""
for callback in self._callbacks:
callback()
def add_reticle_changed_fn(self, callback):
"""Add a callback to be executed whenever any ReticleModel submodel data changes.
This is useful for rebuilding the overlay whenever any data changes.
Args:
callback (function): The function to call when the reticle model changes.
"""
self._callbacks.append(callback)
| 2,712 | Python | 44.98305 | 115 | 0.703171 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/maticodes/viewport/reticle/views.py | from functools import partial
import carb
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import scene
from . import constants
from .constants import CompositionGuidelines
from .models import ReticleModel
from . import styles
class ReticleOverlay:
"""The reticle viewport overlay.
Build the reticle graphics and ReticleMenu button on the given viewport window.
"""
_instances = []
def __init__(self, model: ReticleModel, vp_win: ui.Window, ext_id: str):
"""ReticleOverlay constructor
Args:
model (ReticleModel): The reticle model
vp_win (Window): The viewport window to build the overlay on.
ext_id (str): The extension id.
"""
self.model = model
self.vp_win = vp_win
self.ext_id = ext_id
# Rebuild the overlay whenever the viewport window changes
self.vp_win.set_height_changed_fn(self.on_window_changed)
self.vp_win.set_width_changed_fn(self.on_window_changed)
self._view_change_sub = None
try:
# VP2 resolution change sub
self._view_change_sub = self.vp_win.viewport_api.subscribe_to_view_change(self.on_window_changed)
except AttributeError:
carb.log_info("Using Viewport Legacy: Reticle will not automatically update on resolution changes.")
# Rebuild the overlay whenever the model changes
self.model.add_reticle_changed_fn(self.build_viewport_overlay)
ReticleOverlay._instances.append(self)
resolution = self.vp_win.viewport_api.get_texture_resolution()
self._aspect_ratio = resolution[0] / resolution[1]
@classmethod
def get_instances(cls):
"""Get all created instances of ReticleOverlay"""
return cls._instances
def __del__(self):
self.destroy()
def destroy(self):
self._view_change_sub = None
self.scene_view.scene.clear()
self.scene_view = None
self.reticle_menu.destroy()
self.reticle_menu = None
self.vp_win = None
def on_window_changed(self, *args):
"""Update aspect ratio and rebuild overlay when viewport window changes."""
if self.vp_win is None:
return
settings = carb.settings.get_settings()
if type(self.vp_win).__name__ == "LegacyViewportWindow":
fill = settings.get(constants.SETTING_RESOLUTION_FILL)
else:
fill = self.vp_win.viewport_api.fill_frame
if fill:
width = self.vp_win.frame.computed_width + 8
height = self.vp_win.height
else:
width, height = self.vp_win.viewport_api.resolution
self._aspect_ratio = width / height
self.build_viewport_overlay()
def get_aspect_ratio_flip_threshold(self):
"""Get magic number for aspect ratio policy.
Aspect ratio policy doesn't seem to swap exactly when window_aspect_ratio == window_texture_aspect_ratio.
This is a hack that approximates where the policy changes.
"""
return self.get_aspect_ratio() - self.get_aspect_ratio() * 0.05
def build_viewport_overlay(self, *args):
"""Build all viewport graphics and ReticleMenu button."""
if self.vp_win is not None:
with self.vp_win.get_frame(self.ext_id):
with ui.ZStack():
# Set the aspect ratio policy depending if the viewport is wider than it is taller or vice versa.
if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold():
self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL)
else:
self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL)
# Build all the scene view guidelines
with self.scene_view.scene:
if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS:
self._build_thirds()
elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD:
self._build_quad()
elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR:
self._build_crosshair()
if self.model.action_safe_enabled.as_bool:
self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0,
color=cl.action_safe_default)
if self.model.title_safe_enabled.as_bool:
self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0,
color=cl.title_safe_default)
if self.model.custom_safe_enabled.as_bool:
self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0,
color=cl.custom_safe_default)
if self.model.letterbox_enabled.as_bool:
self._build_letterbox()
# Build ReticleMenu button
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
self.reticle_menu = ReticleMenu(self.model)
def _build_thirds(self):
"""Build the scene ui graphics for the Thirds composition mode."""
aspect_ratio = self.get_aspect_ratio()
line_color = cl.comp_lines_default
inverse_ratio = 1 / aspect_ratio
if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL:
scene.Line([-0.333 * aspect_ratio, -1, 0], [-0.333 * aspect_ratio, 1, 0], color=line_color)
scene.Line([0.333 * aspect_ratio, -1, 0], [0.333 * aspect_ratio, 1, 0], color=line_color)
scene.Line([-aspect_ratio, -0.333, 0], [aspect_ratio, -0.333, 0], color=line_color)
scene.Line([-aspect_ratio, 0.333, 0], [aspect_ratio, 0.333, 0], color=line_color)
else:
scene.Line([-1, -0.333 * inverse_ratio, 0], [1, -0.333 * inverse_ratio, 0], color=line_color)
scene.Line([-1, 0.333 * inverse_ratio, 0], [1, 0.333 * inverse_ratio, 0], color=line_color)
scene.Line([-0.333, -inverse_ratio, 0], [-0.333, inverse_ratio, 0], color=line_color)
scene.Line([0.333, -inverse_ratio, 0], [0.333, inverse_ratio, 0], color=line_color)
def _build_quad(self):
"""Build the scene ui graphics for the Quad composition mode."""
aspect_ratio = self.get_aspect_ratio()
line_color = cl.comp_lines_default
inverse_ratio = 1 / aspect_ratio
if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL:
scene.Line([0, -1, 0], [0, 1, 0], color=line_color)
scene.Line([-aspect_ratio, 0, 0], [aspect_ratio, 0, 0], color=line_color)
else:
scene.Line([0, -inverse_ratio, 0], [0, inverse_ratio, 0], color=line_color)
scene.Line([-1, 0, 0], [1, 0, 0], color=line_color)
def _build_crosshair(self):
"""Build the scene ui graphics for the Crosshair composition mode."""
aspect_ratio = self.get_aspect_ratio()
line_color = cl.comp_lines_default
if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL:
scene.Line([0, 0.05 * aspect_ratio, 0], [0, 0.1 * aspect_ratio, 0], color=line_color)
scene.Line([0, -0.05 * aspect_ratio, 0], [0, -0.1 * aspect_ratio, 0], color=line_color)
scene.Line([0.05 * aspect_ratio, 0, 0], [0.1 * aspect_ratio, 0, 0], color=line_color)
scene.Line([-0.05 * aspect_ratio, 0, 0], [-0.1 * aspect_ratio, 0, 0], color=line_color)
else:
scene.Line([0, 0.05 * 1, 0], [0, 0.1 * 1, 0], color=line_color)
scene.Line([0, -0.05 * 1, 0], [0, -0.1 * 1, 0], color=line_color)
scene.Line([0.05 * 1, 0, 0], [0.1 * 1, 0, 0], color=line_color)
scene.Line([-0.05 * 1, 0, 0], [-0.1 * 1, 0, 0], color=line_color)
scene.Points([[0.00005, 0, 0]], sizes=[2], colors=[line_color])
def _build_safe_rect(self, percentage, color):
"""Build the scene ui graphics for the safe area rectangle
Args:
percentage (float): The 0-1 percentage the render target that the rectangle should fill.
color: The color to draw the rectangle wireframe with.
"""
aspect_ratio = self.get_aspect_ratio()
inverse_ratio = 1 / aspect_ratio
if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL:
scene.Rectangle(aspect_ratio*2*percentage, 1*2*percentage, thickness=1, wireframe=True, color=color)
else:
scene.Rectangle(1*2*percentage, inverse_ratio*2*percentage, thickness=1, wireframe=True, color=color)
def _build_letterbox(self):
"""Build the scene ui graphics for the letterbox."""
aspect_ratio = self.get_aspect_ratio()
letterbox_color = cl.letterbox_default
letterbox_ratio = self.model.letterbox_ratio.as_float
def build_letterbox_helper(width, height, x_offset, y_offset):
move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0)
with scene.Transform(transform=move):
scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color)
move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0)
with scene.Transform(transform=move):
scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color)
if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL:
if letterbox_ratio >= aspect_ratio:
height = 1 - aspect_ratio / letterbox_ratio
rect_height = height / 2
rect_offset = 1 - rect_height
build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset)
else:
width = aspect_ratio - letterbox_ratio
rect_width = width / 2
rect_offset = aspect_ratio - rect_width
build_letterbox_helper(rect_width, 1, rect_offset, 0)
else:
inverse_ratio = 1 / aspect_ratio
if letterbox_ratio >= aspect_ratio:
height = inverse_ratio - 1 / letterbox_ratio
rect_height = height / 2
rect_offset = inverse_ratio - rect_height
build_letterbox_helper(1, rect_height, 0, rect_offset)
else:
width = (aspect_ratio - letterbox_ratio) * inverse_ratio
rect_width = width / 2
rect_offset = 1 - rect_width
build_letterbox_helper(rect_width, inverse_ratio, rect_offset, 0)
def get_aspect_ratio(self):
"""Get the aspect ratio of the viewport.
Returns:
float: The viewport aspect ratio.
"""
return self._aspect_ratio
class ReticleMenu:
"""The popup reticle menu"""
def __init__(self, model: ReticleModel):
"""ReticleMenu constructor
Stores the model and builds the Reticle button.
Args:
model (ReticleModel): The reticle model
"""
self.model = model
self.button = ui.Button("Reticle", width=0, height=0, mouse_pressed_fn=self.show_reticle_menu,
style={"margin": 10, "padding": 5, "color": cl.white})
self.reticle_menu = None
def destroy(self):
self.button.destroy()
self.button = None
self.reticle_menu = None
def on_group_check_changed(self, safe_area_group, model):
"""Enables/disables safe area groups
When a safe area checkbox state changes, all the widgets of the respective
group should be enabled/disabled.
Args:
safe_area_group (HStack): The safe area group to enable/disable
model (SimpleBoolModel): The safe group checkbox model.
"""
safe_area_group.enabled = model.as_bool
def on_composition_mode_changed(self, guideline_type):
"""Sets the selected composition mode.
When a composition button is clicked, it should be checked on and the other
buttons should be checked off. Sets the composition mode on the ReticleModel too.
Args:
guideline_type (_type_): _description_
"""
self.model.composition_mode.set_value(guideline_type)
self.comp_off_button.checked = guideline_type == CompositionGuidelines.OFF
self.comp_thirds_button.checked = guideline_type == CompositionGuidelines.THIRDS
self.comp_quad_button.checked = guideline_type == CompositionGuidelines.QUAD
self.comp_crosshair_button.checked = guideline_type == CompositionGuidelines.CROSSHAIR
def show_reticle_menu(self, x, y, button, modifier):
"""Build and show the reticle menu popup."""
self.reticle_menu = ui.Menu("Reticle", width=400, height=200)
self.reticle_menu.clear()
with self.reticle_menu:
with ui.Frame(width=0, height=100):
with ui.HStack():
with ui.VStack():
ui.Label("Composition", alignment=ui.Alignment.LEFT, height=30)
with ui.VGrid(style=styles.comp_group_style, width=150, height=0,
column_count=2, row_height=75):
current_comp_mode = self.model.composition_mode.as_int
with ui.HStack():
off_checked = current_comp_mode == CompositionGuidelines.OFF
callback = partial(self.on_composition_mode_changed, CompositionGuidelines.OFF)
self.comp_off_button = ui.Button("Off", name="Off", checked=off_checked,
width=70, height=70, clicked_fn=callback)
with ui.HStack():
thirds_checked = current_comp_mode == CompositionGuidelines.THIRDS
callback = partial(self.on_composition_mode_changed, CompositionGuidelines.THIRDS)
self.comp_thirds_button = ui.Button("Thirds", name="Thirds", checked=thirds_checked,
width=70, height=70, clicked_fn=callback)
with ui.HStack():
quad_checked = current_comp_mode == CompositionGuidelines.QUAD
callback = partial(self.on_composition_mode_changed, CompositionGuidelines.QUAD)
self.comp_quad_button = ui.Button("Quad", name="Quad", checked=quad_checked,
width=70, height=70, clicked_fn=callback)
with ui.HStack():
crosshair_checked = current_comp_mode == CompositionGuidelines.CROSSHAIR
callback = partial(self.on_composition_mode_changed,
CompositionGuidelines.CROSSHAIR)
self.comp_crosshair_button = ui.Button("Crosshair", name="Crosshair",
checked=crosshair_checked, width=70, height=70,
clicked_fn=callback)
ui.Spacer(width=10)
with ui.VStack(style=styles.safe_areas_group_style):
ui.Label("Safe Areas", alignment=ui.Alignment.LEFT, height=30)
with ui.HStack(width=0):
ui.Spacer(width=20)
cb = ui.CheckBox(model=self.model.action_safe_enabled)
action_safe_group = ui.HStack(enabled=self.model.action_safe_enabled.as_bool)
callback = partial(self.on_group_check_changed, action_safe_group)
cb.model.add_value_changed_fn(callback)
with action_safe_group:
ui.Spacer(width=10)
ui.Label("Action Safe", alignment=ui.Alignment.TOP)
ui.Spacer(width=14)
with ui.VStack():
ui.FloatSlider(self.model.action_safe_percentage, width=100,
format="%.0f%%", min=0, max=100, step=1)
ui.Rectangle(name="ActionSwatch", height=5)
ui.Spacer()
with ui.HStack(width=0):
ui.Spacer(width=20)
cb = ui.CheckBox(model=self.model.title_safe_enabled)
title_safe_group = ui.HStack(enabled=self.model.title_safe_enabled.as_bool)
callback = partial(self.on_group_check_changed, title_safe_group)
cb.model.add_value_changed_fn(callback)
with title_safe_group:
ui.Spacer(width=10)
ui.Label("Title Safe", alignment=ui.Alignment.TOP)
ui.Spacer(width=25)
with ui.VStack():
ui.FloatSlider(self.model.title_safe_percentage, width=100,
format="%.0f%%", min=0, max=100, step=1)
ui.Rectangle(name="TitleSwatch", height=5)
ui.Spacer()
with ui.HStack(width=0):
ui.Spacer(width=20)
cb = ui.CheckBox(model=self.model.custom_safe_enabled)
custom_safe_group = ui.HStack(enabled=self.model.custom_safe_enabled.as_bool)
callback = partial(self.on_group_check_changed, custom_safe_group)
cb.model.add_value_changed_fn(callback)
with custom_safe_group:
ui.Spacer(width=10)
ui.Label("Custom Safe", alignment=ui.Alignment.TOP)
ui.Spacer(width=5)
with ui.VStack():
ui.FloatSlider(self.model.custom_safe_percentage, width=100,
format="%.0f%%", min=0, max=100, step=1)
ui.Rectangle(name="CustomSwatch", height=5)
ui.Spacer()
ui.Label("Letterbox", alignment=ui.Alignment.LEFT, height=30)
with ui.HStack(width=0):
ui.Spacer(width=20)
cb = ui.CheckBox(model=self.model.letterbox_enabled)
letterbox_group = ui.HStack(enabled=self.model.letterbox_enabled.as_bool)
callback = partial(self.on_group_check_changed, letterbox_group)
cb.model.add_value_changed_fn(callback)
with letterbox_group:
ui.Spacer(width=10)
ui.Label("Letterbox Ratio", alignment=ui.Alignment.TOP)
ui.Spacer(width=5)
ui.FloatDrag(self.model.letterbox_ratio, width=35, min=0.001, step=0.01)
self.reticle_menu.show_at(x - self.reticle_menu.width, y - self.reticle_menu.height)
| 20,348 | Python | 52.691293 | 129 | 0.543886 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/maticodes/viewport/reticle/tests/reticle_tests.py | """ Tests Module
TODO:
* Write actual tests.
"""
from pathlib import Path
from typing import Optional
import carb
import omni.kit
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from maticodes.viewport.reticle.extension import CameraReticleExtension
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../data")
class TestReticle(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self._all_widgets = []
self._settings = carb.settings.get_settings()
self._original_value = self._settings.get_as_int("/persistent/app/viewport/displayOptions")
self._settings.set_int("/persistent/app/viewport/displayOptions", 0)
# Create test area
await self.create_test_area(256, 256)
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE
self._test_window = ui.Window(
"Viewport",
dockPreference=ui.DockPreference.DISABLED,
flags=window_flags,
width=256,
height=256,
position_x=0,
position_y=0,
)
# Override default background
self._test_window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}})
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# After running each test
async def tearDown(self):
self._golden_img_dir = None
self._test_window = None
self._settings.set_int("/persistent/app/viewport/displayOptions", self._original_value)
await super().tearDown()
async def test_reticle_menu_button(self):
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_reticle_menu_button.png")
| 1,962 | Python | 32.844827 | 128 | 0.649847 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/maticodes/viewport/reticle/tests/__init__.py | from maticodes.viewport.reticle.tests.reticle_tests import TestReticle | 70 | Python | 69.99993 | 70 | 0.885714 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/config/extension.toml | [package]
version = "1.4.0"
title = "Camera Reticle"
description="Adds a camera reticle featuring composition guidelines, safe area guidelines, and letterbox."
authors=["Matias Codesal <[email protected]>"]
readme = "docs/README.md"
changelog="docs/CHANGELOG.md"
repository = ""
category = "Rendering"
keywords = ["camera", "reticle", "viewport"]
preview_image = "data/preview.png"
icon = "icons/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.ui.scene" = {}
"omni.kit.viewport.utility" = {}
# Main python module this extension provides, it will be publicly available as "import omni.hello.world".
[[python.module]]
name = "maticodes.viewport.reticle"
| 677 | TOML | 28.47826 | 106 | 0.734121 |
matiascodesal/omni-camera-reticle/exts/maticodes.viewport.reticle/docs/CHANGELOG.md | # Changelog
All notable changes to this project will be documented in this file.
## [Unreleased]
## [1.4.0] - 2022-09-09
### Added
- Fixed bad use of viewport window frame for VP Next
- Now use ViewportAPI.subscribe_to_view_change() on VP Next
## [1.3.0] - 2022-07-10
### Added
- `omni.kit.viewport.utility` dependency.
### Changed
- Refactored to use `omni.kit.viewport.utility`. (Only works with Kit 103.1.2+ now.)
- Renamed `reticle.py` to `views.py`
- Moved **Reticle** button to the bottom right of the viewport instead of bottom left.
## [1.2.0] - 2022-05-24
### Changed
- Refactored to use VP1 instead of hybrid VP1/2
- Renamed "draw" functions to "build"
- Moved color constants to omni.ui.color
## [1.1.0] - 2022-03-31
### Changed
- Improved the cleanup code when the extension is shutdown.
## [1.0.0] - 2022-03-28
### Added
- Added extension icon
- Applies overlay to all existing viewports on extension startup
- Added docstrings
- Refactored to use Model-View pattern
- Now supports when viewport is narrower than the render resolution aspect ratio.
## [0.1.0] - 2022-03-25
### Added
- Initial add of the Camera Reticle extension. | 1,150 | Markdown | 27.774999 | 86 | 0.712174 |
heavyai/omni-component/README.md | # HEAVY.AI | Omni.Ui Component System
This component system was first presented during a NVIDIA Partner Spotlight with HEAVY.AI and can be found [here on YouTube](https://youtu.be/QhBMgx2G86g?t=1640)

## Goals
1. Provide a means to encapsulate functions and `omni.ui` widgets to modularize UI code by its purpose to enforce boundaries using separation of concerns
2. Standardize the creation and implementation of UI components in a manner that enforces self-documentation and a homogenous UI codebase
3. Provide the utility of updating and re-rendering specific components without re-rendering components that have not changed
## Examples
### Hello World
```python
from heavyai.ui.component import Component
class SimpleLabel(Component):
def render(self):
ui.Label("Hello World")
# USAGE
SimpleLabel()
class CustomLabel(Component):
value: str = "Hello World"
def render(self):
ui.Label(self.value)
# USAGE
CustomLabel(value="Hello There")
```
### Internal State
```python
from heavyai.ui.component import Component
class ButtonCounter(Component):
value: int = 0
on_change: Optional[Callable[[int], None]]
def _handle_click(self):
self.value += 1
if self.on_change:
self.on_change(self.value)
self.update()
def render(self):
with self.get_root(ui.HStack):
ui.Label(str(self.value))
ui.Button("Increment", clicked_fn=self._handle_click()
# USAGE
ButtonCounter(on_change=lambda val: print(val))
```
### Subscribing Components
```python
from heavyai.ui.component import Component
class UsdSubscribingComponent(Component):
prim: pxr.Usd.Prim
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.subscription: carb.Subscription = (
usd.get_watcher().subscribe_to_change_info_path(
path=self.prim.GetPath(), on_change=self._handle_prim_change
)
)
def _handle_prim_change(self, prim_attr_path):
self.update()
def render(self):
with self.get_root(ui.VStack):
pass
def destroy(self):
self.subscription.unsubscribe()
class AbstractModelSubscribingComponent(Component):
model: sc.AbstractManipulatorModel
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.subscription: carb.Subscription = (
self.model.subscribe_item_changed_fn(
self._handle_model_item_changed
)
)
def _handle_model_item_changed(self, model, item):
self.update()
def render(self):
with self.get_root(ui.VStack):
pass
def destroy(self):
self.subscription.unsubscribe()
```
## Re-rendering “In Place”
Similar to the ability to update the `style` property of any `ui.Widget` element or the `text` property of `ui.Label` and `ui.Button` elements, `Components` can also be updated after they are created. Components can update themselves in response to subscribed events or user interactions, or components can be updated elsewhere via reference. This *drastically* increases the composability of UI elements.
### Using Setters
```python
class CustomLabel(Component):
value: str = "Hello World"
def set_value(self, value: str):
self.value = value
self.update()
def render(self):
ui.Label(self.value)
hello_world_label = CustomLabel()
hello_world_label.set_value(
"Goodbye, and see you later"
)
```
### Using a Reference
```python
hello_world_label = CustomLabel()
hello_world_label.value = "Goodbye, and see you later"
hello_world_label.update()
```
## Caveat: Destroying a Component
Components are not automatically deleted when cleared from a container (or should otherwise be destroyed), so if a `destroy()` method is provided, a reference to that component must be stored and destroyed by the component’s “parent” when appropriate, resulting in a chain of saved references and destroy calls. This is often the case when a component sets up a subscription; the subscription must be unsubscribed when the component is removed. See 'Subscribing Components' above for examples of components that require a `destroy` method.
```python
class ParentComponent(Component):
def render(self):
prim = # get prim reference
with self.get_root(ui.VStack):
self.child = UsdSubscribingComponent(prim=prim)
def destroy(self):
self.child.destroy()
```
| 4,626 | Markdown | 27.73913 | 539 | 0.689148 |
heavyai/omni-component/exts/heavyai.ui.component/heavyai/ui/component/extension.py | from __future__ import annotations
import asyncio
import contextlib
from typing import Dict, Optional, TYPE_CHECKING
import omni.kit.app
if TYPE_CHECKING:
import omni.ui as ui
class Component:
"""
The base class that UI elements should be subclassed from
Attributes
----------
name : Optional[str]
The name of the root container.
style : Optional[Dict]
The local style of the root container.
height : Optional[int]
The height of the root container.
width : Optional[int]
The width of the root container
style_type_name_override : Optional[str]
By default, we use typeName to look up the style.
But sometimes it's necessary to use a custom name.
For example, when a widget as a part of another widget.(Label is a part of Button)
This property can override the name to use in style.
"""
style: Optional[Dict] = None
height: Optional[int] = None
width: Optional[int] = None
name: Optional[str] = None
style_type_name_override: Optional[str] = None
def __init__(self, render_on_init=True, **kwargs):
"""
Parameters
----------
render_on_init : bool
If the render method should be called upon component creation
"""
# ui.Container is ui.VStack/HStack/ZStack/etc
self._root: ui.Container = None
self._debounce_task: asyncio.Future = None
props = self.get_props() # grab declared component props
for k, v in kwargs.items():
try:
assert k in props # ensure the prop has been declared
setattr(self, k, v) # set props
except AssertionError:
raise AssertionError(f"Prop '{k}' must be annotated") from None
# in rare situations you may need to choose when the component initially renders
if render_on_init:
self.render()
@classmethod
def get_props(cls):
d = {}
for c in cls.mro():
try:
d.update(**c.__annotations__)
except AttributeError:
pass
return d
@property
def visible(self):
if self._root:
return self._root.visible
return False
@visible.setter
def visible(self, new_visible):
if not self._root:
raise Exception("Component has not been rendered") from None
self._root.visible = new_visible
@property
def enabled(self):
if self._root:
return self._root.enabled
@enabled.setter
def enabled(self, value):
if self._root:
self._root.enabled = value
def get_root(self, Container: ui.Container, default_visible=True, **kwargs):
"""
Creates and returns a new container upon initial call.
Clears the container and returns reference upon subsequent calls.
This allows a component to be re-rendered without losing its positioning
"""
if self._root:
self._root.clear()
else:
if self.height is not None:
kwargs.update(height=self.height)
if self.width is not None:
kwargs.update(width=self.width)
if self.style is not None:
kwargs.update(style=self.style)
if self.name is not None:
kwargs.update(name=self.name)
if self.style_type_name_override is not None:
kwargs.update(style_type_name_override=self.style_type_name_override)
self._root = Container(**kwargs)
self._root.visible = default_visible
return self._root
async def render_async(self):
"""Waits for next frame before re-rendering"""
await omni.kit.app.get_app().next_update_async()
self.render()
def update(self, loop=asyncio.get_event_loop()):
"""Used to re-render the component"""
asyncio.ensure_future(self.render_async(), loop=loop)
def update_debounce(self, delay=0.2):
"""
Queues re-render after a delay and resets the timer on subsequent calls if timer has not completed
"""
async def run_after_delay():
await asyncio.sleep(delay)
await self.render_async()
with contextlib.suppress(Exception):
self._debounce_task.cancel()
self._debounce_task = asyncio.ensure_future(run_after_delay())
def render(self):
raise NotImplementedError()
def __del__(self):
"""
Note: `__del__` is not reliably called when parent component is destroyed or re-rendered
If a component requires clean-up (such as subscriptions, windows, frames, or event listeners),
the parent component/class must manually call destroy when appropriate.
"""
self.destroy()
def destroy(self):
"""
If a component requires clean-up (such as subscriptions, windows, frames, or event listeners),
the parent component/class must manually call destroy when appropriate.
"""
pass
| 5,135 | Python | 31.506329 | 106 | 0.601558 |
heavyai/omni-component/exts/heavyai.ui.component/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["HEAVY.AI", "Brendan Turner", "Chris Matzenbach"]
# The title and description fields are primarily for displaying extension info in UI
title = "Heavy Omni.UI Component System"
description="Component class for UI organization and encapsulation"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "./docs/README.md"
# URL of the extension source repository.
repository = "https://github.com/heavyai/omni-component"
# One of categories for UI.
category = "other"
# Keywords for the extension
keywords = ["heavyai", "component", "react"]
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "resources/partner-spotlight-slide.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "resources/logo_black.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.ui" = {}
# Main python module this extension provides, it will be publicly available as "import omni.hello.world".
[[python.module]]
name = "heavyai.ui.component"
| 1,262 | TOML | 33.135134 | 118 | 0.751189 |
syntway/model_exploder/README.md | # Model Exploder Tool

Model Exploder separates a 3D model into its component parts for a better view of their relationship and how they fit together.
Model separation happens as if by a small controlled explosion, emanating from its center. This is often known as an [exploded-view](https://en.wikipedia.org/wiki/Exploded-view_drawing) of the model.
Exploded-views can be used to understand a model from its components and can also be used to create drawings for parts catalogs or assembly/maintenance/instruction information. Or in general, just to blow-up a 3D model.
## Quick Links
* [Features](#features)
* [Installation](#installation)
* [How to Use](#how-to-use)
* [Credits](#credits)
* [Examples](#examples)
## Features
- Easy to use: select a model, click the Use button and move the Distance slider.
- Includes several ways to explode the model around a central point, axis or plane.
- Interactive editing of the explosion center: just drag the "Center" manipulator in the viewport.
- Works with meshes, USD Shapes, references/payloads. Point instances and skeletons are moved as a whole.
- Adds Undo-Redo state when applying changes.
- Works with NVIDIA's Omniverse Create, Code 2022+ or any other Kit-based apps. Compatible with multiple viewports and with the legacy viewport of older Omniverse versions.
## Installation
This tool is a plain Omniverse extension that can be installed like any other.
1. Download the latest [release](https://github.com/syntway/model_exploder/releases) or clone the [repository](https://github.com/syntway/model_exploder) into your computer.
2. In the Omniverse App (Create, Code, etc.), open the Extensions window from: Window menu > Extensions.
3. In the Extensions window, open the Settings page, by clicking the small gear button at the top of the left bar.
4. In the Settings page that appears at the right, you'll see a list of Extension Search Paths. Add the path location of the exts/ subfolder. This subfolder is inside the location to where you installed in step 1.
5. In the search field at the top left bar, next to the gear button, type model exploder - the tool should appear listed - click it.
6. Information about the Model Exploder tool will appear at the right side: check the Enabled and the Autoload checkboxes. The tool is now installed in your Omniverse app.
## How to Use
Select Model Exploder from the Window menu - the Model Exploder tool window appears:

Select models to explode: at least two parts must be selected (meshes, USD Shapes, etc).
The top button changes to "Click to use...". Click it to explode the selected parts.

Move the Distance slider and the parts are exploded from their shared center:

The Center combo box chooses the type of explosion movement: from a central point, around an axis or expanding from a plane.

Move the center point/axis/plane by dragging the Center manipulator in the viewport. Click the Recenter button to bring it back to the default middle position:

The Options section allows customization of the tool's behavior:

The available options are:
- Acceleration from Center: exploded parts accelerate based on their initial distance from Center.
This setting controls how farthest parts accelerate more than nearest ones.
- Distance Multiplier: multiply the explosion distance selected in the above slider.
For smaller or larger explosion scales.
- Initial Bounds Visibility: the visibility of the initial bounding box for the used shapes, from transparent to fully visible.
- Unselect Parts on Use: when starting to use a group of selected parts, should they be unselected for simpler visuals?
Finally, click the Apply button to add an Undo-Redo state. Or Cancel to return to the initial parts positions.
### Tips
- Click the ( i ) button for help and more information (opens this page).
- On complex models, the first interaction with the Distance slider might take a few seconds - next ones are much faster.
- If model parts do not separate and remain joined to each other:
- Make sure model is divided in parts (meshes, USD shapes, etc), as this tools works by moving those parts.
- With the Distance slider away from its leftmost position, move the Center manipulator in the viewport into the middle of the parts group.
- Separate the group of "stuck" parts before separating the rest of the model.
- The initial bounds preview and center manipulator work in the active (last used) viewport. To change viewports, close the Model Exploder window and open again after using the new viewport.
## Credits
This tool is developed by [Syntway](https://www.syntway.com), the VR/Metaverse tools division of FaronStudio.
The tool uses SVG icons from [SVG Repo](https://www.svgrepo.com/).
3D models used in examples are from: [Bastien Genbrugge](https://sketchfab.com/3d-models/spherebot-17baf2bd295f460a924e62854ced1427), [mdesigns100](https://3dexport.com/free-3dmodel-residential-building-model-296192.htm), [dap](https://3dexport.com/free-3dmodel-ym-house-185521.htm), [KatSy](https://3dsky.org/3dmodels/show/chastnyi_dom_3) and Pixar's [Kitchen Set](https://graphics.pixar.com/usd/release/dl_downloads.html).
## Examples




| 5,622 | Markdown | 50.587155 | 424 | 0.777303 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/style.py | from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from .libs.ui_utils import UiPal
THIS_FOLDER_PATH = Path(__file__).parent.absolute()
EXT_ROOT_FOLDER_PATH = THIS_FOLDER_PATH.parent.parent
ICONS_PATH = EXT_ROOT_FOLDER_PATH.joinpath("data").joinpath("icons")
# window frame cascade
WINDOW_FRAME = {
"ComboBox": {
"border_radius": 6,
"margin": 0,
},
"ComboBox:disabled": {
"color": UiPal.TEXT_DISABLED,
},
"Slider": {
"draw_mode": ui.SliderDrawMode.HANDLE,
"color": UiPal.TRANSP_NOT_0,
"border_radius": 6,
},
"Slider:disabled": {
"secondary_color": UiPal.TEXT_DISABLED,
},
"CheckBox:disabled": {
"background_color": UiPal.TEXT_DISABLED,
},
"Button.Label:disabled": {
"color": UiPal.TEXT_DISABLED,
},
"Button.Label::ever_bright": {
"color": cl.white,
},
"Button.Label::ever_bright:disabled": {
"color": cl.white,
},
"Image::info": {
"image_url": str(ICONS_PATH / "info.svg"),
"color": UiPal.TEXT,
},
"Image::info:hovered": {
"image_url": str(ICONS_PATH / "info.svg"),
"color": cl.white,
},
"Line": {
"color": UiPal.TEXT_DISABLED
},
"CollapsableFrame": {
"border_radius": 4,
},
}
| 1,358 | Python | 18.985294 | 68 | 0.552283 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/extension.py | from functools import partial
import asyncio
import omni.ext
import omni.ui as ui
import omni.kit.commands
import carb.settings
from .libs.app_utils import call_on_parts_ready, call_after_update, get_setting_or
from .window import Window
from .engine import Engine
from . import const
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
# print("ext.on_startup", ext_id)
self._window = None
self._ext_id = ext_id
def build():
ui.Workspace.set_show_window_fn(const.WINDOW_NAME, partial(self.show_window, None))
# carb.settings.get_settings().set("persistent/exts/syntway.model_exploder/windowShowOnStartup", True)
show = get_setting_or(const.SETTINGS_PATH + "windowShowOnStartup", False)
ed_menu = omni.kit.ui.get_editor_menu()
if ed_menu:
self._menu = ed_menu.add_item(const.MENU_PATH, self.show_window, toggle=True, value=show)
if show:
self.show_window(None, True) # ui.Workspace.show_window(WINDOW_NAME)
call_on_parts_ready(build, 1) # stage ready
def on_shutdown(self):
# print("ext.on_shutdown")
ui.Workspace.set_show_window_fn(const.WINDOW_NAME, None)
ed_menu = omni.kit.ui.get_editor_menu()
if ed_menu and omni.kit.ui.editor_menu.EditorMenu.has_item(const.MENU_PATH):
ed_menu.remove_item(const.MENU_PATH)
self._menu = None
if self._window:
self._window.destroy(True)
self._window = None
def show_window(self, menu, value):
# print("ext.show_window", value, self._window)
if value: # show
if self._window is None:
self._window = Window(const.WINDOW_NAME, self._ext_id)
self._window.set_visibility_changed_fn(self._visibility_changed_fn)
else:
self._window.show()
elif self._window:
self._window.visible = False # will destroy in _visibility_changed_fn
def _set_menu(self, value):
# print("ext._set_menu", value)
ed_menu = omni.kit.ui.get_editor_menu()
if ed_menu:
ed_menu.set_value(const.MENU_PATH, value)
def _visibility_changed_fn(self, visible):
# print("ext._visibility_changed_fn", visible)
self._set_menu(visible)
if not visible: # destroy window
def destroy_window():
# print("ext.destroy_window", self._window)
if self._window:
self._window.destroy(False)
self._window = None
call_after_update(destroy_window)
class ExplodeEngineApplyCommand(omni.kit.commands.Command):
"""
Undo/redoable command used by engine to apply final and initial position lists
Don't use outside this extension.
States are a tuple of (dist, change_list, time_code)
"""
def __init__(self, initial_state, final_state, stage):
super().__init__()
self._initial_state = initial_state
self._final_state = final_state
self._stage = stage
def do(self):
Engine.apply_state(self._final_state, self._stage, None)
def undo(self):
Engine.apply_state(self._initial_state, self._stage, None)
omni.kit.commands.register_all_commands_in_module(__name__)
| 3,380 | Python | 26.266129 | 114 | 0.606805 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/engine.py | import asyncio, copy
import carb
import omni.ext
import omni.ui as ui
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.kit.commands
import omni.usd
import omni.timeline
from pxr import Usd, UsdGeom, UsdSkel, Sdf, Tf
import pxr.Gf as Gf
import omni.kit.notification_manager as nm
from omni.usd.commands import TransformPrimCommand, TransformPrimSRTCommand
from .libs.usd_helper import UsdHelper
from .libs.usd_utils import (set_prim_translation, set_prim_translation_fast,
set_prim_transform, get_prim_transform,
get_prim_translation, create_edit_context)
from .libs.viewport_helper import ViewportHelper
from .libs.app_helper import AppHelper
from .libs.app_utils import get_setting_or, set_setting, call_after_update
from . import const
APPLY_ASYNC = True
class Engine():
def __init__(self):
self.meshes_base_aabb = Gf.Range3d()
self._meshes = []
self._dist = 0
self._center_mode = get_setting_or(const.SETTINGS_PATH + const.CENTER_MODE_SETTING, const.DEFAULT_CENTER_MODE)
self._dist_mult = get_setting_or(const.SETTINGS_PATH + const.DIST_MULT_SETTING, const.DEFAULT_DIST_MULT)
self._order_accel = get_setting_or(const.SETTINGS_PATH + const.ACCEL_SETTING, const.ACCEL_DEFAULT)
self._explo_center = Gf.Vec3d(0)
self._last_explo_center = Gf.Vec3d(0)
self._apply_needed = False
self._apply_task = None
self._recalc_changed_needed = set()
self._ignore_next_objects_changed = 0 # 0=no, 1=only next, 2:all until reset
self._dist_base_size = 100
self.usd = UsdHelper()
self._app = AppHelper()
self._app.add_update_event_fn(self._on_update)
stream = omni.timeline.get_timeline_interface().get_timeline_event_stream()
self._timeline_sub = stream.create_subscription_to_pop(self._on_timeline_event)
def destroy(self):
self._apply_cancel()
self._timeline_sub = None
self._recalc_changed_needed.clear()
if self.usd:
self.usd.remove_stage_objects_changed_fn(self._on_stage_objects_changed)
self.usd.detach()
self.usd = None
if self._app:
self._app.detach()
self._app = None
Engine._instance = None
def reset(self, set_to_initial):
self._apply_cancel()
if set_to_initial and self.dist > 0: # if dist is 0, nothing to do
self._apply(-2, self._explo_center, self._meshes) # returns prims to initial's
self._meshes.clear()
self._dist = 0
self.usd.remove_stage_objects_changed_fn(self._on_stage_objects_changed)
def _on_update(self, _):
if self._recalc_changed_needed:
self._recalc_changed(self._recalc_changed_needed)
self._recalc_changed_needed.clear()
if self._apply_needed:
if APPLY_ASYNC:
if not self._apply_task or self._apply_task.done():
self._apply_needed = False
dist = self._dist
explo_center = Gf.Vec3d(self._explo_center)
meshes = copy.copy(self._meshes)
self._apply_task = asyncio.ensure_future(self._async_apply(dist, explo_center, meshes))
# else still applying last
else:
self._apply_needed = False
self._apply(-1, self._explo_center, self._meshes) # returns prims to initial's
def _on_stage_objects_changed(self, notice):
if self._ignore_next_objects_changed:
if self._ignore_next_objects_changed == 1:
self._ignore_next_objects_changed = 0
return
if not self._meshes: # should never happen?
return
# set filters out duplicate path property changes
changed_paths = set(Sdf.Path.GetAbsoluteRootOrPrimPath(i) for i in notice.GetChangedInfoOnlyPaths())
# print("_on_stage_objects_changed", changed_paths)
for n in changed_paths:
ch_path = n.GetPrimPath().pathString
# avoid camera changes
if ch_path.startswith("/OmniverseKit_") or ch_path.endswith("/animationData"):
continue
for p in self._meshes:
path = p["path"]
if path.startswith(ch_path):
self._recalc_changed_needed.add(path)
def _on_timeline_event(self, e):
# print("engine:_on_timeline_event", e.type)
if self.has_meshes:
if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_CHANGED):
self._ignore_next_objects_changed = 1
AVOID_CHILDREN_PRIM_TYPES = ["Camera"] # avoid recursion on these
@staticmethod
def _traverse_add_prim(list, prim):
"""Recursively traverse the hierarchy"""
if not prim.IsValid(): # might not exist anymore
return
prim_t = prim.GetTypeName()
if prim.HasAuthoredReferences(): # refs: check if any children
ref_list = []
children = prim.GetChildren()
for c in children:
Engine._traverse_add_prim(ref_list, c)
if ref_list: # add children but not itself
list += ref_list
else: # no children, add itself
list.append(prim)
return
if prim.IsA(UsdGeom.PointInstancer) or prim.IsA(UsdSkel.Root): # instance, SkelRoot: add but don't recurse inside
list.append(prim)
return
if prim.IsA(UsdGeom.Gprim):
list.append(prim)
if not prim_t in Engine.AVOID_CHILDREN_PRIM_TYPES:
children = prim.GetChildren()
for c in children:
Engine._traverse_add_prim(list, c)
def _sel_get_prim_paths_parent_first_order(self, paths):
stage = self.usd.stage
prims = []
for path in paths:
prim = stage.GetPrimAtPath(path)
prims.append(prim)
u_prims = []
for p in prims:
Engine._traverse_add_prim(u_prims, p)
return u_prims
def sel_capture(self, paths=None):
# print("sel_capture")
if paths is None:
paths = self.usd.get_selected_prim_paths()
# print("_sel_capture", paths)
u_prims = self._sel_get_prim_paths_parent_first_order(paths)
self._meshes = []
self._dist = 0
if len(u_prims) < 2:
return False
time_code = self.usd.timecode
xform_cache = UsdGeom.XformCache(time_code)
bbox_cache = UsdGeom.BBoxCache(time_code, [UsdGeom.Tokens.default_])
self._explo_center = Gf.Vec3d(0) # average of prim centroids
aa_bounds = Gf.Range3d()
# world positions
for prim in u_prims:
path = prim.GetPath().pathString
lbb = bbox_cache.ComputeLocalBound(prim)
lcent = lbb.ComputeCentroid()
ltrans = get_prim_translation(prim, time_code)
ldelta = ltrans - lcent # translation from centroid to the placing pos
wbb = bbox_cache.ComputeWorldBound(prim)
wbb_aa = wbb.ComputeAlignedRange()
aa_bounds.UnionWith(wbb_aa)
wtrans = wbb.ComputeCentroid()
lmat = get_prim_transform(prim, False, xform_cache, time_code)
# print(path, "local", lbb, lcent, ltrans, "world", wbb, wbb_aa, wtrans, lmat)
# prim, prim_path, untransformed/local mid, world_mid, initial_local_translation
entry = {"prim": prim, "path": path, "ini_wtrans": wtrans, "ldelta": ldelta, "ini_lmat": lmat}
self._meshes.append(entry)
# print(entry)
self._explo_center += wtrans
# centroid and base AA bounds
self._explo_center /= len(u_prims)
self._last_explo_center = self._explo_center
self.meshes_base_aabb = aa_bounds
# _dist_base_size size scale
size = aa_bounds.GetSize()
self._dist_base_size = max(size[0], size[1], size[2]) * 0.5
self._calc_dist_order()
# print(time_code, self._explo_center, self._dist_base_size)
self._ignore_next_objects_changed = 0
self.usd.add_stage_objects_changed_fn(self._on_stage_objects_changed)
# print("sel_capture end")
return True
def _recalc_changed(self, ch_paths):
time_code = self.usd.timecode
bbox_cache = UsdGeom.BBoxCache(time_code, [UsdGeom.Tokens.default_])
dist = self._dist
dist = self._calc_dist(dist)
for p in self._meshes:
path = p["path"]
if path in ch_paths: # only if changed
prim = p["prim"]
lbb = bbox_cache.ComputeLocalBound(prim)
lcent = lbb.ComputeCentroid()
ltrans = get_prim_translation(prim, time_code)
ldelta = ltrans - lcent
wbb = bbox_cache.ComputeWorldBound(prim)
new_wtrans = wbb.ComputeCentroid()
# calc dir
w_dir = new_wtrans - self._explo_center
w_dir = self._calc_normalized_dir(w_dir)
new_ini_wtrans = new_wtrans - w_dir * dist
p["ini_wtrans"] = new_ini_wtrans
p["ldelta"] = ldelta
# print("changed", path, new_wtrans, ldelta)
# not needed and conflicts with translate manipulator's dragging: self.apply_asap()
self._calc_dist_order()
def apply_asap(self):
self._apply_needed = True
def _apply_cancel(self):
if APPLY_ASYNC:
if self._apply_task:
if self._apply_task.done():
return
self._apply_task.cancel()
async def _async_apply(self, dist_value, explo_center, meshes):
self._apply(dist_value, explo_center, meshes)
self._apply_task = None
def _apply(self, dist, explo_center, meshes):
"""dist: -2: reset to stored initial pos, -1: use current self._dist, >=0: 0..1"""
if not meshes:
return
# print("_apply", dist)
time_code = self.usd.timecode
changes = self._prepare_apply_state(dist, explo_center, meshes, time_code, True)
is_reset = dist == -2
state = (is_reset, changes, time_code)
Engine.apply_state(state, self.usd.stage, self)
# print("_apply end")
def _prepare_apply_state(self, dist, explo_center, meshes, time_code, with_prims):
"""dist: -2: reset to stored initial pos, -1: use current self._dist, >=0: 0..1"""
if dist == -1:
dist = self._dist
# dist can now be [0..1] or -2 for reset to initial
if dist >= 0:
dist_factor = self._calc_dist(dist)
else:
dist_factor = dist
time_code = self.usd.timecode
xform_cache = UsdGeom.XformCache(time_code)
changes = []
for mp in meshes:
prim = mp["prim"]
if not prim.IsValid(): # avoid any invalidated prims, deleted for example
# print("skipping", prim)
continue
path = mp["path"]
ini_wtrans = mp["ini_wtrans"]
ldelta = mp["ldelta"]
prim = mp["prim"]
dist_order = mp["dist_order"]
if dist_factor >= 0:
# calc world pos
# calc dir
w_ini_vec = ini_wtrans - explo_center
w_ini_len = w_ini_vec.GetLength()
w_ini_len = max(w_ini_len, 1e-5)
w_dir = self._calc_normalized_dir(w_ini_vec)
order_factor = 1.0 + dist_order * self._order_accel
w_vec = w_dir * dist_factor * order_factor
dest_w_trans = ini_wtrans + w_vec
# get local->parent->world transforms
p2w = xform_cache.GetParentToWorldTransform(prim)
# transform back from world to local coords
w2p = p2w.GetInverse()
dest_ptrans = w2p.Transform(dest_w_trans)
# calc delta in mesh local/untransformed space
dest_ltrans = dest_ptrans + ldelta
# local trans, in parent space coords
ltrans = (dest_ltrans[0], dest_ltrans[1], dest_ltrans[2])
#print(prim, dest_w_trans, ltrans)
else:
ltrans = mp["ini_lmat"]
if with_prims:
changes.append((prim, path, ltrans))
else:
changes.append((None, path, ltrans))
return changes
@staticmethod
def apply_state(state, stage, instance):
# print("apply_state", state, instance)
is_reset, changes, time_code = state
if instance:
instance._ignore_next_objects_changed = 2
if not is_reset:
""" Slower alternative:
for ch in changes:
prim, path, ltrans = ch
# print(path,ltrans, type(ltrans))
cmd = TransformPrimSRTCommand(path=path,
new_translation=ltrans,
time_code=time_code)
cmd.do()
"""
stage = stage
sdf_change_block = 2
with Sdf.ChangeBlock():
for ch in changes:
prim, path, lmat = ch
if prim is None:
prim = stage.GetPrimAtPath(path)
# print(prim, ltrans)
with create_edit_context(path, stage):
set_prim_translation(prim, lmat, sdf_change_block=sdf_change_block, time_code=time_code)
#set_prim_translation_fast(prim, lmat, sdf_change_block=sdf_change_block, time_code=time_code)
else:
for ch in changes:
prim, path, ltrans = ch
# print(path,ltrans, type(ltrans))
cmd = TransformPrimCommand(path=path,
new_transform_matrix=ltrans,
time_code=time_code)
cmd.do()
if instance:
instance._ignore_next_objects_changed = 0
# print("apply_state end")
def commit(self):
time_code = self.usd.timecode
dist = -2
changes = self._prepare_apply_state(dist, self._explo_center, self._meshes, time_code, False)
is_reset = dist == -2
initial_state = (is_reset, changes, time_code)
dist = -1
changes = self._prepare_apply_state(dist, self._explo_center, self._meshes, time_code, False)
is_reset = dist == -2
final_state = (is_reset, changes, time_code)
self._ignore_next_objects_changed = 2
stage = self.usd.stage
omni.kit.commands.execute("ExplodeEngineApplyCommand",
initial_state=initial_state,
final_state=final_state,
stage=stage)
self._ignore_next_objects_changed = 0
self.reset(False)
"""
# compile transform list for undo
time_code = self.usd.timecode
xform_cache = UsdGeom.XformCache(time_code)
self._ignore_next_objects_changed = 2
xforms=[]
for mp in self._meshes:
p = mp["prim"]
path = mp["path"]
ini_mat = mp["ini_lmat"]
new_mat = get_prim_transform(p, False, xform_cache, time_code)
xforms.append((path, new_mat, ini_mat, time_code, False))
self.reset(False)
if xforms:
if True:
omni.kit.undo.begin_group()
for x in xforms:
omni.kit.commands.execute("TransformPrim",
path=x[0],
new_transform_matrix=x[1],
old_transform_matrix=x[2]
)
omni.kit.undo.end_group()
else:
omni.kit.commands.execute(
"TransformPrims", prims_to_transform=xforms
)
self._ignore_next_objects_changed = 0
"""
def _calc_dist(self, dist):
dist = dist ** const.DIST_EXP
dist = dist * self._dist_base_size * self._dist_mult
return dist
def _calc_dir(self, dir):
if self._center_mode >= 1 and self._center_mode <= 3: # around axis: zero axis displacement
dir[self._center_mode - 1] = 0.
elif self._center_mode >= 4: # from a plane
i = self._center_mode - 4
dir[i] = 0.
dir[(i + 1) % 3] = 0.
def _calc_normalized_dir(self, dir):
self._calc_dir(dir)
if dir.GetLength() > 1e-6:
dir.Normalize()
return dir
def _calc_dist_order(self):
"""dist_order is the 0..1 position of the mesh with regard to _explo_center"""
min_len = float("inf")
max_len = -1
len_list = []
for mp in self._meshes:
vec = mp["ini_wtrans"] - self._explo_center
self._calc_dir(vec)
len = vec.GetLength()
len = max(len, 1e-5)
len_list.append(len)
min_len = min(len, min_len)
max_len = max(len, max_len)
max_min_range = max_len - min_len
max_min_range = max(max_min_range, 1e-5)
index = 0
for mp in self._meshes:
order = (len_list[index] - min_len) / max_min_range
mp["dist_order"] = order
index+=1
@property
def has_meshes(self):
return self.meshes_count >= 2
@property
def meshes_count(self):
return len(self._meshes)
@property
def stage_selection_meshes_count(self):
paths = self.usd.get_selected_prim_paths()
u_prims = self._sel_get_prim_paths_parent_first_order(paths)
return len(u_prims)
@property
def center(self):
return self._explo_center
@center.setter
def center(self, center):
self._explo_center = center
self._calc_dist_order()
self.apply_asap()
@property
def dist(self):
return self._dist
@dist.setter
def dist(self, d):
self._dist = d
self.apply_asap()
@property
def center_mode(self):
return self._center_mode
@center_mode.setter
def center_mode(self, c):
self._center_mode = c
set_setting(const.SETTINGS_PATH + const.CENTER_MODE_SETTING, self._center_mode)
self.apply_asap()
@property
def order_accel(self):
return self._order_accel
@order_accel.setter
def order_accel(self, v):
self._order_accel = v
set_setting(const.SETTINGS_PATH + const.ACCEL_SETTING, self._order_accel)
self.apply_asap()
@property
def dist_mult(self):
return self._dist_mult
@dist_mult.setter
def dist_mult(self, m):
self._dist_mult = m
set_setting(const.SETTINGS_PATH + const.DIST_MULT_SETTING, self._dist_mult)
self.apply_asap()
def recenter(self):
self._explo_center = self._last_explo_center
self.apply_asap()
def is_centered(self):
return Gf.IsClose(self._explo_center, self._last_explo_center, 1e-6)
| 19,891 | Python | 26.437241 | 126 | 0.539641 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/const.py | from omni.ui import color as cl
DEV_MODE = 0
# extension/window
WINDOW_NAME = "Model Exploder"
MENU_PATH = f"Window/{WINDOW_NAME}"
SETTINGS_PATH = "persistent/exts/syntway.model_exploder/"
INFO_URL = "https://www.syntway.com/model_exploder/?info#how-to-use"
# ui
DISTANCE_LABEL = "Distance"
CENTER_LABEL = "Center"
SELECT_TO_EXPLODE_TEXT = "Start by selecting what to explode..."
SELECT_TO_USE_TEXT = "Click to use the {0} selected parts"
SELECTED_TEXT = "Exploding {0} parts"
DONE_TEXT = "Apply"
RESET_TEXT = "Cancel"
CENTER_TEXT = "Center"
RECENTER_TEXT = "Recenter"
OPTIONS_TITLE = "Options"
OPTIONS_DIST_MULT_LABEL = "Distance Multiplier"
OPTIONS_DIST_MULT_COMBO_VALUES = [
("1x", 1.),
("5x ", 5.),
("10x", 10.),
("100x", 100.)
]
OPTIONS_ACCEL_LABEL = "Acceleration from Center"
OPTIONS_ACCEL_MAX = 5.
OPTIONS_BOUNDS_ALPHA_LABEL = "Initial Bounds Visibility"
OPTIONS_BOUNDS_ALPHA_SETTING = "boundsAlpha"
OPTIONS_BOUNDS_ALPHA_DEFAULT = 0.5
OPTIONS_UNSELECT_ON_USE_LABEL = "Unselect Parts on Use"
OPTIONS_UNSELECT_ON_USE_SETTING = "unselectOnUse"
OPTIONS_UNSELECT_ON_USE_DEFAULT = True
TIMELINE_RESET_TEXT = "Timeline has changed: resetting exploded meshes..."
CENTER_COMBO_LABELS = [
"Point",
"X Axis",
"Y Axis", # up
"Z Axis", # up
"XY Plane", # ground
"YZ Plane",
"ZX Plane" # ground
]
CENTER_COMBO_AXIS_FIRST = 1
CENTER_COMBO_AXIS_SUFFIX = " (Vertical)"
CENTER_COMBO_PLANE_FIRST = 4
CENTER_COMBO_PLANE_SUFFIX = " (Ground)"
# engine
CENTER_MANIP_LABEL_OFFSET = -11
CENTER_MANIP_LABEL_SIZE = 15
DEFAULT_CENTER_MODE = 0
CENTER_MODE_SETTING = "centerMode"
DEFAULT_DIST_MULT = 5.
DIST_MULT_SETTING = "distMult"
ACCEL_DEFAULT = 1.68
ACCEL_SETTING = "orderAccel"
DIST_EXP = 1.3
BOUNDS_BASE_AABB_COLOR = cl("#808080ff") # rgba order
# tooltips
TOOLTIP_USE = "First select the models to explode, then click this button to use."
TOOLTIP_INFO = "Help and more info on this tool."
TOOLTIP_DIST = "Select the explosion distance. For larger distances, see Options - Distance Multiplier."
TOOLTIP_CENTER_MODE = """Select the explosion center type, which can be a point, an axis or a plane.
You can drag the Center manipulator directly in the viewport to change its position."""
TOOLTIP_RECENTER = "Toggle the Center manipulator in the viewport back to the centroid of the used shapes."
TOOLTIP_OPTIONS_ACCEL = """Exploded parts accelerate based on their initial distance from Center.
This setting controls how farthest parts accelerate more than nearest ones."""
TOOLTIP_OPTIONS_DIST = """Multiply the explosion distance selected in the above slider.
For smaller or larger explosion scales."""
TOOLTIP_OPTIONS_BOUNDS = """Visibility of the initial bounding box for the used shapes,
from transparent to fully visible."""
TOOLTIP_OPTIONS_UNSELECT = """When starting to use a group of selected parts,
should they be unselected for simpler visuals?"""
TOOLTIP_CANCEL = "Cancel the tool and leave parts in their initial positions."
TOOLTIP_APPLY = "Applies the current parts positions and adds an Undo-Redo state." | 3,079 | Python | 28.333333 | 107 | 0.725885 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/window.py | import asyncio, copy, webbrowser
import carb
import omni.ui as ui
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.kit.commands
import omni.usd
import omni.timeline
from pxr import Usd, UsdGeom, UsdSkel, Sdf, Tf
import pxr.Gf as Gf
import omni.kit.notification_manager as nm
from .libs.viewport_helper import ViewportHelper
from .libs.app_utils import get_setting_or, set_setting, call_after_update
from .libs.ui_utils import create_reset_button, create_tooltip_fn, UiPal, UiPal_refresh
from .libs.manipulators import TranslateManipulator
from .engine import Engine
from . import const
from . import style
class Window(ui.Window):
def __init__(self, title: str, ext_id: str, **kwargs):
# print("win.__init__")
self._ext_id = ext_id
self._engine = Engine()
self._scene_reg = None
self._center_manip = None
self._center_label = None
self._center_label_transform = None
self._base_aabb_lines = []
self._options_bounds_alpha = get_setting_or(const.SETTINGS_PATH + const.OPTIONS_BOUNDS_ALPHA_SETTING,
const.OPTIONS_BOUNDS_ALPHA_DEFAULT)
self._options_unselect_on_use = get_setting_or(const.SETTINGS_PATH + const.OPTIONS_UNSELECT_ON_USE_SETTING,
const.OPTIONS_UNSELECT_ON_USE_DEFAULT)
kwargs["auto_resize"] = True
super().__init__(title, **kwargs)
self.auto_resize = True
self._ui_built = False
self.frame.set_build_fn(self._build_fn)
self._vp = ViewportHelper()
# print(self._vp.info())
# create manipulator scene
self._scene_reg = self._vp.register_scene_proxy(self._scene_create, self._scene_destroy,
self._scene_get_visible, self._scene_set_visible,
self._ext_id)
self._engine.usd.add_stage_event_fn(self._on_stage_event)
def destroy(self, is_ext_shutdown):
# print("win.destroy", is_ext_shutdown)
self._dist_slider = None
self._use_button = None
self._center_mode_combo = None
self._recenter_button = None
self._options = None
self._options_dist_mult_combo = None
self._options_accel_slider = None
self._options_bounds_slider = None
self._options_unselect_on_use_check = None
self._done_button = None
self._reset_button = None
if self._center_manip:
self._center_manip.destroy()
self._center_manip = None
self._center_label = None
self._center_label_transform = None
self._base_aabb_lines.clear()
if self._scene_reg:
self._vp.unregister_scene(self._scene_reg)
self._scene_reg = None
if self._vp:
self._vp.detach()
self._vp = None
if self._engine:
if self._engine.usd:
self._engine.usd.remove_stage_event_fn(self._on_stage_event)
if not is_ext_shutdown and self._engine.has_meshes and self._engine.dist != 0:
self._engine.reset(True) # cancel current to intial positions
self._engine.destroy()
self._engine = None
super().destroy()
def _build_fn(self):
"""Called to build the UI once the window is visible"""
# print(f"win._build_fn {self.visible}")
UiPal_refresh()
self.frame.style = style.WINDOW_FRAME
with ui.VStack(width=386, style={"margin": 7}): # spacing=9, style={"margin": 7}
with ui.VStack(height=0, spacing=11, style={"margin": 0}): # spacing=9, style={"margin": 7}
with ui.HStack(skip_draw_when_clipped=True, spacing=5):
self._use_button = ui.Button(const.SELECT_TO_EXPLODE_TEXT,
name="ever_bright",
height=24,
clicked_fn=self._on_use_clicked,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_USE))
ui.Image(name="info",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=18, height=24,
mouse_pressed_fn=lambda *p: self._on_info(),
tooltip_fn=create_tooltip_fn(const.TOOLTIP_INFO))
with ui.HStack(skip_draw_when_clipped=True, spacing=6):
ui.Label(const.DISTANCE_LABEL, width=50,
mouse_pressed_fn=lambda *p: self._on_dist_set_zero(),
tooltip_fn=create_tooltip_fn(const.TOOLTIP_DIST))
self._dist_slider = ui.FloatSlider(min=0, max=1,
# tooltip_fn=create_tooltip_fn(const.TOOLTIP_DIST)
)
self._dist_slider.model.add_value_changed_fn(self._on_dist_slider_changed)
with ui.HStack(skip_draw_when_clipped=True, spacing=6):
ui.Label(const.CENTER_LABEL, width=50,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_CENTER_MODE))
self._center_mode_combo = ui.ComboBox(self._engine.center_mode,
*const.CENTER_COMBO_LABELS,
width=145,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_CENTER_MODE))
self._center_mode_combo.model.add_item_changed_fn(self._on_center_mode_changed)
self._setup_center_combo_labels()
self._recenter_button = ui.Button(const.RECENTER_TEXT, width=60,
clicked_fn=self._on_recenter_clicked,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_RECENTER))
ui.Spacer(height=1)
self._options = ui.CollapsableFrame(const.OPTIONS_TITLE,
collapsed=not bool(const.DEV_MODE))
with self._options:
with ui.VStack(spacing=0, style={"margin": 3}):
with ui.HStack(spacing=6):
ui.Label(const.OPTIONS_ACCEL_LABEL,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_OPTIONS_ACCEL))
with ui.HStack():
self._options_accel_slider = ui.FloatSlider(min=0, max=const.OPTIONS_ACCEL_MAX)
self._options_accel_slider.model.set_value(self._engine._order_accel)
self._options_accel_slider.model.add_value_changed_fn(self._on_options_accel_changed)
create_reset_button(const.ACCEL_DEFAULT,
self._options_accel_slider.model,
self._options_accel_slider.model.set_value,
self._options_accel_slider.model.add_value_changed_fn)
with ui.HStack(spacing=6):
ui.Label(const.OPTIONS_DIST_MULT_LABEL,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_OPTIONS_DIST))
with ui.HStack():
# locate dist_mult label index from self._engine.dist_mult
def get_dist_mult_index(dist_mult):
index = 0
for i in range(len(const.OPTIONS_DIST_MULT_COMBO_VALUES)):
entry = const.OPTIONS_DIST_MULT_COMBO_VALUES[i]
if dist_mult == entry[1]:
index = i
break
return index
self._options_dist_mult_combo = ui.ComboBox(
get_dist_mult_index(self._engine.dist_mult),
*[a[0] for a in const.OPTIONS_DIST_MULT_COMBO_VALUES],
tooltip_fn=create_tooltip_fn(const.TOOLTIP_OPTIONS_DIST)
)
self._options_dist_mult_combo.model.add_item_changed_fn(self._on_options_dist_mult_changed)
create_reset_button(get_dist_mult_index(const.DEFAULT_DIST_MULT),
self._options_dist_mult_combo.model.get_item_value_model(),
self._options_dist_mult_combo.model.get_item_value_model().set_value,
self._options_dist_mult_combo.model.add_item_changed_fn)
with ui.HStack(spacing=6):
ui.Label(const.OPTIONS_BOUNDS_ALPHA_LABEL,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_OPTIONS_BOUNDS))
with ui.HStack():
self._options_bounds_slider = ui.FloatSlider(min=0, max=1,
#tooltip_fn=create_tooltip_fn(const.TOOLTIP_OPTIONS_BOUNDS)
)
self._options_bounds_slider.model.set_value(self._options_bounds_alpha)
self._options_bounds_slider.model.add_value_changed_fn(self._on_options_bounds_changed)
create_reset_button(const.OPTIONS_BOUNDS_ALPHA_DEFAULT,
self._options_bounds_slider.model,
self._options_bounds_slider.model.set_value,
self._options_bounds_slider.model.add_value_changed_fn)
with ui.HStack(spacing=6):
ui.Label(const.OPTIONS_UNSELECT_ON_USE_LABEL,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_OPTIONS_UNSELECT))
with ui.HStack():
self._options_unselect_on_use_check = ui.CheckBox(width=12,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_OPTIONS_UNSELECT))
self._options_unselect_on_use_check.model.set_value(self._options_unselect_on_use)
self._options_unselect_on_use_check.model.add_value_changed_fn(self._on_options_unselect_changed)
# ui.Spacer(width=1)
ui.Line()
create_reset_button(const.OPTIONS_UNSELECT_ON_USE_DEFAULT,
self._options_unselect_on_use_check.model,
self._options_unselect_on_use_check.model.set_value,
self._options_unselect_on_use_check.model.add_value_changed_fn)
ui.Spacer(height=1)
with ui.HStack(skip_draw_when_clipped=True, spacing=9):
self._reset_button = ui.Button(const.RESET_TEXT, clicked_fn=self._on_reset_clicked,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_CANCEL))
ui.Spacer()
self._done_button = ui.Button(const.DONE_TEXT, clicked_fn=self._on_done_clicked,
tooltip_fn=create_tooltip_fn(const.TOOLTIP_APPLY))
#ui.Button("Test", clicked_fn=self._on_test)
self._ui_built = True
self._refresh_ui()
def _on_stage_event(self, ev: carb.events.IEvent):
# print("Window._on_stage_event", ev.type)
if not self._ui_built: # a stage event can call us before _build_fn()
return
if ev.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
if not self._engine.has_meshes:
self._refresh_ui()
elif ev.type == int(omni.usd.StageEventType.CLOSING):
# print("Window.CLOSING")
self._reset(False) # calls engine.reset
#self._engine.usd.detach()
elif ev.type == int(omni.usd.StageEventType.OPENED):
# print("Window.OPENED")
self._setup_center_combo_labels()
def _refresh_ui(self):
if not self._engine.has_meshes: # nothing selected
self._dist_slider.enabled = False
self._center_mode_combo.enabled = False
self._recenter_button.enabled = False
self._done_button.enabled = False
self._reset_button.enabled = False
sel_mesh_count = self._engine.stage_selection_meshes_count
if sel_mesh_count >= 2:
self._use_button.text = const.SELECT_TO_USE_TEXT.format(sel_mesh_count)
self._use_button.enabled = True
else:
self._use_button.text = const.SELECT_TO_EXPLODE_TEXT
self._use_button.enabled = False
else:
mesh_count = self._engine.meshes_count
self._use_button.text = const.SELECTED_TEXT.format(mesh_count)
self._use_button.enabled = False
self._dist_slider.enabled = True
self._center_mode_combo.enabled = True
self._recenter_button.enabled = not self._engine.is_centered()
self._done_button.enabled = True
self._reset_button.enabled = True
def _setup_center_combo_labels(self):
model = self._center_mode_combo.model
ch = model.get_item_children()
up = self._engine.usd.stage_up_index
if up == 1: # y up
mark = [const.CENTER_COMBO_AXIS_FIRST + 1, const.CENTER_COMBO_PLANE_FIRST + 2]
else: # z up
mark = [const.CENTER_COMBO_AXIS_FIRST + 2, const.CENTER_COMBO_PLANE_FIRST + 0]
for l in range(len(const.CENTER_COMBO_LABELS)):
label = const.CENTER_COMBO_LABELS[l]
if l in mark:
if l < const.CENTER_COMBO_PLANE_FIRST:
label += const.CENTER_COMBO_AXIS_SUFFIX
else:
label += const.CENTER_COMBO_PLANE_SUFFIX
m = model.get_item_value_model(ch[l])
m.set_value(label)
def _reset(self, set_to_initial):
self._engine.reset(set_to_initial)
self._enable_center_controls(False)
self._enable_base_aabb(False)
self._dist_slider.model.set_value(0)
self._refresh_ui()
def _on_use_clicked(self):
if not self._engine.sel_capture():
self._reset(False)
return
self._sync_base_aabb()
self._enable_base_aabb(True)
self._enable_center_controls(True)
if self._center_manip:
self._set_center_manip_point(self._engine.center)
if self._options_unselect_on_use:
self._engine.usd.set_selected_prim_paths([])
self._refresh_ui()
def _on_dist_set_zero(self):
self._dist_slider.model.set_value(0)
def _on_dist_slider_changed(self, model):
self._engine.dist = model.as_float
def _on_center_mode_changed(self, m, *args):
self._engine.center_mode = m.get_item_value_model().get_value_as_int()
def _on_recenter_clicked(self):
self._engine.recenter()
self._set_center_manip_point(self._engine.center)
self._recenter_button.enabled = not self._engine.is_centered()
def _on_done_clicked(self):
self._engine.commit()
self._reset(False)
def _on_reset_clicked(self):
self._reset(True)
def _scene_create(self, vp_args):
vp_api = vp_args["viewport_api"]
if not self._vp.same_api(vp_api): # ensure scene is created in same viewport we're attached to
return
# print("_scene_create", vp_args, self._vp._api)
self._center_manip = TranslateManipulator(viewport=self._vp,
enabled=False,
changed_fn=self._on_center_manip_changed
)
self._center_label_transform = sc.Transform() # before next _sync
self._sync_scene_label()
with self._center_label_transform:
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA, scale_to=sc.Space.SCREEN):
with sc.Transform(transform=sc.Matrix44.get_scale_matrix(2, 2, 1)):
wup = self._engine.usd.stage_up
wup *= const.CENTER_MANIP_LABEL_OFFSET
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*wup)):
self._center_label = sc.Label(const.CENTER_TEXT, alignment=ui.Alignment.CENTER,
size=const.CENTER_MANIP_LABEL_SIZE, visible=False)
self._create_base_aabb()
def _scene_destroy(self):
if self._center_manip:
self._center_manip.destroy()
self._center_manip = None
def _scene_get_visible(self):
return True
def _scene_set_visible(self, value):
if self._center_manip.enabled: # only set if manip is enabled
self._center_manip.enabled = value
def _on_center_manip_changed(self, action, manip):
# print("_on_center_manip_changed")
assert self._engine.has_meshes
self._sync_scene_label()
self._engine.center = manip.point
self._recenter_button.enabled = not self._engine.is_centered()
def _enable_center_controls(self, ena):
if self._center_manip:
self._center_manip.enabled = ena
if self._center_label:
self._center_label.visible = ena
def _set_center_manip_point(self, wpt):
self._center_manip.point = wpt
self._sync_scene_label()
def _sync_scene_label(self):
wpt = Gf.Vec3d(self._center_manip.point)
self._center_label_transform.transform = sc.Matrix44.get_translation_matrix(*wpt)
def prepare_base_aabb_color(self):
color = const.BOUNDS_BASE_AABB_COLOR
color = (color & 0x00ffffff) | (int(self._options_bounds_alpha * 255) << 24)
return color
def _create_base_aabb(self):
self._base_aabb_lines.clear()
color = self.prepare_base_aabb_color()
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
self._base_aabb_lines.append(sc.Line([0, 0, 0], [0, 0, 0], color=color, visible=False))
def _sync_base_aabb(self):
"""
points p#
4 5
6 7
0 1
2 3
lines
8| |9
10| |11
_4_
5/ /6
-7-
_0_
1/ /2
-3-
"""
if self._engine.meshes_base_aabb.IsEmpty():
return
mi, ma = self._engine.meshes_base_aabb.min, self._engine.meshes_base_aabb.max
p0=[mi[0],mi[1],mi[2]]
p1=[ma[0],mi[1],mi[2]]
p2=[mi[0],mi[1],ma[2]]
p3=[ma[0],mi[1],ma[2]]
p4=[mi[0],ma[1],mi[2]]
p5=[ma[0],ma[1],mi[2]]
p6=[mi[0],ma[1],ma[2]]
p7=[ma[0],ma[1],ma[2]]
self._base_aabb_lines[0].start,self._base_aabb_lines[0].end, = p0,p1
self._base_aabb_lines[1].start,self._base_aabb_lines[1].end, = p0,p2
self._base_aabb_lines[2].start,self._base_aabb_lines[2].end, = p1,p3
self._base_aabb_lines[3].start,self._base_aabb_lines[3].end, = p2,p3
self._base_aabb_lines[4].start,self._base_aabb_lines[4].end, = p4,p5
self._base_aabb_lines[5].start,self._base_aabb_lines[5].end, = p4,p6
self._base_aabb_lines[6].start,self._base_aabb_lines[6].end, = p5,p7
self._base_aabb_lines[7].start,self._base_aabb_lines[7].end, = p6,p7
self._base_aabb_lines[8].start,self._base_aabb_lines[8].end, = p0,p4
self._base_aabb_lines[9].start,self._base_aabb_lines[9].end, = p1,p5
self._base_aabb_lines[10].start,self._base_aabb_lines[10].end, = p2,p6
self._base_aabb_lines[11].start,self._base_aabb_lines[11].end, = p3,p7
def _enable_base_aabb(self, ena):
if self._engine.meshes_base_aabb.IsEmpty():
ena = False
for l in self._base_aabb_lines:
l.visible = ena
def _on_options_dist_mult_changed(self, m, *args):
index = m.get_item_value_model().get_value_as_int()
mult = const.OPTIONS_DIST_MULT_COMBO_VALUES[index][1]
self._engine.dist_mult = mult
def _on_options_accel_changed(self, model):
self._engine.order_accel = model.as_float
def _on_options_bounds_changed(self, model):
self._options_bounds_alpha = model.as_float
set_setting(const.SETTINGS_PATH + const.OPTIONS_BOUNDS_ALPHA_SETTING, self._options_bounds_alpha)
color = self.prepare_base_aabb_color()
for l in self._base_aabb_lines:
l.color = color
def _on_options_unselect_changed(self, m):
self._options_unselect_on_use = m.as_float
set_setting(const.SETTINGS_PATH + const.OPTIONS_UNSELECT_ON_USE_SETTING, self._options_unselect_on_use)
def _on_info(self):
res = webbrowser.open(const.INFO_URL)
| 23,446 | Python | 37.063312 | 143 | 0.514416 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/libs/app_utils.py | """"""
import asyncio, functools, sys
import os.path
import carb
import omni.kit
import omni.kit.viewport.utility as vut
import omni.ui as ui
import omni.usd
from pxr import Gf, Tf, Sdf, Usd, UsdGeom, CameraUtil
VERSION = 11
def call_after_update(fn, update_count=1):
async def wait_for_update(count):
while count:
await omni.kit.app.get_app().next_update_async()
count -= 1
fn()
asyncio.ensure_future(wait_for_update(update_count))
def call_on_ready(is_ready_fn, on_ready_fn, max_tries=sys.maxsize):
async def wait_for():
nonlocal max_tries
while max_tries:
await omni.kit.app.get_app().next_update_async()
if is_ready_fn():
on_ready_fn()
return
max_tries -= 1
if is_ready_fn(): # straight away?
on_ready_fn()
return
else:
asyncio.ensure_future(wait_for())
def call_on_parts_ready(on_ready_fn, part_flags=1 | 2 | 4,
max_tries=sys.maxsize,
usd_context=None, usd_context_name='',
window_name: str = None,
):
"""Call back when all parts in part_flags are ready:
part_flags:
Stage ready=1
Stage camera ready=2 -> implies stage ready
Viewport non-zero frame size=4
"""
def are_parts_ready():
ready_mask = 0
if part_flags & (1 | 2 | 4):
api, win = vut.get_active_viewport_and_window(usd_context_name=usd_context_name,
window_name=window_name)
if part_flags & (1 | 2):
if usd_context is None:
ctx = omni.usd.get_context()
else:
ctx = usd_context
if not ctx:
return False
stage = ctx.get_stage()
if not stage:
return False
cam_prim = stage.GetPrimAtPath(api.camera_path)
ready_mask = 1 | (2 if cam_prim.IsValid() else 0)
if part_flags & 4:
if not win:
return False
ws_win = ui.Workspace.get_window(win.name)
if not ws_win:
return False
if not hasattr(ws_win, 'frame'):
return False
ws_win_frame = ws_win.frame
if ws_win_frame.computed_width > 0 and ws_win_frame.computed_height > 0:
ready_mask |= 4
return part_flags & ready_mask == part_flags
call_on_ready(are_parts_ready, on_ready_fn, max_tries)
# convenience calls
def call_on_stage_ready(on_ready_fn, usd_context=None, max_tries=sys.maxsize):
call_on_parts_ready(on_ready_fn, 1, usd_context=usd_context, max_tries=max_tries)
def call_on_stage_camera_ready(on_ready_fn,
usd_context=None, usd_context_name='',
window_name: str = None,
max_tries=sys.maxsize):
call_on_parts_ready(on_ready_fn, 1 | 2,
usd_context=usd_context, usd_context_name=usd_context_name,
window_name=window_name, max_tries=max_tries)
def get_setting_or(path, not_found_value):
value = carb.settings.get_settings().get(path)
if value is not None:
return value
else:
return not_found_value
def set_setting(path, value):
carb.settings.get_settings().set(path, value)
def delete_setting(path):
carb.settings.get_settings().destroy_item(path)
def get_extension_path(ext_id, sub_path=None):
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
if sub_path is not None:
return os.path.join(ext_path, sub_path)
else:
return ext_path
def matrix44_flatten(mat):
"""Get a omni.ui.scene.Matrix44 (an array[16]) from a pxr.Gf.Matrix4d or array[4][4]."""
return [mat[0][0], mat[0][1], mat[0][2], mat[0][3],
mat[1][0], mat[1][1], mat[1][2], mat[1][3],
mat[2][0], mat[2][1], mat[2][2], mat[2][3],
mat[3][0], mat[3][1], mat[3][2], mat[3][3]]
| 4,241 | Python | 25.185185 | 93 | 0.537373 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/libs/manipulators.py | """
If you're getting Kit launch time errors related with omni.ui.scene,
add omni.ui.scene to your extension dependencies in extension.toml:
[dependencies]
"omni.ui.scene" = {}
"""
from typing import Dict
import carb
import omni.kit, omni.usd
from pxr import Gf, Sdf, Tf, Usd, UsdGeom
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.manipulator.transform import AbstractTransformManipulatorModel, Operation
from omni.kit.manipulator.transform.manipulator import TransformManipulator, Axis
from omni.kit.manipulator.transform.simple_transform_model import SimpleTransformModel
from omni.kit.manipulator.transform.gestures import TranslateChangedGesture, TranslateDragGesturePayload
from .viewport_helper import ViewportHelper
class TranslateManipulator():
VERSION = 9
def __init__(self, viewport: ViewportHelper,
point=Gf.Vec3d(0, 0, 0),
size=1.,
enabled=False,
axes: Axis = Axis.ALL,
style: Dict = {},
changed_fn=None):
""" style: all colors in 0xAABBGGRR
{
"Translate.Axis::x": {"color": 0xAABBGGRR},
"Translate.Axis::y": {"color": },
"Translate.Axis::z": {"color": },
"Translate.Plane::x_y": {"color": },
"Translate.Plane::y_z": {"color": },
"Translate.Plane::z_x": {"color": },
"Translate.Point": {"color": 0xAABBGGRR, "type": "point"/"notpoint"},
}
"""
self._manip = None
self._gesture = None
self._changed_fn = None
#if not viewport.is_attached:
# raise AssertionError("Viewport not attached")
self._is_legacy = viewport.is_legacy
model = SimpleTransformModel()
model.set_operation(Operation.TRANSLATE)
model.set_floats(model.get_item("translate"), point)
self._changed_fn = changed_fn
self._gesture = TranslateGesture(viewport=viewport, changed_fn=self._on_changed_fn)
if self._is_legacy:
self._manip = ManipulatorFactory.create_manipulator(TransformManipulator,
model=model,
size=size,
enabled=enabled,
axes=axes,
style=style,
gestures=[self._gesture])
else:
#self._manip = None
#raise AssertionError("TranslateManipulator not currently usable on VP2")
self._manip = TransformManipulator(model=model,
size=size,
enabled=enabled,
axes=axes,
style=style,
gestures=[self._gesture])
def __del__(self):
self.destroy()
def destroy(self):
if self._gesture:
self._gesture.destroy()
self._gesture = None
if self._manip:
if self._is_legacy:
ManipulatorFactory.destroy_manipulator(self._manip)
else:
self._manip.destroy()
self._manip = None
if self._changed_fn:
self._changed_fn = None
@property
def enabled(self):
return self._manip.enabled
@enabled.setter
def enabled(self, ena):
self._manip.enabled = ena
@property
def point(self):
return self._manip.model.get_as_floats(self._manip.model.get_item("translate"))
@point.setter
def point(self, point):
self._manip.model.set_floats(self._manip.model.get_item("translate"),
[point[0], point[1], point[2]])
def set_changed_fn(self, fn):
""" fn(action, manip)
action: began=0,changed=1,ended=2,canceled=3
"""
self._changed_fn = fn
def _on_changed_fn(self, action, point):
if self._changed_fn:
self._changed_fn(action, self)
"""
class PointTranslateModel(SimpleTransformModel):
def __init__(self, point):
super().__init__()
self.set_operation(Operation.TRANSLATE)
self.set_floats(self.get_item("translate"), point)
"""
class TranslateGesture(TranslateChangedGesture):
def __init__(self, viewport, changed_fn=None, **kwargs):
TranslateChangedGesture.__init__(self)
self._vp = viewport
self.changed_fn = changed_fn
def destroy(self):
self._vp = None
self.changed_fn = None
def __del__(self):
self.destroy()
def on_began(self):
# print("TranslateGesture.on_began", self._vp.window_name)
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, TranslateDragGesturePayload):
return
model = self.sender.model
if not model:
return
pt = model.get_as_floats(model.get_item("translate"))
self._begin_point = Gf.Vec3d(*pt)
if self._vp.is_legacy:
self._vp.temp_select_enabled(False)
if self.changed_fn:
self.changed_fn(0, self._begin_point)
def on_ended(self):
# print("TranslateGesture.on_ended")
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, TranslateDragGesturePayload):
return
model = self.sender.model
if not model:
return
if self.changed_fn:
pt = model.get_as_floats(model.get_item("translate"))
self.changed_fn(2, Gf.Vec3d(*pt))
def on_canceled(self):
# print("TranslateGesture.on_canceled")
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, TranslateDragGesturePayload):
return
model = self.sender.model
if not model:
return
if self.changed_fn:
pt = model.get_as_floats(model.get_item("translate"))
self.changed_fn(3, Gf.Vec3d(*pt))
def on_changed(self):
# print("TranslateGesture.on_changed")
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, TranslateDragGesturePayload):
return
model = self.sender.model
if not model:
return
translate = Gf.Vec3d(*self.gesture_payload.moved)
point = self._begin_point + translate
model.set_floats(model.get_item("translate"), [point[0], point[1], point[2]])
if self.changed_fn:
self.changed_fn(1, point)
| 6,989 | Python | 25.477273 | 124 | 0.546001 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/libs/usd_utils.py | """
Notes:
"""
import omni.kit
import omni.usd
from pxr import Gf, Sdf, Usd, UsdGeom
VERSION = 15
XFORM_OP_TRANSLATE_TYPE_TOKEN = UsdGeom.XformOp.GetOpTypeToken(UsdGeom.XformOp.TypeTranslate)
XFORM_OP_TRANSLATE_ATTR_NAME = "xformOp:" + XFORM_OP_TRANSLATE_TYPE_TOKEN
def get_prim_transform(prim,
with_pivot,
xform_cache=None,
time_code=Usd.TimeCode.Default()):
"""Returns a prim's local transformation, converting mesh points into parent-space coords.
with_pivot=True: returns GetLocalTransformation, where pivot and pivot^-1 are included into the translation.
with_pivot=False will set translation to the actual translate XformOp.
If no pivot is set, returns GetLocalTransformation()
"""
if xform_cache is None:
xform_cache = UsdGeom.XformCache(time_code)
mat, _ = xform_cache.GetLocalTransformation(prim)
if with_pivot:
return mat
# remove pivot from local transform
attr_name = XFORM_OP_TRANSLATE_ATTR_NAME
op_attr = prim.GetAttribute(attr_name + ":pivot")
if not op_attr: # no pivot, return mat
return mat
op_attr = prim.GetAttribute(attr_name)
if op_attr:
op = UsdGeom.XformOp(op_attr)
if op:
trans = op.Get(time_code)
if trans is not None:
mat.SetTranslateOnly(make_vec3_for_matrix4(mat, trans))
return mat
# translation not found: set to identity translate
mat.SetTranslateOnly(make_vec3_for_matrix4(mat, 0, 0, 0))
return mat
def set_prim_transform(prim, mat,
sdf_change_block=1,
time_code=Usd.TimeCode.Default()):
"""sdf_change_block: 0: don't use, 1: use locally, 2: assume already began"""
sdf_change_block = 0
stage = prim.GetStage()
if sdf_change_block == 1:
Sdf.BeginChangeBlock()
xform = UsdGeom.Xformable(prim)
ops = xform.GetOrderedXformOps()
for op in ops:
if op.GetOpType() == UsdGeom.XformOp.TypeTransform:
_set_xform_op_time_code(op, mat, time_code, stage)
if sdf_change_block == 1:
Sdf.EndChangeBlock()
return
def get_or_add(op_type, prec):
type_token = UsdGeom.XformOp.GetOpTypeToken(op_type)
attr_name = "xformOp:" + type_token
op_attr = prim.GetAttribute(attr_name)
if op_attr:
op = UsdGeom.XformOp(op_attr)
if op:
return op
if sdf_change_block >= 1:
Sdf.EndChangeBlock()
op = xform.AddXformOp(op_type, prec)
if sdf_change_block >= 1:
Sdf.BeginChangeBlock()
return op
# not a transform: decompose matrix and set various S,R,T as needed
_, _, scale, rot_mat, trans, _ = mat.Factor()
rot_mat.Orthonormalize(False)
rot = rot_mat.ExtractRotation()
new_ops = []
# translation
op = get_or_add(UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.PrecisionDouble)
if op:
_set_xform_op_time_code(op, trans, time_code, stage)
new_ops.append(op)
# scale/rotate pivot (a translate)
pivot_op = None
attr_name = XFORM_OP_TRANSLATE_ATTR_NAME + ":pivot"
op_attr = prim.GetAttribute(attr_name)
if op_attr:
pivot_op = UsdGeom.XformOp(op_attr)
if pivot_op:
new_ops.append(pivot_op)
# rotation: pick first type
rot_type, rot_prec = UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.PrecisionFloat
for op in ops:
op_type = op.GetOpType()
if op_type >= UsdGeom.XformOp.TypeRotateX and op_type <= UsdGeom.XformOp.TypeOrient:
rot_type, rot_prec = op_type, op.GetPrecision()
break
def rot_get_or_add(rot_type,
axis_0, axis_1, axis_2,
x, y, z,
rot_prec
):
angles = rot.Decompose(axis_0, axis_1, axis_2)
rot_vals = Gf.Vec3f(angles[x], angles[y], angles[z]) # unscramble to x,y,z order that op.Set() needs
op = get_or_add(rot_type, rot_prec)
if op:
_set_xform_op_time_code(op, rot_vals, time_code, stage)
new_ops.append(op)
# single rotation?
if rot_type >= UsdGeom.XformOp.TypeRotateX and rot_type <= UsdGeom.XformOp.TypeRotateZ:
angles = rot.Decompose(Gf.Vec3d.ZAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis())
op = get_or_add(UsdGeom.XformOp.TypeRotateX, rot_prec)
if op:
_set_xform_op_time_code(op, angles[2], time_code, stage)
new_ops.append(op)
op = get_or_add(UsdGeom.XformOp.TypeRotateY, rot_prec)
if op:
_set_xform_op_time_code(op, angles[1], time_code, stage)
new_ops.append(op)
op = get_or_add(UsdGeom.XformOp.TypeRotateZ, rot_prec)
if op:
_set_xform_op_time_code(op, angles[0], time_code, stage)
new_ops.append(op)
# quaternion?
elif rot_type == UsdGeom.XformOp.TypeOrient:
type_token = UsdGeom.XformOp.GetOpTypeToken(rot_type)
attr_name = "xformOp:" + type_token
op_attr = prim.GetAttribute(attr_name)
if op_attr:
op = UsdGeom.XformOp(op_attr)
if op:
_set_xform_op_time_code(op, rot.GetQuat(), time_code, stage)
new_ops.append(op)
# triple rotation?
elif rot_type == UsdGeom.XformOp.TypeRotateXZY:
rot_get_or_add(rot_type,
Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis(), Gf.Vec3d.XAxis(),
2, 0, 1,
rot_prec)
elif rot_type == UsdGeom.XformOp.TypeRotateYXZ:
rot_get_or_add(rot_type,
Gf.Vec3d.ZAxis(), Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(),
1, 2, 0,
rot_prec)
elif rot_type == UsdGeom.XformOp.TypeRotateYZX:
rot_get_or_add(rot_type,
Gf.Vec3d.XAxis(), Gf.Vec3d.ZAxis(), Gf.Vec3d.YAxis(),
0, 2, 1,
rot_prec)
elif rot_type == UsdGeom.XformOp.TypeRotateZXY:
rot_get_or_add(rot_type,
Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis(), Gf.Vec3d.ZAxis(),
1, 0, 2,
rot_prec)
elif rot_type == UsdGeom.XformOp.TypeRotateZYX:
rot_get_or_add(rot_type,
Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis(),
0, 1, 2,
rot_prec)
else: # just assume TypeRotateXYZ for any other
rot_get_or_add(rot_type,
Gf.Vec3d.ZAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis(),
2, 1, 0,
rot_prec)
# scale
op = get_or_add(UsdGeom.XformOp.TypeScale, UsdGeom.XformOp.PrecisionFloat)
if op:
_set_xform_op_time_code(op, scale, time_code, stage)
new_ops.append(op)
# pivot_op^-1
if pivot_op is not None:
for op in ops:
if op.IsInverseOp() and \
op.GetOpType() == UsdGeom.XformOp.TypeTranslate and \
is_pivot_xform_op_name_suffix(op.GetOpName()):
new_ops.append(op)
break
# and finally set new ops into xform
xform.SetXformOpOrder(new_ops, xform.GetResetXformStack())
if sdf_change_block == 1:
Sdf.EndChangeBlock()
"""
Note: touch_prim_xform() doesn't work, probably because the value is equal and caches are not rebuilt.
But this does:
lmat = get_prim_transform(prim, False, xform_cache, time_code)
cmd = TransformPrimCommand(path=path, new_transform_matrix=lmat, time_code=time_code)
#slower: cmd = TransformPrimSRTCommand(path=path, time_code=time_code)
cmd.do()
--------------------
def touch_prim_xform(prim,
sdf_change_block=1,
time_code=Usd.TimeCode.Default()):
#sdf_change_block: 0: don't use, 1: use locally, 2: assume already began
if sdf_change_block == 1:
Sdf.BeginChangeBlock()
xform = UsdGeom.Xformable(prim)
ops = xform.GetOrderedXformOps()
for op in ops:
if not op.IsInverseOp():
op.Set(op.Get(time_code), time_code)
break
if sdf_change_block == 1:
Sdf.EndChangeBlock()
"""
def get_prim_translation(prim,
time_code=Usd.TimeCode.Default()):
# remove pivot from local transform
op_attr = prim.GetAttribute(XFORM_OP_TRANSLATE_ATTR_NAME)
if op_attr:
op = UsdGeom.XformOp(op_attr)
if op:
trans = op.Get(time_code)
if trans is not None:
return Gf.Vec3d(trans)
# translation not found: return identity
return Gf.Vec3d(0.)
def set_prim_translation(prim, trans,
sdf_change_block=1,
time_code=Usd.TimeCode.Default()):
"""sdf_change_block: 0: don't use, 1: use locally, 2: assume already began"""
# print(prim.GetPath().pathString)
sdf_change_block = 0
mat_op = trans_op = None
xform = UsdGeom.Xformable(prim)
for op in xform.GetOrderedXformOps():
op_type = op.GetOpType()
if op_type == UsdGeom.XformOp.TypeTransform:
mat_op = op
break
elif op_type == UsdGeom.XformOp.TypeTranslate and not is_pivot_xform_op_name_suffix(op.GetOpName()): # op.SplitName()
# simple translation, not pivot/invert
trans_op = op
break
if mat_op: # has matrix op
if sdf_change_block == 1:
Sdf.BeginChangeBlock()
mat = Gf.Matrix4d()
mat.SetTranslate(trans)
stage = prim.GetStage()
_set_xform_op_time_code(mat_op, mat, time_code, stage)
else: # set or add a translation xform op
stage = prim.GetStage()
# can't just set attr as order might not have been set
if not trans_op:
if sdf_change_block == 2:
Sdf.EndChangeBlock()
trans_op = _prepend_xform_op(xform,
UsdGeom.XformOp.TypeTranslate,
get_xform_op_precision(trans),
time_code, stage)
if sdf_change_block == 2:
Sdf.BeginChangeBlock()
if sdf_change_block == 1:
Sdf.BeginChangeBlock()
_set_xform_op_time_code(trans_op, trans, time_code, stage)
if sdf_change_block == 1:
Sdf.EndChangeBlock()
def set_prim_translation_fast(prim, trans,
sdf_change_block=1,
time_code=Usd.TimeCode.Default()):
"""
As set_translation() but won't copy time samples from weaker layers.
sdf_change_block: 0: don't use, 1: use locally, 2: assume already began
see: https://graphics.pixar.com/usd/release/api/class_sdf_change_block.html
"""
sdf_change_block = 0
if prim.HasAttribute("xformOp:mat"): # has matrix op
if sdf_change_block == 1:
Sdf.BeginChangeBlock()
at = prim.GetAttribute("xformOp:mat")
if not at.GetNumTimeSamples():
time_code = Usd.TimeCode.Default()
mat = at.Get(time_code)
mat.SetTranslateOnly(trans)
at.Set(mat, time_code)
else: # set or add a translation xform op
# can't just set attr as order might not have been set
attr = prim.GetAttribute("xformOp:translate")
op = UsdGeom.XformOp(attr)
if not op:
if sdf_change_block == 2:
Sdf.EndChangeBlock()
stage = prim.GetStage()
xform = UsdGeom.Xformable(prim)
op = _prepend_xform_op(xform,
UsdGeom.XformOp.TypeTranslate,
get_xform_op_precision(trans),
time_code, stage)
if sdf_change_block == 2:
Sdf.BeginChangeBlock()
if sdf_change_block == 1:
Sdf.BeginChangeBlock()
if not op.GetNumTimeSamples():
time_code = Usd.TimeCode.Default()
op.Set(trans, time_code) # Gf.Vec3d()
if sdf_change_block == 1:
Sdf.EndChangeBlock()
def _set_xform_op_time_code(xform_op, value, time_code, stage):
prev = xform_op.Get(time_code)
if not xform_op.GetNumTimeSamples(): # no time samples
time_code = Usd.TimeCode.Default()
if prev is None:
if not time_code.IsDefault():
omni.usd.copy_timesamples_from_weaker_layer(stage, xform_op.GetAttr())
xform_op.Set(value, time_code)
else:
value_type = type(prev) # to preserve existing value type
if not time_code.IsDefault():
omni.usd.copy_timesamples_from_weaker_layer(stage, xform_op.GetAttr())
xform_op.Set(value_type(value), time_code)
def _prepend_xform_op(xform, op_type, prec, time_code, stage):
# print("pre", _get_xform_op_order(xform))
prev_ops = xform.GetOrderedXformOps()
xform.SetXformOpOrder([])
# print("mid", _get_xform_op_order(xform))
new_op = xform.AddXformOp(op_type, prec)
for op in prev_ops:
suffix = get_xform_op_name_suffix(op.GetOpName())
inverse = op.IsInverseOp()
new = xform.AddXformOp(op.GetOpType(), op.GetPrecision(),
suffix,
inverse)
if not inverse:
value = op.Get(time_code)
if value is not None:
_set_xform_op_time_code(new, value, time_code, stage)
# print("post", _get_xform_op_order(xform))
return new_op
def get_xform_op_precision(t):
if isinstance(t, Gf.Matrix4d) or isinstance(t, Gf.Vec3d):
return UsdGeom.XformOp.PrecisionDouble
else:
return UsdGeom.XformOp.PrecisionFloat
def get_vec3_type_for_matrix4(mat):
if isinstance(mat, Gf.Matrix4d):
return Gf.Vec3d
else:
return Gf.Vec3f
def make_vec3_for_matrix4(mat, x, y=None, z=None):
t = get_vec3_type_for_matrix4(mat)
if y is None:
return t(x[0], x[1], x[2])
else:
return t(x, y, z)
def _get_xform_op_order(xform):
out = ""
for op in xform.GetOrderedXformOps():
out += op.GetOpName() + ","
return out
XFORM_OP_INVERSE_PREFIX = "!invert!"
def is_xform_op_name_inverse(op_name):
return op_name.startswith(XFORM_OP_INVERSE_PREFIX)
def get_xform_op_name_suffix(op_name):
# or
if is_xform_op_name_inverse(op_name):
op_name = op_name.split(XFORM_OP_INVERSE_PREFIX, 1)[1]
if op_name.startswith("xformOp:"):
tags = op_name.split(":", 2)
if len(tags) >= 3:
return tags[2]
return ""
def is_pivot_xform_op_name_suffix(op_name):
"""or faster:
"xformOp:" in op_name and "pivot" in op_name
"""
suffix = get_xform_op_name_suffix(op_name)
if suffix != "":
return suffix == "pivot"
else:
return False
def create_edit_context(path, stage):
"""Unsafe from threading? No issues so far:
https://graphics.pixar.com/usd/release/api/class_usd_edit_context.html#details
"""
layer, prim = omni.usd.find_spec_on_session_or_its_sublayers(stage, path)
if not prim or not layer:
return Usd.EditContext(stage)
if prim.specifier == Sdf.SpecifierDef:
return Usd.EditContext(stage, Usd.EditTarget(layer))
else:
return Usd.EditContext(stage)
| 15,617 | Python | 27.14054 | 126 | 0.570212 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/libs/ui_utils.py | """
Utility UI functions.
"""
from enum import IntEnum
import omni.ui as ui
VERSION = 4
class UiPaletteDark(IntEnum):
"""Colors in 0xAABBGGRR format. All colors with ff alpha if possible"""
BACK = 0xff23211f # darker than WINDOW_BACK: general widget background, window title bar
BACK_SELECTED = 0xff6e6e6e
BACK_HOVERED = BACK_SELECTED
TEXT = 0xffcccccc
TEXT_SELECTED = 0xff8b8a8a
TEXT_DISABLED = 0xff505050
WINDOW_BACK = 0xff454545 # lighter than BACK: window base color where darker controls are placed
TOOLTIP_TEXT = 0xff303030
TOOLTIP_BACK = 0xffaadddd
RESET = 0xffa07d4f # field reset button
TRANSP = 0x00000000
TRANSP_NOT_0 = 0x00ffffff # some widgets collapse width if 0 is passed as a color
UiPal = UiPaletteDark
def UiPal_refresh():
global UiPal
UiPal = UiPaletteDark
def create_tooltip(text: str,
tooltip_style=None,
tooltip_text_style=None):
if tooltip_style is None:
tooltip_style = {
"color": UiPal.TOOLTIP_TEXT,
"background_color": UiPal.TOOLTIP_BACK,
"margin": -1,
"border_width": 0,
}
if tooltip_text_style is None:
tooltip_text_style = {"margin": 3}
with ui.ZStack(style=tooltip_style):
ui.Rectangle()
ui.Label(text, style=tooltip_text_style)
def create_tooltip_fn(text: str,
tooltip_style=None,
tooltip_text_style=None):
return lambda: create_tooltip(text, tooltip_style, tooltip_text_style)
def create_reset_button(reset_value,
widget_model,
widget_set_value_fn,
widget_add_value_changed_fn,
style_on=None,
style_off=None,
on_tooltip_text=True, # True: use default, None: no tooltip
) -> ui.Rectangle:
if style_on is None:
style_on = {
"background_color": UiPal.RESET,
"border_radius": 2,
"color": 0xffffffff
}
if style_off is None:
style_off = {"background_color": UiPal.TEXT_DISABLED}
if on_tooltip_text is True:
on_tooltip_text = "Click to reset to default value"
def update_rect(new_value, *_):
if type(new_value) is ui.AbstractItemModel:
new_value = new_value.get_item_value_model()
if type(reset_value) is bool:
new_value = new_value.as_bool
elif type(reset_value) is int:
new_value = new_value.as_int
elif type(reset_value) is float:
new_value = new_value.as_float
# value changed? display reset button
rect.visible = new_value != reset_value
SIZE = 12
OFF_LEFT_PAD = 3
OFF_SIZE = 5
with ui.VStack(width=0, style={"margin": 0}):
ui.Spacer()
with ui.ZStack(width=SIZE, height=SIZE):
# disabled reset button
with ui.HStack(width=SIZE, height=SIZE):
ui.Spacer(width=OFF_LEFT_PAD)
with ui.VStack(width=SIZE, height=SIZE):
ui.Spacer()
ui.Rectangle(width=OFF_SIZE, height=OFF_SIZE, name="reset_off",
style=style_off)
ui.Spacer()
# actionable reset button
rect = ui.Rectangle(
width=SIZE,
height=SIZE,
name="reset",
alignment=ui.Alignment.V_CENTER,
style=style_on,
margin=0)
if on_tooltip_text is not None:
rect.set_tooltip_fn(create_tooltip_fn(on_tooltip_text))
rect.set_mouse_pressed_fn(lambda x, y, b, m: widget_set_value_fn(reset_value))
# initial rect visibility
update_rect(widget_model)
ui.Spacer()
widget_add_value_changed_fn(update_rect)
return rect
| 4,015 | Python | 25.077922 | 101 | 0.558655 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/libs/viewport_helper.py | """
+ Coordinate spaces:
- 2D screen coordinate spaces
ui: whole frame area float UI units, only equal to px units when omni.ui.Workspace.get_dpi_scale() is 1. ui = px_units / dpi_scale.
Origin is left-top corner of the frame, 0..ui_size().
(app_ui = ui coordinates in Kit's app coordinates, window left-top is the origin.)
(px: whole frame area integer screen monitor pixels, 0..px_size(). Use ui coords instead for units to scale in high density displays)
01: float 0..1 coordinates covering whole frame area. Origin is left-top corner.
ndc: float -1..+1 Normalized Device Coordinates covering whole frame area. Origin is center, 1,1 is top-right corner of frame.
iscene: coordinates in a SceneView with view and projection transforms both set to identity matrices.
Origin is center, +x,+y is right-top corner. Can span -xy..+xy, where xy=iscene_half().
Fixed aspect ratio: a size displays at the same length in x and y.
render: area where rendering displays with size fitted to frame area, which can occupy whole or only a part.
NDC coords always extend -1..+1, origin is the center, 1,1 is top-right corner of frame.
- 3D world space
world: world space 3D coordinates
+ Coordinate/size conversions:
- 2D screen spaces
conv_iscene_from_render
conv_iscene_from_ndc
conv_iscene_from_01
conv_iscene_from_ui
size_iscene_from_ui
conv_render_from_ndc <-> conv_ndc_from_render
conv_01_from_ui <-> conv_ui_from_01
conv_ndc_from_ui <-> conv_ui_from_ndc
conv_01_from_app_ui, conv_ndc_from_app_ui, conv_ui_from_app_ui
conv_ndc_from_01 <-> conv_01_from_ndc
- 3D <-> 2D spaces
conv_render_from_world
conv_iscene_from_world
pick_ray_from_render
All conv_* methods accept points in Gf.Vec2*/Gf.Vec3* or tuple, but always return Gf.Vec2d/Gf.Vec3d points.
+ SceneView transformations
get_transform_iscene_from_ui
get_transform_iscene_from_render
+ Legacy Viewport:
Extension omni.kit.viewport_legacy (was omni.kit.window.viewport)
_win -> class omni.kit.viewport.utility.legacy_viewport_window.LegacyViewportWindow -> omni.ui.Window
_api -> class omni.kit.viewport.utility.legacy_viewport_api.LegacyViewportAPI
Use _win.legacy_window to get the actual IViewportWindow ->
class omni.kit.viewport_legacy._viewport_legacy.IViewportWindow
set_enabled_picking(), get_mouse_event_stream(), etc
+ Viewport Next
Partially supported. Extensions omni.kit.viewport.window, omni.kit.widget.viewport
+ Notes
- Don't store and always access ViewportHelper's frame or render area sizes as they may change due to user interactions,
even when changing Kit between display monitors.
"""
import asyncio, functools
import carb
import omni.kit
import omni.kit.viewport.utility as vut
import omni.ui as ui
""" Since omni.ui.scene may not not available on Kit's early launch,
if you're launch time errors related with omni.ui.scene, add omni.ui.scene
to your extension dependencies in extension.toml:
[dependencies]
"omni.ui.scene" = {} """
from omni.ui import scene as sc
from pxr import Gf, Tf, Sdf, Usd, UsdGeom, CameraUtil
SETTING_RENDER_WIDTH = "/app/renderer/resolution/width"
SETTING_RENDER_HEIGHT = "/app/renderer/resolution/height"
SETTING_CONFORM_POLICY = "/app/hydra/aperture/conform"
SETTING_RENDER_FILL_LEGACY = "/app/runLoops/rendering_0/fillResolution"
SETTING_RENDER_FILL = "/persistent/app/viewport/{api_id}/fillViewport"
SETTING_DEFAULT_WINDOW_NAME = "/exts/omni.kit.viewport.window/startup/windowName"
class ViewportHelper():
LIB_VERSION = 45
def __init__(self, window_name=None, attach: bool = True):
self._win = None
self._api = None
self._ws_win_frame = None
self._sub_render_width = None
self._sub_render_height = None
self._sub_render_fill = None
self._is_legacy = True
self._frame_mouse_fns = {} # frame: set(fn,fn,...)
self._frame_size_changed_fns = {} # frame: set(fn,fn,...)
self._render_changed_fns = set() # set(fn,fn,...)
self._stage_objects_changed = None # [listener, set(fn,fn,...)]
self._changed_fns = {} # fn: sub_flags
if attach:
res = self.attach(window_name=window_name)
if not res:
raise AssertionError("Could not attach")
def __del__(self):
self.detach()
def attach(self, window_name=None, usd_context_name: str = '') -> bool:
""" window_name:
str: actual window name/title, like "Viewport"
None: current/last active viewport
int: index into ViewportHelper.get_window_names()
Window selection order: .get_active_viewport_and_window() vut tries to attach "Viewport Next" first,
then legacy "Viewport" windows."""
self.detach()
if window_name is not None:
if type(window_name) is int:
wn_list = ViewportHelper.get_window_names()
if window_name < len(wn_list):
window_name = wn_list[window_name]
else:
raise AssertionError("Non-existent window_name")
else:
raise AssertionError("Bad window_name index")
self._api,self._win = vut.get_active_viewport_and_window(usd_context_name=usd_context_name,
window_name=window_name)
if self._win is None or self._api is None:
self._win = None
self._api = None
self._ws_win = None
self._ws_win_frame = None
return False
if self.stage is None:
raise AssertionError("Stage not available")
self._is_legacy = hasattr(self._api, "legacy_window")
self._ws_win = ui.Workspace.get_window(self._win.name)
if self._ws_win is None:
raise AssertionError("Workspace window not available")
"""
if not self._ws_win.visible:
print("Viewport Window is not visible: can't attach")
self.detach()
return False
"""
if not hasattr(self._ws_win, 'frame'):
self._ws_win_frame = None
raise AssertionError("Workspace window frame not available")
self._ws_win_frame = self._ws_win.frame
return True
def detach(self):
settings = carb.settings.get_settings()
if self._sub_render_width:
settings.unsubscribe_to_change_events(self._sub_render_width)
self._sub_render_width = None
if self._sub_render_height:
settings.unsubscribe_to_change_events(self._sub_render_height)
self._sub_render_height = None
if self._sub_render_fill:
settings.unsubscribe_to_change_events(self._sub_render_fill)
self._sub_render_fill = None
if self._win is not None:
if self._is_legacy:
self._win.destroy()
self._win = None
self._api = None
self._ws_win = None
self._ws_win_frame = None
self._frame_mouse_fns.clear()
self._frame_size_changed_fns.clear()
self._render_changed_fns.clear()
self._changed_fns.clear()
if self._stage_objects_changed is not None:
if len(self._stage_objects_changed):
self._stage_objects_changed[0].Revoke()
self._stage_objects_changed = None
@property
def is_attached(self):
return self._win is not None
@property
def window_name(self) -> str:
return self._win.name
@staticmethod
def get_default_window_name():
return carb.settings.get_settings().get(SETTING_DEFAULT_WINDOW_NAME) or 'Viewport'
@staticmethod
def get_window_names():
try:
from omni.kit.viewport.window import get_viewport_window_instances
return [w.title for w in get_viewport_window_instances()]
except ImportError:
return [ViewportHelper.get_default_window_name()]
@property
def is_legacy(self):
return self._is_legacy
@property
def camera_path(self) -> Sdf.Path:
return self._api.camera_path
@camera_path.setter
def camera_path(self, camera_path):
self._api.camera_path = camera_path
def get_camera_view_proj(self):
frustum = self.get_conformed_frustum()
if frustum is None:
return None
return frustum.ComputeViewMatrix(), frustum.ComputeProjectionMatrix()
def same_api(self, api) -> bool:
return id(api) == id(self._api)
def get_gf_camera(self):
"""Returns None if no valid prim found."""
cam = self._api.camera_path
stage = self.stage
if stage is None:
raise AssertionError("Stage not available")
cam_prim = stage.GetPrimAtPath( self.camera_path )
if cam_prim and cam_prim.IsValid():
usd_cam = UsdGeom.Camera(cam_prim)
if usd_cam:
return usd_cam.GetCamera()
# fall over
return None
@property
def fps(self) -> float:
return self._api.fps
@property
def usd_context_name(self) -> str:
return self._api.usd_context_name
@property
def usd_context(self):
return self._api.usd_context
@property
def stage(self):
return self.usd_context.get_stage()
def get_frame(self, frame_id: str):
return self._win.get_frame(frame_id)
@property
def ui_size(self):
""" Due to DPI pixel multiplier, can return fractional.
In DPI > 1 displays, this is UI units. Actual display pixels = UI units * omni.ui.Workspace.get_dpi_scale() """
if self._ws_win_frame is not None:
return self._ws_win_frame.computed_width, self._ws_win_frame.computed_height
else:
return 1.,1.
@property
def px_size(self):
""" Returns int size """
ui_size = self.ui_size
dpi_mult = ui.Workspace.get_dpi_scale()
return int(round(ui_size[0] * dpi_mult)), int(round(ui_size[1] * dpi_mult))
@property
def ui_size_ratio(self):
size = self.ui_size
return size[0] / size[1] if size[1] else 1.
@property
def render_size_px(self):
size = self._api.resolution
return (int(size[0]), int(size[1]))
@render_size_px.setter
def render_size_px(self, size):
self._api.resolution = (int(size[0]), int(size[1]))
# render_size width/height ratio
@property
def render_size_ratio(self):
size = self.render_size_px
return size[0] / size[1] if size[1] else 1.
""" ?Also render_rect_px, render_left_top_px """
"""
Kit-103.1.2/3: render_fill_frame get/set does not work coherently
Legacy Viewport: setting fill_frame makes viewport settings "Fill Viewport" disappear
Viewport 2: only works setting to True
Kit 104.0:
Viewport 2: api is not initialized to setting: so we use setting
@property
def render_fill_frame(self):
return self._api.fill_frame
@render_fill_frame.setter
def render_fill_frame(self, value: bool):
self._api.fill_frame = value
"""
@property
def render_fill_frame(self):
if self._is_legacy:
name = SETTING_RENDER_FILL_LEGACY
else:
name = SETTING_RENDER_FILL.format(api_id=self._api.id)
return bool(carb.settings.get_settings().get(name))
@render_fill_frame.setter
def render_fill_frame(self, value: bool):
if self._is_legacy:
name = SETTING_RENDER_FILL_LEGACY
else:
name = SETTING_RENDER_FILL.format(api_id=self._api.id)
carb.settings.get_settings().set(name, value)
def get_conformed_frustum(self):
cam = self.get_gf_camera()
if cam is None:
raise AssertionError("Camera not available")
frustum = cam.frustum
conform_policy = ViewportHelper.get_conform_policy()
CameraUtil.ConformWindow(frustum, conform_policy, self.render_size_ratio)
return frustum
@staticmethod
def get_conform_policy():
"""conform_policy: how is the render area fit into the frame area"""
policy = carb.settings.get_settings().get(SETTING_CONFORM_POLICY)
if policy is None or policy < 0 or policy > 5:
return CameraUtil.MatchHorizontally
else:
policies = [
CameraUtil.MatchVertically,
CameraUtil.MatchHorizontally,
CameraUtil.Fit,
CameraUtil.Crop,
CameraUtil.DontConform,
CameraUtil.DontConform,
]
return policies[policy]
def sync_scene_view(self, scene_view):
"""Must be called after viewport changes or before using a SceneView.
A SceneView's "screen_aspect_ratio" is the ratio of what we call the render space"""
frame_ratio = self.ui_size_ratio
render_ratio = self.render_size_ratio
if False and abs(frame_ratio - render_ratio) < 1e-6: # render equal to frame area: set to 0
ratio = 0
else:
ratio = render_ratio
if scene_view.screen_aspect_ratio != ratio:
scene_view.screen_aspect_ratio = ratio
# print("setup_scene_view asp_rat", scene_view.screen_aspect_ratio)
#====================================================================== coord space conversion
# generic NDC <-> 0..1 conversion
@staticmethod
def conv_ndc_from_01(coord):
return Gf.Vec2d( coord[0]*2. - 1., -(coord[1]*2. - 1.) )
@staticmethod
def conv_01_from_ndc(coord):
return Gf.Vec2d( (coord[0] + 1.) * 0.5, (-coord[1] + 1.) * 0.5)
def conv_01_from_ui(self, coord):
width,height = self.ui_size
return Gf.Vec2d(coord[0] / width, coord[1] / height)
def conv_ui_from_01(self, coord):
width,height = self.ui_size
return Gf.Vec2d(coord[0] * width, coord[1] * height)
def conv_ui_from_app_ui(self, coord):
frame = self._win.frame
return Gf.Vec2d(coord[0] - frame.screen_position_x, coord[1] - frame.screen_position_y)
def conv_01_from_app_ui(self, coord):
frame = self._win.frame
return self.conv_01_from_ui( (coord[0] - frame.screen_position_x, coord[1] - frame.screen_position_y) )
def conv_ndc_from_ui(self, coord):
xy = self.conv_01_from_ui(coord)
return ViewportHelper.conv_ndc_from_01(xy)
def conv_ui_from_ndc(self, coord):
xy = ViewportHelper.conv_01_from_ndc(xy)
return ViewportHelper.conv_ui_from_01(xy)
def conv_ndc_from_app_ui(self, coord):
xy = self.conv_01_from_app_ui(coord)
return ViewportHelper.conv_ndc_from_01(xy)
@property
def _render_from_size_ratios(self):
fr = self.ui_size
frame_ratio = fr[0] / fr[1] if fr[1] else 1.
render_ratio = self.render_size_ratio
if frame_ratio >= render_ratio: # tex vertical -1..+1
return (frame_ratio / render_ratio, 1.)
else: #
return (1., render_ratio / frame_ratio)
# coordinate conversion between frame-NDC and render(NDC) spaces
def conv_render_from_ndc(self, frame_ndc):
mx = frame_ndc[0]
my = frame_ndc[1]
ratios = self._render_from_size_ratios
mx *= ratios[0]
my *= ratios[1]
return Gf.Vec2d(mx, my)
def conv_ndc_from_render(self, render_ndc):
mx,my = self.conv_render_from_ndc(render_ndc)
return Gf.Vec2d(1./mx, 1./my)
def iscene_size(self, scene_view):
w,h = self.iscene_half(scene_view)
return w*2.,h*2.
def iscene_half(self, scene_view):
frame_ratio = self.ui_size_ratio
render_ratio = self.render_size_ratio
fills = abs(frame_ratio - render_ratio) < 1e-6
lands = frame_ratio >= render_ratio
asp_rat = scene_view.aspect_ratio_policy
# print("fills,lands", fills, lands, frame_ratio, render_ratio)
if asp_rat == sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT:
if fills and frame_ratio < 1:
mul = 1.,1./frame_ratio
elif lands:
mul = frame_ratio,1.
else:
mul = render_ratio,render_ratio/frame_ratio
elif asp_rat == sc.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL:
if lands:
mul = frame_ratio/render_ratio,1./render_ratio
else:
mul = 1.,1./frame_ratio
elif asp_rat == sc.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL:
if lands:
mul = frame_ratio,1.
else:
mul = render_ratio,render_ratio/frame_ratio
elif asp_rat == sc.AspectRatioPolicy.PRESERVE_ASPECT_CROP:
if fills and frame_ratio < 1:
mul=frame_ratio,1.
elif lands:
mul = frame_ratio/render_ratio,1./render_ratio
elif frame_ratio >= 1:
mul = 1.,1./frame_ratio
else:
mul = 1,1./frame_ratio
elif asp_rat == sc.AspectRatioPolicy.STRETCH:
if frame_ratio >= 1:
mul = frame_ratio,1.
else:
mul = 1,1./frame_ratio
else:
mul = 1.,1.
return mul
def iscene_render_half(self, scene_view):
"""Render half size expressed in iscene coords"""
frame_ratio = self.ui_size_ratio
render_ratio = self.render_size_ratio
fills = abs(frame_ratio - render_ratio) < 1e-6
lands = frame_ratio >= render_ratio
asp_rat = scene_view.aspect_ratio_policy
if asp_rat == sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT:
if fills and frame_ratio < 1:
mul = 1.,1./frame_ratio
else:
mul = render_ratio,1.
elif asp_rat == sc.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL:
mul = 1.,1./render_ratio
elif asp_rat == sc.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL:
mul = render_ratio,1.
elif asp_rat == sc.AspectRatioPolicy.PRESERVE_ASPECT_CROP:
if fills and frame_ratio < 1:
mul=frame_ratio,1.
else:
mul = 1.,1./render_ratio
elif asp_rat == sc.AspectRatioPolicy.STRETCH:
if fills and frame_ratio < 1:
mul = 1.,1./render_ratio
elif lands:
mul = render_ratio,1.
elif frame_ratio >= 1:
mul = frame_ratio,frame_ratio/render_ratio
else:
mul = 1.,1./render_ratio
else:
mul = 1.,1.
return mul
def conv_iscene_from_render(self, render_pt, scene_view):
mul = self.iscene_render_half(scene_view)
return Gf.Vec2d(render_pt[0] * mul[0], render_pt[1] * mul[1])
def conv_iscene_from_01(self, ui01, scene_view):
size = self.ui_size
pt = ViewportHelper.conv_ndc_from_01(ui01)
mul = self.iscene_half(scene_view)
return Gf.Vec2d(pt[0] * mul[0], pt[1] * mul[1])
def conv_iscene_from_ndc(self, ndc, scene_view):
mul = self.iscene_half(scene_view)
return Gf.Vec2d(ndc[0] * mul[0], ndc[1] * mul[1])
def conv_iscene_from_ui(self, ui_pt, scene_view):
size = self.ui_size
pt = ui_pt[0] / size[0] * 2. - 1., ui_pt[1] / size[1] * 2. - 1. # pt now in NDC
mul = self.iscene_half(scene_view)
return Gf.Vec2d(pt[0] * mul[0], pt[1] * mul[1])
def size_iscene_from_ui(self, ui_size, scene_view):
size = self.ui_size
ui_sz = 2. * ui_size / size[0]
mul = self.iscene_half(scene_view)
return ui_sz * mul[0]
def get_transform_iscene_from_ui(self, scene_view):
size_ui = self.ui_size
iscene_half = self.iscene_half(scene_view)
return sc.Matrix44.get_scale_matrix(iscene_half[0], iscene_half[1], 1.) * \
sc.Matrix44.get_translation_matrix(-1., +1., 0) * \
sc.Matrix44.get_scale_matrix(2./size_ui[0], -2./size_ui[1], 1.)
def get_transform_iscene_from_render(self, scene_view):
iscene_render_half = self.iscene_render_half(scene_view)
return sc.Matrix44.get_scale_matrix(iscene_render_half[0], iscene_render_half[1], 1.)
#====================================================================== 3D world <-> 2D screen conversion
def pick_ray_from_render(self, render_ndc, frustum=None):
if frustum is None:
frustum = self.get_conformed_frustum()
pos = Gf.Vec2d(render_ndc[0],render_ndc[1])
return frustum.ComputePickRay(pos)
"""
From frame space NDC coords example:
x,y = self.conv_render_from_ndc(frame_ndc)
if x is None or x < -1.0 or x > 1.0 or y < -1.0 or y > 1.0:
return None
return get_pick_ray((x,y))
"""
def conv_render_from_world(self, wpt):
""" wpt can be Gd.Vec3*, (x,y,z), single value or list
returns Gf.Vec2d, single value or list NDC coords
"""
view,proj = self.get_camera_view_proj()
mat = view*proj
if isinstance(wpt, list):
wpt_list=wpt
else:
wpt_list=[wpt]
rpt = []
for pt in wpt_list:
r = mat.Transform( Gf.Vec3d(pt[0],pt[1],pt[2]) )
rpt.append(r)
if isinstance(wpt, list):
return rpt
else:
return rpt[0]
def conv_iscene_from_world(self, wpt, scene_view):
""" wpt can be Gd.Vec3*, (x,y,z) or list. Not single value.
returns Gf.Vec2d, single value or list NDC coords
"""
view,proj = self.get_camera_view_proj()
mat = view*proj
if isinstance(wpt, list):
wpt_list=wpt
else:
wpt_list=[wpt]
mul = self.iscene_render_half(scene_view)
spt = []
for pt in wpt_list:
r = mat.Transform( Gf.Vec3d(pt[0],pt[1],pt[2]) )
s = Gf.Vec2d(r[0] * mul[0], r[1] * mul[1])
spt.append(s)
if isinstance(wpt, list):
return spt
else:
return spt[0]
def add_frame_mouse_fn(self, frame, fn, coord_space=0):
"""Called function params:
op:
0=press
1=move
2=release
3=double click
4=mouse wheel
5=mouse hovered (entered) frame
x,y: coordinates inside frame, depending on coord_space:
0=01 space
1=ui space
2=ndc space
3=render space
button:
0=left
1=right
2=middle
mod flags:
1=shift
2=ctrl
4=alt
(6=altGr = ctrl + alt)
0x40000000=unknown during move and release
"""
if not frame in self._frame_mouse_fns:
self._frame_mouse_fns[frame] = set()
fnlist = self._frame_mouse_fns[frame]
if fn in fnlist:
return
fnlist.add(fn)
last_button_pressed = None
def dispatch(op, x,y, button, mod):
for fn in fnlist:
fn(op, x,y, button, mod)
def to_space(x,y):
if coord_space <= 1:
p01 = self.conv_01_from_app_ui((x,y))
if coord_space == 0:
return p01
else:
return self.conv_ui_from_01(p01)
else:
pndc = self.conv_ndc_from_app_ui((x,y))
if coord_space == 2:
return pndc
else:
return self.conv_render_from_ndc(pndc)
def on_mouse_pressed(x,y, button, mod):
nonlocal last_button_pressed
x,y = to_space(x,y)
dispatch(0, x,y, button, mod)
last_button_pressed = button
def on_mouse_moved(x,y, mod, unknown_always_true): #on move: x,y can go outside 0,1
x,y = to_space(x,y)
dispatch(1, x,y, last_button_pressed, mod)
def on_mouse_released(x,y, button, mod):
nonlocal last_button_pressed
x,y = to_space(x,y)
dispatch(2, x,y, button, mod)
last_button_pressed = None
def on_mouse_double_clicked(x,y, button, mod):
x,y = to_space(x,y)
dispatch(3, x,y, button, mod)
def on_mouse_wheel(x,y, mod):
dispatch(4, x,y, None, mod)
def on_mouse_hovered(entered): # x=entered info
dispatch(5, entered, None, None, None)
frame.set_mouse_pressed_fn(on_mouse_pressed)
frame.set_mouse_moved_fn(on_mouse_moved)
frame.set_mouse_released_fn(on_mouse_released)
frame.set_mouse_double_clicked_fn(on_mouse_double_clicked)
frame.set_mouse_wheel_fn(on_mouse_wheel)
frame.set_mouse_hovered_fn(on_mouse_hovered)
def add_frame_size_changed_fn(self, frame, fn):
if not frame in self._frame_size_changed_fns:
def on_frame_size_changed():
if not frame in self._frame_size_changed_fns:
return
for fn in self._frame_size_changed_fns[frame]:
fn()
frame.set_computed_content_size_changed_fn( on_frame_size_changed )
self._frame_size_changed_fns[frame] = set()
fnlist = self._frame_size_changed_fns[frame]
fnlist.add( fn )
def remove_frame_size_changed_fn(self, frame, fn):
if frame in self._frame_size_changed_fns:
fnlist = self._frame_size_changed_fns[frame]
fnlist.discard( fn )
def add_render_changed_fn(self, fn):
"""Call fn handler on render resolution or fill mode changed"""
if self._sub_render_width is None:
def on_render_changed(*args):
""" will render resolution/frame_fill take a frame to reflect """
async def async_func():
await omni.kit.app.get_app().next_update_async()
for fn in self._render_changed_fns:
fn()
asyncio.ensure_future( async_func() )
settings = carb.settings.get_settings()
self._sub_render_width = settings.subscribe_to_node_change_events(SETTING_RENDER_WIDTH, on_render_changed)
self._sub_render_height = settings.subscribe_to_node_change_events(SETTING_RENDER_HEIGHT, on_render_changed)
self._sub_render_fill = settings.subscribe_to_node_change_events(SETTING_RENDER_FILL, on_render_changed)
self._render_changed_fns.add(fn)
def remove_render_changed_fn(self, fn):
if self._sub_render_width is not None:
self._render_changed_fns.discard(fn)
def add_camera_changed_fn(self, fn):
"""Call fn handler when USD camera changes"""
if self._stage_objects_changed is None:
# handler needs to be a method as Register won't hold reference to a local function
listener = Tf.Notice.Register( Usd.Notice.ObjectsChanged, self._on_stage_objects_changed, self.stage)
self._stage_objects_changed = [listener, set()]
val = self._stage_objects_changed
val[1].add(fn)
def _on_stage_objects_changed(self, notice, stage):
if stage != self.stage or self._stage_objects_changed is None:
return
# did active camera change?
cam_path = self.camera_path
for n in notice.GetChangedInfoOnlyPaths():
if n.GetPrimPath() == cam_path: # found camera
for fn in self._stage_objects_changed[1]:
fn()
return
def remove_camera_changed_fn(self, fn):
if self._stage_objects_changed is not None:
val = self._stage_objects_changed
val[1].discard(fn)
def add_changed_fn(self, fn, sub_flags = 1|2|4, frame = None):
"""Call handler on frame, render or camera changes, depending on sub_flags mask.
sub_flags: 1=frame size changed (requires frame param), 2=render changed, 4=camera changed
fn(changed_flag)
"""
self._changed_fns[fn] = sub_flags #overwrite any existing for fn
# add everytime because functions avoid duplicates: but only if not using lambdas!
if sub_flags & 1:
if frame is None:
raise AssertionError("Frame size changed: frame parameter cannot be None")
self.add_frame_size_changed_fn(frame, self._on_frame_changed)
if sub_flags & 2:
self.add_render_changed_fn(self._on_render_changed)
if sub_flags & 4:
self.add_camera_changed_fn(self._on_camera_changed)
def _on_frame_changed(self):
self._on_changed(1)
def _on_render_changed(self):
self._on_changed(2)
def _on_camera_changed(self):
self._on_changed(4)
def _on_changed(self, changed_flag):
for fn, mask in self._changed_fns.items():
if mask & changed_flag:
fn(changed_flag)
def remove_changed_fn(self, fn, frame):
if fn in self._changed_fns:
if self._changed_fns[fn] & 1 and frame is None:
raise AssertionError("Frame size changed: frame parameter cannot be None")
del self._changed_fns[fn]
if not len(self._changed_fns):
if frame is not None:
self.remove_frame_size_changed_fn(frame, self._on_frame_changed)
self.remove_render_changed_fn(self._on_render_changed)
self.remove_camera_changed_fn(self._on_camera_changed)
def add_scene_view_update(self, scene_view):
self._api.add_scene_view(scene_view)
def remove_scene_view_update(self, scene_view):
self._api.remove_scene_view(scene_view)
def register_scene(self, scene_creator,
ext_id_or_name: str):
"""Registers a scene creator into:
VP1: a viewport window, where scene is immediately created
VP2: calls RegisterScene with omni.kit.viewport.registry, to create scene in
current (full window) viewports and any new ones.
scene_creator object created with: scene_creator_class(dict)
VP1 dict = {viewport_api}
VP2 dict = {viewport_api: omni.kit.viewport.window.ViewportAPI,
layer_provider: omni.kit.viewport.window.ViewportLayers,
usd_context_name: str}
"""
if self.is_legacy:
with self._win.get_frame(ext_id_or_name):
scene_view = sc.SceneView()
with scene_view.scene:
sce = scene_creator({"viewport_api": self._api})
# have viewport update our SceneView
self.add_scene_view_update(scene_view)
return [scene_view, sce]
else:
try:
from omni.kit.viewport.registry import RegisterScene
scene_reg = RegisterScene(scene_creator, ext_id_or_name)
return [scene_reg]
except ImportError:
return None
def register_scene_proxy(self, create_fn, destroy_fn, get_visible_fn, set_visible_fn,
ext_id_or_name: str):
lamb = ViewportHelper.SceneCreatorProxy.make_lambda(create_fn, destroy_fn, get_visible_fn, set_visible_fn)
return self.register_scene(lamb, ext_id_or_name)
def unregister_scene(self, scene_reg):
if scene_reg is None or not len(scene_reg):
return
if self.is_legacy:
scene_view = scene_reg[0]
self.remove_scene_view_update(scene_view)
scene_view.destroy()
scene_reg.clear()
class SceneCreatorProxy:
@staticmethod
def make_lambda(create_fn, destroy_fn, get_visible_fn, set_visible_fn):
return lambda vp_args: ViewportHelper.SceneCreatorProxy(vp_args, create_fn, destroy_fn, get_visible_fn, set_visible_fn)
def __init__(self, vp_args: dict,
create_fn, destroy_fn, get_visible_fn, set_visible_fn):
# print("SceneCreatorProxy.__init__", vp_args)
# dict_keys(['usd_context_name', 'layer_provider', 'viewport_api'])
"""@ATTN: a scene may be created in multiple viewports. It's up to the _create_fn() callee to make sure it's
being called in the intended viewport by checking vp_args['viewport_api']"""
self._create_fn = create_fn
self._destroy_fn = destroy_fn
self._get_visible_fn = get_visible_fn
self._set_visible_fn = set_visible_fn
self._create_fn(vp_args)
def destroy(self):
# print("SceneCreatorProxy.destroy")
if self._destroy_fn:
self._destroy_fn()
self._create_fn = None
self._destroy_fn = None
self._get_visible_fn = None
self._set_visible_fn = None
def __del__(self):
self.destroy()
# called from viewport registry
@property
def visible(self):
# print("SceneCreatorProxy.get_visible")
if self._get_visible_fn:
return self._get_visible_fn()
else:
return True
@visible.setter
def visible(self, value: bool):
# print("SceneCreatorProxy.set_visible", value)
if self._set_visible_fn:
return self._set_visible_fn(value)
@property
def picking_enabled(self):
"""Object picking and selection rect."""
if self._is_legacy:
self._win.legacy_window.is_enabled_picking()
else:
# print("picking_enabled only supported for legacy viewport")
return True
@picking_enabled.setter
def picking_enabled(self, enabled):
"""Disables object picking and selection rect."""
if self._is_legacy:
self._win.legacy_window.set_enabled_picking(enabled)
else:
# print("picking_enabled only supported for legacy viewport")
pass
def temp_select_enabled(self, enable_picking):
"""Disables object picking and selection rect until next mouse up.
enable_picking: enable picking for surface snap
"""
if self._is_legacy:
self._win.legacy_window.disable_selection_rect(enable_picking)
else:
# print("temp_select_enabled only supported for legacy viewport")
pass
@property
def manipulating_camera(self):
if self._is_legacy:
return self._win.legacy_window.is_manipulating_camera()
else:
# print("is_manipulating_camera only supported for legacy viewport")
return False
def save_render(self, file_path: str, render_product_path: str = None):
"""Doesn't save any overlaid SceneView drawing"""
vut.capture_viewport_to_file(self._api,
file_path=file_path,
is_hdr=False,
render_product_path=render_product_path)
def info(self, scene_view=None):
out = f"window_name='{self.window_name}' is_legacy={self.is_legacy} usd_context_name='{self.usd_context_name} api_id='{self._api.id}'\n"
out += f"ui_size={self.ui_size} dpi={omni.ui.Workspace.get_dpi_scale()} px_size={self.px_size} ui_size_ratio={self.ui_size_ratio}\n"
out += f"render_size_px={self.render_size_px} render_fill_frame={self.render_fill_frame} render_ratio={self.render_size_ratio}\n"
if scene_view is not None:
out += f"iscene_half={self.iscene_half(scene_view)} iscene_size={self.iscene_size(scene_view)} iscene_render_half={self.iscene_render_half(scene_view)}\n"
out += f"camera_path='{self.camera_path}'\n"
out += f"camera frustrum={self.get_conformed_frustum()}\n"
view,proj = self.get_camera_view_proj()
out += f"camera matrixes: view={view} proj={proj}\n"
out += f"conform_policy={self.get_conform_policy()}\n"
if scene_view is not None:
out += f"scene_view aspect_ratio={scene_view.aspect_ratio_policy}\n"
out += f"fps={self.fps}\n"
return out
"""Examples:
vp = ViewportHelper()
res = vp.attach() # "Viewport" "Viewport Next"
print(f"attach res={res}")
frame = vp.get_frame("id")
#frame.clear()
#with frame:
# with ui.VStack():
# ui.Spacer()
# ui.Label("LABEL", alignment=ui.Alignment.CENTER, style={"font_size": 72})
# ui.Button("TO")
# ui.Spacer()
print (vp.info())
#vp.camera_path = "OmniverseKit_Top" # OmniverseKit_Persp
vp.save_render("c:/tmp/vp.png")
""" | 37,345 | Python | 29.045052 | 166 | 0.578525 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/libs/app_helper.py | """"""
import asyncio, functools, sys
import os.path
import carb
import omni.kit
class AppHelper():
VERSION = 10
SETTING_TRANSFORM_OP = "/app/transform/operation"
def __init__(self, attach=True):
self._app = None
self._settings = None
self._setting_changed = {} # {"setting_path": [subs, set(fn0,fn1,...)], }
self._input = None
self._update_event_sub = None
self._update_event_fns = set()
self._key_action_subs = {} # {"action_name": [sub, [(fn0,fn1), (fn1,fn2), ...]] }
if attach:
res = self.attach()
if not res:
raise AssertionError("Could not attach")
def __del__(self):
self.detach()
def attach(self) -> bool:
self.detach()
self._app = omni.kit.app.get_app() # omni.kit.app
self._app_win = omni.appwindow.get_default_app_window() # omni.appwindow
self._settings = carb.settings.get_settings()
return True
def detach(self):
self._update_event_sub = None
self._update_event_fns.clear()
for v in self._setting_changed.values():
self._settings.unsubscribe_to_change_events(v[0])
self._setting_changed = {}
self._settings = None
if self._input is not None:
for v in self._key_action_subs.values():
self._input.unsubscribe_to_action_events(v[0])
self._key_action_subs = {}
self._input = None
if self._app is not None:
self._app = None
def add_update_event_fn(self, fn, order=0, subscription_name=None):
""" 0=NEW_FRAME """
if self._update_event_sub is None:
def on_update(ev):
for fn in self._update_event_fns:
fn(ev)
self._update_event_sub = self._app.get_update_event_stream().create_subscription_to_pop(on_update,
order=order,
name=subscription_name)
self._update_event_fns.clear()
self._update_event_fns.add(fn)
def remove_update_event_fn(self, fn, event_type=-1):
if self._update_event_sub:
self._update_event_fns.discard(fn)
def add_setting_changed_fn(self, setting_path, fn):
""" fn(value, event_type) """
if not setting_path in self._setting_changed:
def on_changed(item, event_type):
fns = self._setting_changed[setting_path][1]
for fn in fns:
fn(str(item), event_type)
self._setting_changed[setting_path] = [None, set()]
self._setting_changed[setting_path][0] = self._settings.subscribe_to_node_change_events(setting_path, on_changed)
s = self._setting_changed[setting_path][1]
s.add(fn)
def get_setting(self, setting_path):
return str( self._settings.get(setting_path) )
def set_setting(self, setting_path, value):
self._settings.set(setting_path, value)
def add_key_action_fn(self, action_name, key, key_modifiers, on_key_fn, is_key_enabled_fn=None):
""" key_modifiers: 1=shift, 2=ctrl, alt=4"""
if action_name in self._key_action_subs:
sub = self._key_action_subs[action_name]
if not (on_key_fn, is_key_enabled_fn) in sub[1]: # fn pair already there
sub[1].append((on_key_fn, is_key_enabled_fn))
return
if self._input is None:
self._input = carb.input.acquire_input_interface()
set_path = self._app_win.get_action_mapping_set_path()
set = self._input.get_action_mapping_set_by_path(set_path)
string = carb.input.get_string_from_action_mapping_desc(key, key_modifiers)
path = set_path + "/" + action_name + "/0"
self._settings.set_default_string(path, string)
def on_action(action_name, event, *_):
if not event.flags & carb.input.BUTTON_FLAG_PRESSED:
return
if not action_name in self._key_action_subs:
return
try: # avoid keys pressed during camera manipulation
import omni.kit.viewport_legacy
vp = omni.kit.viewport_legacy.get_viewport_interface().get_viewport_window()
if vp.is_manipulating_camera():
return
except Exception:
pass
sub = self._key_action_subs[action_name]
for on_key_fn,is_key_enabled_fn in sub[1]:
if is_key_enabled_fn is not None:
if not is_key_enabled_fn():
continue
on_key_fn()
sub = [self._input.subscribe_to_action_events(set, action_name, functools.partial(on_action, action_name)),
[(on_key_fn, is_key_enabled_fn)]]
self._key_action_subs[action_name] = sub
| 5,108 | Python | 26.320855 | 125 | 0.536022 |
syntway/model_exploder/exts/syntway.model_exploder/syntway/model_exploder/libs/usd_helper.py | """
Notes:
"""
import omni.kit
import omni.usd
from pxr import Gf, Tf, Sdf, Usd, UsdGeom, CameraUtil
from .app_utils import call_after_update
class UsdHelper():
VERSION = 17
STAGE_CHANGED_SUB_PREFIX = "UsdHelper-stage-changed-ev"
def __init__(self, attach=True, stage_opened_refresh=1 | 2):
"""
stage_opened_refresh: resubscribe events when a new stage finishes opening. A mask of:
1: resubscribe add_stage_event_fn handlers
2: resubscribe add_stage_objects_changed_fn handlers
"""
self._ctx = None
self._stage_changed = {} # event_type: [sub, set(fn,fn,...)]
self._stage_objects_changed = None # [listener, set(fn,fn,...)]
self._stage_opened_refresh = stage_opened_refresh
self._stage_opened_refresh_sub = None
if attach:
res = self.attach()
if not res:
raise AssertionError("Could not attach")
def __del__(self):
self.detach()
def attach(self, usd_ctx=None) -> bool:
"""usd_ctx can be a string for context name, or an existing UsdContext."""
self.detach()
if usd_ctx is None:
usd_ctx = ''
if isinstance(usd_ctx, str):
self._ctx = omni.usd.get_context(usd_ctx)
else:
self._ctx = usd_ctx
if self._stage_opened_refresh:
self.add_stage_event_fn(self._on_stage_opened_refresh,
omni.usd.StageEventType.OPENED)
return True
def detach(self):
if self._ctx is not None:
self._ctx = None
if self._stage_objects_changed is not None:
if len(self._stage_objects_changed):
self._stage_objects_changed[0].Revoke()
self._stage_objects_changed = None
self._stage_changed.clear()
self._stage_opened_refresh_sub = None
@property
def context(self):
return self._ctx
@property
def stage(self):
return self._ctx.get_stage()
@property
def stage_state(self) -> omni.usd.StageState:
return self._ctx.get_stage_state()
def is_stage_opened(self) -> bool:
return self.stage_state == omni.usd.StageState.OPENED
@property
def stage_up(self):
up = UsdGeom.GetStageUpAxis(self.stage)
if up == UsdGeom.Tokens.y:
return Gf.Vec3d(0, 1, 0)
elif up == UsdGeom.Tokens.z:
return Gf.Vec3d(0, 0, 1)
else: # UsdGeom.Tokens.x
return Gf.Vec3d(1, 0, 0)
@property
def stage_up_index(self):
up = UsdGeom.GetStageUpAxis(self.stage)
if up == UsdGeom.Tokens.y:
return 1
elif up == UsdGeom.Tokens.z:
return 2
else: # UsdGeom.Tokens.x: illegal
return 0
@property
def timecode(self) -> Usd.TimeCode:
stage = self.stage
"""
if stage.HasAuthoredTimeCodeRange(): -> wrong: a stage might not have timeCodes authored,
but its references may have.
Using Usd.TimeCode.Default() in xform_cache.GetLocalTransformation(prim) won't fetch correct matrices
for time_coded prims
"""
time = omni.timeline.get_timeline_interface().get_current_time()
ret = Usd.TimeCode(omni.usd.get_frame_time_code(time, stage.GetTimeCodesPerSecond()))
# or ret = Usd.TimeCode( time * stage.GetTimeCodesPerSecond() )
return ret
def add_stage_event_fn(self, fn, event_type=-1):
"""
Doesn't depend on open stage and remains after closing-opening.
Arg event_type = -1 to accept all, otherwise a single event of type omni.usd.StageEventType.*: (@Kit103)
0=SAVED
1=SAVE_FAILED
2=OPENING
3=OPENED
4=OPEN_FAILED
5=CLOSING
6=CLOSED
7=SELECTION_CHANGED
8=ASSETS_LOADED
9=ASSETS_LOAD_ABORTED
10=GIZMO_TRACKING_CHANGED
11=MDL_PARAM_LOADED
12=SETTINGS_LOADED
13=SETTINGS_SAVING
14=OMNIGRAPH_START_PLAY
15=OMNIGRAPH_STOP_PLAY
16=SIMULATION_START_PLAY
17=SIMULATION_STOP_PLAY
18=ANIMATION_START_PLAY
19=ANIMATION_STOP_PLAY
20=DIRTY_STATE_CHANGED
"""
event_type = int(event_type)
if event_type not in self._stage_changed:
sub = self._sub_stage_event(event_type)
self._stage_changed[event_type] = [sub, set()]
ch = self._stage_changed[event_type]
ch[1].add(fn)
def _sub_stage_event(self, event_type):
sub_name = UsdHelper.STAGE_CHANGED_SUB_PREFIX + str(event_type)
lamb = lambda ev: self._on_stage_event(ev, event_type)
if event_type == -1:
sub = self._ctx.get_stage_event_stream().create_subscription_to_pop(lamb,
name=sub_name)
else:
sub = self._ctx.get_stage_event_stream().create_subscription_to_pop_by_type(event_type,
lamb,
name=sub_name)
return sub
def _on_stage_event(self, ev, target_event_type):
# print("_on_stage_event", ev.type, target_event_type)
if target_event_type in self._stage_changed:
for fn in self._stage_changed[target_event_type][1]:
fn(ev)
def remove_stage_event_fn(self, fn, event_type=-1):
"""
Don't call from fn or will get:
RuntimeError: Set changed size during iteration
"""
if event_type in self._stage_changed:
ch = self._stage_changed[event_type]
ch[1].discard(fn)
def _on_stage_opened_refresh(self, ev):
# print("_on_stage_opened_refresh", ev.type)
def resub():
if self._stage_opened_refresh & 1:
# print("resub _stage_changed")
for event_type in self._stage_changed:
ch = self._stage_changed[event_type]
ch[0] = self._sub_stage_event(event_type)
if self._stage_opened_refresh & 2 and self._stage_objects_changed is not None:
# print("resub _stage_objects_changed")
self._stage_objects_changed[0] = self._sub_stage_objects_changed()
call_after_update(resub)
def add_stage_objects_changed_fn(self, fn):
# print("add_stage_objects_changed_fn")
"""
Depends on stage: if closed must call remove_stage_objects_changed_fn(), then on stage opened call add_stage_objects_changed_fn again.
From https://graphics.pixar.com/usd/dev/api/class_usd_notice_1_1_objects_changed.html:
Usd.Notice.ObjectsChanged: Object changes, either "resync" or "changed-info".
"Resyncs" are potentially structural changes that invalidate entire subtrees of UsdObjects (including prims and properties).
For example, if the path "/foo" is resynced, then all subpaths like "/foo/bar" and "/foo/bar.baz" may be arbitrarily changed.
When a prim is resynced, say "/foo/bar", it might have been created or destroyed. In that case "/foo"'s list of children will have changed, but we do not consider "/foo" to be resynced. If we did, it would mean clients would have to consider all of "/foo/bar"'s siblings (and their descendants) to be resynced which might be egregious overinvalidation.
In contrast, "changed-info" means that a nonstructural change has occurred, like an attribute value change or a value change to a metadata field not related to composition.
This notice provides API for two client use-cases. Clients interested in testing whether specific objects are affected by the changes should use the AffectedObject()
method (and the ResyncedObject() and ChangedInfoOnly() methods).
Clients that wish to reason about all changes as a whole should use the GetResyncedPaths() and GetChangedInfoOnlyPaths() methods.
fn(notice: Tf.notice) can call notice.GetChangedInfoOnlyPaths()
"""
if self._stage_objects_changed is None:
# handler needs to be a method as Register won't hold reference to a local function
listener = self._sub_stage_objects_changed()
self._stage_objects_changed = [listener, set()]
val = self._stage_objects_changed
val[1].add(fn)
# print("add")
def _sub_stage_objects_changed(self):
return Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_stage_objects_changed, self.stage)
def _on_stage_objects_changed(self, notice, stage):
if stage != self.stage or self._stage_objects_changed is None:
return
for fn in self._stage_objects_changed[1]:
fn(notice)
def remove_stage_objects_changed_fn(self, fn):
# print("remove_stage_objects_changed_fn")
if self._stage_objects_changed is not None:
val = self._stage_objects_changed
val[1].discard(fn)
# print("discard")
def get_selected_prim_paths(self):
sel = self.get_selection()
return sel.get_selected_prim_paths()
def set_selected_prim_paths(self, paths, expand_in_stage=False):
sel = self.get_selection()
sel.set_selected_prim_paths(paths, expand_in_stage)
def get_selection(self):
return self._ctx.get_selection()
def set_pickable(self, enabled, prim_path="/"):
"""If disabled, Kit will still display selection rects but nothing will be selected."""
self._ctx.set_pickable(prim_path, enabled)
"""
Timeline events
stream = omni.timeline.get_timeline_interface().get_timeline_event_stream()
self._timeline_sub = stream.create_subscription_to_pop(self._on_timeline_event)
0=PLAY
1=PAUSE
2=STOP
3=CURRENT_TIME_CHANGED
4=CURRENT_TIME_TICKED
5=LOOP_MODE_CHANGED
6=START_TIME_CHANGED
7=END_TIME_CHANGED
8=TIME_CODE_PER_SECOND_CHANGED
9=AUTO_UPDATE_CHANGED
10=PREROLLING_CHANGED
""" | 10,223 | Python | 28.80758 | 360 | 0.60002 |
syntway/model_exploder/exts/syntway.model_exploder/config/extension.toml | [package]
# Semantic versioning: https://semver.org/
version = "0.9.5"
title = "Model Exploder"
description="Separate model parts to view their relationship and how they fit together."
authors = ["Syntway"]
category = "Tools"
keywords = ["kit", "tool", "tools", "util", "utils", "explode model", "exploded view"]
# repository = "https://github.com/syntway/model_exploder"
icon = "data/icons/ext.png"
preview_image = "data/preview.png"
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.viewport.utility" = {}
"omni.ui.scene" = {}
"omni.usd" = {}
[[python.module]]
name = "syntway.model_exploder"
| 659 | TOML | 20.999999 | 88 | 0.68437 |
syntway/model_exploder/exts/syntway.model_exploder/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.9.5] - 2024-04-12
### Changed
- Fix deprecated SDF.Begin/EndChangeBlock() reference.
- Bump version.
## [0.9.4] - 2022-12-07
### Changed
- Moved menu entry to the Window top-level menu, because some apps hide the Tools menu, like Code.
## [0.9.3] - 2022-12-04
### Changed
- New UiPal for simpler color handling. Changed styles and supporting code to use it.
- ReadMe doc updated.
## [0.9.2] - 2022-11-12
### Changed
- Compatible with the multiple viewports of Create 2022.3. The initial bounds and center manipulator work in the viewport which is active when the tool window opens.
- Initial Bounds Visibility displays in mid-grey to be visible in bright backgrounds.
- Info button link changed to Syntway's website.
## [0.9.1] - 2022-10-29
### Added
- First public release.
| 968 | Markdown | 32.413792 | 165 | 0.722107 |
syntway/model_exploder/exts/syntway.model_exploder/docs/README.md | # Model Exploder Tool
Model Exploder separates a 3D model into its parts for a better view of their relationship and how they fit together.
Model separation is done as if by a small controlled explosion emanating from its center. This is often known as an exploded-view of the model.
Exploded-views can be used to understand a model from its components and can also be used to create drawings for parts catalogs or assembly/maintenance/instruction information.
## Features
- Easy to use: select a model, click the Use button and move the Distance slider.
- Includes several ways to explode the model around a central point, axis or plane.
- Interactive editing of the explosion center: just drag the "Center" manipulator in the viewport.
- Works with meshes, USD Shapes, references/payloads. Point instances and skeletons are moved as a whole.
- Adds Undo-Redo state when applying changes.
- Works with NVIDIA's Omniverse Create, Code 2022+ or any other Kit-based apps. Compatible with multiple viewports and with the legacy viewport of older Omniverse versions.
### Tips
- Model Exploder is available in the Window menu.
- Click the ( i ) button for help and more information.
- On complex models, the first interaction with the Distance slider might take a few seconds - next ones are much faster.
- If model parts do not separate and remain joined to each other:
- Make sure model is divided in parts (meshes, USD shapes, etc), as this tools works by moving those parts.
- With the Distance slider away from its leftmost position, move the Center manipulator in the viewport into the middle of the parts group.
- Separate the group of "stuck" parts before separating the rest of the model.
- The initial bounds preview and center manipulator work in the active (last used) viewport. To change viewports, close the Model Exploder window and open again after using the new viewport.
## Credits
This tool is developed by Syntway, the VR/Metaverse tools division of FaronStudio: www.syntway.com
Uses icons from SVG Repo: www.svgrepo.com
3D model used in the preview snapshot is from mdesigns100: 3dexport.com/free-3dmodel-residential-building-model-296192.htm
| 2,175 | Markdown | 61.171427 | 190 | 0.788506 |
NVIDIA-Omniverse/OmniIsaacGymEnvs/README.md | # Omniverse Isaac Gym Reinforcement Learning Environments for Isaac Sim
## About this repository
This repository contains Reinforcement Learning examples that can be run with the latest release of [Isaac Sim](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html). RL examples are trained using PPO from [rl_games](https://github.com/Denys88/rl_games) library and examples are built on top of Isaac Sim's `omni.isaac.core` and `omni.isaac.gym` frameworks.
Please see [release notes](docs/release_notes.md) for the latest updates.
<img src="https://user-images.githubusercontent.com/34286328/171454189-6afafbff-bb61-4aac-b518-24646007cb9f.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184172037-cdad9ee8-f705-466f-bbde-3caa6c7dea37.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/171454182-0be1b830-bceb-4cfd-93fb-e1eb8871ec68.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/171454193-e027885d-1510-4ef4-b838-06b37f70c1c7.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184174894-03767aa0-936c-4bfe-bbe9-a6865f539bb4.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184168200-152567a8-3354-4947-9ae0-9443a56fee4c.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184176312-df7d2727-f043-46e3-b537-48a583d321b9.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184178817-9c4b6b3c-c8a2-41fb-94be-cfc8ece51d5d.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/171454160-8cb6739d-162a-4c84-922d-cda04382633f.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/171454176-ce08f6d0-3087-4ecc-9273-7d30d8f73f6d.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184170040-3f76f761-e748-452e-b8c8-3cc1c7c8cb98.gif" width="614" height="307"/>
## System Requirements
It is recommended to have at least 32GB RAM and a GPU with at least 12GB VRAM. For detailed system requirements, please visit the [Isaac Sim System Requirements](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/requirements.html#system-requirements) page. Please refer to the [Troubleshooting](docs/troubleshoot.md#memory-consumption) page for a detailed breakdown of memory consumption.
## Installation
Follow the Isaac Sim [documentation](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html) to install the latest Isaac Sim release.
*Examples in this repository rely on features from the most recent Isaac Sim release. Please make sure to update any existing Isaac Sim build to the latest release version, 2023.1.1, to ensure examples work as expected.*
Once installed, this repository can be used as a python module, `omniisaacgymenvs`, with the python executable provided in Isaac Sim.
To install `omniisaacgymenvs`, first clone this repository:
```bash
git clone https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs.git
```
Once cloned, locate the [python executable in Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_python.html). By default, this should be `python.sh`. We will refer to this path as `PYTHON_PATH`.
To set a `PYTHON_PATH` variable in the terminal that links to the python executable, we can run a command that resembles the following. Make sure to update the paths to your local path.
```
For Linux: alias PYTHON_PATH=~/.local/share/ov/pkg/isaac_sim-*/python.sh
For Windows: doskey PYTHON_PATH=C:\Users\user\AppData\Local\ov\pkg\isaac_sim-*\python.bat $*
For IsaacSim Docker: alias PYTHON_PATH=/isaac-sim/python.sh
```
Install `omniisaacgymenvs` as a python module for `PYTHON_PATH`:
```bash
PYTHON_PATH -m pip install -e .
```
The following error may appear during the initial installation. This error is harmless and can be ignored.
```
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
```
### Running the examples
*Note: All commands should be executed from `OmniIsaacGymEnvs/omniisaacgymenvs`.*
To train your first policy, run:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Cartpole
```
An Isaac Sim app window should be launched. Once Isaac Sim initialization completes, the Cartpole scene will be constructed and simulation will start running automatically. The process will terminate once training finishes.
Note that by default, we show a Viewport window with rendering, which slows down training. You can choose to close the Viewport window during training for better performance. The Viewport window can be re-enabled by selecting `Window > Viewport` from the top menu bar.
To achieve maximum performance, launch training in `headless` mode as follows:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant headless=True
```
#### A Note on the Startup Time of the Simulation
Some of the examples could take a few minutes to load because the startup time scales based on the number of environments. The startup time will continually
be optimized in future releases.
### Extension Workflow
The extension workflow provides a simple user interface for creating and launching RL tasks. To launch Isaac Sim for the extension workflow, run:
```bash
./<isaac_sim_root>/isaac-sim.gym.sh --ext-folder </parent/directory/to/OIGE>
```
Note: `isaac_sim_root` should be located in the same directory as `python.sh`.
The UI window can be activated from `Isaac Examples > RL Examples` by navigating the top menu bar.
For more details on the extension workflow, please refer to the [documentation](docs/framework/extension_workflow.md).
### Loading trained models // Checkpoints
Checkpoints are saved in the folder `runs/EXPERIMENT_NAME/nn` where `EXPERIMENT_NAME`
defaults to the task name, but can also be overridden via the `experiment` argument.
To load a trained checkpoint and continue training, use the `checkpoint` argument:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=runs/Ant/nn/Ant.pth
```
To load a trained checkpoint and only perform inference (no training), pass `test=True`
as an argument, along with the checkpoint name. To avoid rendering overhead, you may
also want to run with fewer environments using `num_envs=64`:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=runs/Ant/nn/Ant.pth test=True num_envs=64
```
Note that if there are special characters such as `[` or `=` in the checkpoint names,
you will need to escape them and put quotes around the string. For example,
`checkpoint="runs/Ant/nn/last_Antep\=501rew\[5981.31\].pth"`
We provide pre-trained checkpoints on the [Nucleus](https://docs.omniverse.nvidia.com/nucleus/latest/index.html) server under `Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints`. Run the following command
to launch inference with pre-trained checkpoint:
Localhost (To set up localhost, please refer to the [Isaac Sim installation guide](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html)):
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth test=True num_envs=64
```
Production server:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth test=True num_envs=64
```
When running with a pre-trained checkpoint for the first time, we will automatically download the checkpoint file to `omniisaacgymenvs/checkpoints`. For subsequent runs, we will re-use the file that has already been downloaded, and will not overwrite existing checkpoints with the same name in the `checkpoints` folder.
## Runing from Docker
Latest Isaac Sim Docker image can be found on [NGC](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim). A utility script is provided at `docker/run_docker.sh` to help initialize this repository and launch the Isaac Sim docker container. The script can be run with:
```bash
./docker/run_docker.sh
```
Then, training can be launched from the container with:
```bash
/isaac-sim/python.sh scripts/rlgames_train.py headless=True task=Ant
```
To run the Isaac Sim docker with UI, use the following script:
```bash
./docker/run_docker_viewer.sh
```
Then, training can be launched from the container with:
```bash
/isaac-sim/python.sh scripts/rlgames_train.py task=Ant
```
To avoid re-installing OIGE each time a container is launched, we also provide a dockerfile that can be used to build an image with OIGE installed. To build the image, run:
```bash
docker build -t isaac-sim-oige -f docker/dockerfile .
```
Then, start a container with the built image:
```bash
./docker/run_dockerfile.sh
```
Then, training can be launched from the container with:
```bash
/isaac-sim/python.sh scripts/rlgames_train.py task=Ant headless=True
```
### Isaac Sim Automator
Cloud instances for AWS, Azure, or GCP can be setup using [IsaacSim Automator](https://github.com/NVIDIA-Omniverse/IsaacSim-Automator/tree/main#omniverse-isaac-gym).
## Livestream
OmniIsaacGymEnvs supports livestream through the [Omniverse Streaming Client](https://docs.omniverse.nvidia.com/app_streaming-client/app_streaming-client/overview.html). To enable this feature, add the commandline argument `enable_livestream=True`:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant headless=True enable_livestream=True
```
Connect from the Omniverse Streaming Client once the SimulationApp has been created. Note that enabling livestream is equivalent to training with the viewer enabled, thus the speed of training/inferencing will decrease compared to running in headless mode.
## Training Scripts
All scripts provided in `omniisaacgymenvs/scripts` can be launched directly with `PYTHON_PATH`.
To test out a task without RL in the loop, run the random policy script with:
```bash
PYTHON_PATH scripts/random_policy.py task=Cartpole
```
This script will sample random actions from the action space and apply these actions to your task without running any RL policies. Simulation should start automatically after launching the script, and will run indefinitely until terminated.
To run a simple form of PPO from `rl_games`, use the single-threaded training script:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Cartpole
```
This script creates an instance of the PPO runner in `rl_games` and automatically launches training and simulation. Once training completes (the total number of iterations have been reached), the script will exit. If running inference with `test=True checkpoint=<path/to/checkpoint>`, the script will run indefinitely until terminated. Note that this script will have limitations on interaction with the UI.
### Configuration and command line arguments
We use [Hydra](https://hydra.cc/docs/intro/) to manage the config.
Common arguments for the training scripts are:
* `task=TASK` - Selects which task to use. Any of `AllegroHand`, `Ant`, `Anymal`, `AnymalTerrain`, `BallBalance`, `Cartpole`, `CartpoleCamera`, `Crazyflie`, `FactoryTaskNutBoltPick`, `FactoryTaskNutBoltPlace`, `FactoryTaskNutBoltScrew`, `FrankaCabinet`, `FrankaDeformable`, `Humanoid`, `Ingenuity`, `Quadcopter`, `ShadowHand`, `ShadowHandOpenAI_FF`, `ShadowHandOpenAI_LSTM` (these correspond to the config for each environment in the folder `omniisaacgymenvs/cfg/task`)
* `train=TRAIN` - Selects which training config to use. Will automatically default to the correct config for the environment (ie. `<TASK>PPO`).
* `num_envs=NUM_ENVS` - Selects the number of environments to use (overriding the default number of environments set in the task config).
* `seed=SEED` - Sets a seed value for randomization, and overrides the default seed in the task config
* `pipeline=PIPELINE` - Which API pipeline to use. Defaults to `gpu`, can also set to `cpu`. When using the `gpu` pipeline, all data stays on the GPU. When using the `cpu` pipeline, simulation can run on either CPU or GPU, depending on the `sim_device` setting, but a copy of the data is always made on the CPU at every step.
* `sim_device=SIM_DEVICE` - Device used for physics simulation. Set to `gpu` (default) to use GPU and to `cpu` for CPU.
* `device_id=DEVICE_ID` - Device ID for GPU to use for simulation and task. Defaults to `0`. This parameter will only be used if simulation runs on GPU.
* `rl_device=RL_DEVICE` - Which device / ID to use for the RL algorithm. Defaults to `cuda:0`, and follows PyTorch-like device syntax.
* `multi_gpu=MULTI_GPU` - Whether to train using multiple GPUs. Defaults to `False`. Note that this option is only available with `rlgames_train.py`.
* `test=TEST`- If set to `True`, only runs inference on the policy and does not do any training.
* `checkpoint=CHECKPOINT_PATH` - Path to the checkpoint to load for training or testing.
* `headless=HEADLESS` - Whether to run in headless mode.
* `enable_livestream=ENABLE_LIVESTREAM` - Whether to enable Omniverse streaming.
* `experiment=EXPERIMENT` - Sets the name of the experiment.
* `max_iterations=MAX_ITERATIONS` - Sets how many iterations to run for. Reasonable defaults are provided for the provided environments.
* `warp=WARP` - If set to True, launch the task implemented with Warp backend (Note: not all tasks have a Warp implementation).
* `kit_app=KIT_APP` - Specifies the absolute path to the kit app file to be used.
Hydra also allows setting variables inside config files directly as command line arguments. As an example, to set the minibatch size for a rl_games training run, you can use `train.params.config.minibatch_size=64`. Similarly, variables in task configs can also be set. For example, `task.env.episodeLength=100`.
#### Hydra Notes
Default values for each of these are found in the `omniisaacgymenvs/cfg/config.yaml` file.
The way that the `task` and `train` portions of the config works are through the use of config groups.
You can learn more about how these work [here](https://hydra.cc/docs/tutorials/structured_config/config_groups/)
The actual configs for `task` are in `omniisaacgymenvs/cfg/task/<TASK>.yaml` and for `train` in `omniisaacgymenvs/cfg/train/<TASK>PPO.yaml`.
In some places in the config you will find other variables referenced (for example,
`num_actors: ${....task.env.numEnvs}`). Each `.` represents going one level up in the config hierarchy.
This is documented fully [here](https://omegaconf.readthedocs.io/en/latest/usage.html#variable-interpolation).
### Tensorboard
Tensorboard can be launched during training via the following command:
```bash
PYTHON_PATH -m tensorboard.main --logdir runs/EXPERIMENT_NAME/summaries
```
## WandB support
You can run (WandB)[https://wandb.ai/] with OmniIsaacGymEnvs by setting `wandb_activate=True` flag from the command line. You can set the group, name, entity, and project for the run by setting the `wandb_group`, `wandb_name`, `wandb_entity` and `wandb_project` arguments. Make sure you have WandB installed in the Isaac Sim Python executable with `PYTHON_PATH -m pip install wandb` before activating.
## Training with Multiple GPUs
To train with multiple GPUs, use the following command, where `--proc_per_node` represents the number of available GPUs:
```bash
PYTHON_PATH -m torch.distributed.run --nnodes=1 --nproc_per_node=2 scripts/rlgames_train.py headless=True task=Ant multi_gpu=True
```
## Multi-Node Training
To train across multiple nodes/machines, it is required to launch an individual process on each node.
For the master node, use the following command, where `--proc_per_node` represents the number of available GPUs, and `--nnodes` represents the number of nodes:
```bash
PYTHON_PATH -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=0 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=localhost:5555 scripts/rlgames_train.py headless=True task=Ant multi_gpu=True
```
Note that the port (`5555`) can be replaced with any other available port.
For non-master nodes, use the following command, replacing `--node_rank` with the index of each machine:
```bash
PYTHON_PATH -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=1 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=ip_of_master_machine:5555 scripts/rlgames_train.py headless=True task=Ant multi_gpu=True
```
For more details on multi-node training with PyTorch, please visit [here](https://pytorch.org/tutorials/intermediate/ddp_series_multinode.html). As mentioned in the PyTorch documentation, "multinode training is bottlenecked by inter-node communication latencies". When this latency is high, it is possible multi-node training will perform worse than running on a single node instance.
## Tasks
Source code for tasks can be found in `omniisaacgymenvs/tasks`.
Each task follows the frameworks provided in `omni.isaac.core` and `omni.isaac.gym` in Isaac Sim.
Refer to [docs/framework/framework.md](docs/framework/framework.md) for how to create your own tasks.
Full details on each of the tasks available can be found in the [RL examples documentation](docs/examples/rl_examples.md).
## Demo
We provide an interactable demo based on the `AnymalTerrain` RL example. In this demo, you can click on any of
the ANYmals in the scene to go into third-person mode and manually control the robot with your keyboard as follows:
- `Up Arrow`: Forward linear velocity command
- `Down Arrow`: Backward linear velocity command
- `Left Arrow`: Leftward linear velocity command
- `Right Arrow`: Rightward linear velocity command
- `Z`: Counterclockwise yaw angular velocity command
- `X`: Clockwise yaw angular velocity command
- `C`: Toggles camera view between third-person and scene view while maintaining manual control
- `ESC`: Unselect a selected ANYmal and yields manual control
Launch this demo with the following command. Note that this demo limits the maximum number of ANYmals in the scene to 128.
```
PYTHON_PATH scripts/rlgames_demo.py task=AnymalTerrain num_envs=64 checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal_terrain.pth
```
<img src="https://user-images.githubusercontent.com/34286328/184688654-6e7899b2-5847-4184-8944-2a96b129b1ff.gif" width="600" height="300"/>
| 18,653 | Markdown | 55.871951 | 469 | 0.777408 |
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/cfg/config.yaml |
# Task name - used to pick the class to load
task_name: ${task.name}
# experiment name. defaults to name of training config
experiment: ''
# if set to positive integer, overrides the default number of environments
num_envs: ''
# seed - set to -1 to choose random seed
seed: 42
# set to True for deterministic performance
torch_deterministic: False
# set the maximum number of learning iterations to train for. overrides default per-environment setting
max_iterations: ''
## Device config
physics_engine: 'physx'
# whether to use cpu or gpu pipeline
pipeline: 'gpu'
# whether to use cpu or gpu physx
sim_device: 'gpu'
# used for gpu simulation only - device id for running sim and task if pipeline=gpu
device_id: 0
# device to run RL
rl_device: 'cuda:0'
# multi-GPU training
multi_gpu: False
## PhysX arguments
num_threads: 4 # Number of worker threads used by PhysX - for CPU PhysX only.
solver_type: 1 # 0: pgs, 1: tgs
# RLGames Arguments
# test - if set, run policy in inference mode (requires setting checkpoint to load)
test: False
# used to set checkpoint path
checkpoint: ''
# evaluate checkpoint
evaluation: False
# disables rendering
headless: False
# enables native livestream
enable_livestream: False
# timeout for MT script
mt_timeout: 300
# enables viewport recording
enable_recording: False
# interval between video recordings (in steps)
recording_interval: 2000
# length of the recorded video (in steps)
recording_length: 100
# fps for writing recorded video
recording_fps: 30
# directory to save recordings in
recording_dir: ''
wandb_activate: False
wandb_group: ''
wandb_name: ${train.params.config.name}
wandb_entity: ''
wandb_project: 'omniisaacgymenvs'
# path to a kit app file
kit_app: ''
# Warp
warp: False
# set default task and default training config based on task
defaults:
- _self_
- task: Cartpole
- train: ${task}PPO
- override hydra/job_logging: disabled
# set the directory where the output files get saved
hydra:
output_subdir: null
run:
dir: .
| 2,007 | YAML | 22.348837 | 103 | 0.744893 |
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/scripts/random_policy.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import gym
import hydra
from omegaconf import DictConfig
import os
import time
import numpy as np
import torch
import omniisaacgymenvs
from omniisaacgymenvs.envs.vec_env_rlgames import VecEnvRLGames
from omniisaacgymenvs.utils.config_utils.path_utils import get_experience
from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import *
from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from omniisaacgymenvs.utils.task_util import initialize_task
@hydra.main(version_base=None, config_name="config", config_path="../cfg")
def parse_hydra_configs(cfg: DictConfig):
cfg_dict = omegaconf_to_dict(cfg)
print_dict(cfg_dict)
headless = cfg.headless
render = not headless
enable_viewport = "enable_cameras" in cfg.task.sim and cfg.task.sim.enable_cameras
# select kit app file
experience = get_experience(headless, cfg.enable_livestream, enable_viewport, cfg.enable_recording, cfg.kit_app)
env = VecEnvRLGames(
headless=headless,
sim_device=cfg.device_id,
enable_livestream=cfg.enable_livestream,
enable_viewport=enable_viewport or cfg.enable_recording,
experience=experience
)
# parse experiment directory
module_path = os.path.abspath(os.path.join(os.path.dirname(omniisaacgymenvs.__file__)))
experiment_dir = os.path.join(module_path, "runs", cfg.train.params.config.name)
# use gym RecordVideo wrapper for viewport recording
if cfg.enable_recording:
if cfg.recording_dir == '':
videos_dir = os.path.join(experiment_dir, "videos")
else:
videos_dir = cfg.recording_dir
video_interval = lambda step: step % cfg.recording_interval == 0
video_length = cfg.recording_length
env.is_vector_env = True
if env.metadata is None:
env.metadata = {"render_modes": ["rgb_array"], "render_fps": cfg.recording_fps}
else:
env.metadata["render_modes"] = ["rgb_array"]
env.metadata["render_fps"] = cfg.recording_fps
env = gym.wrappers.RecordVideo(
env, video_folder=videos_dir, step_trigger=video_interval, video_length=video_length
)
# sets seed. if seed is -1 will pick a random one
from omni.isaac.core.utils.torch.maths import set_seed
cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic)
cfg_dict["seed"] = cfg.seed
task = initialize_task(cfg_dict, env)
num_frames = 0
first_frame = True
prev_time = time.time()
while env.simulation_app.is_running():
if env.world.is_playing():
if first_frame:
env.reset()
prev_time = time.time()
first_frame = False
# get upper and lower bounds of action space, sample actions randomly on this interval
action_high = env.action_space.high[0]
action_low = env.action_space.low[0]
actions = (action_high - action_low) * torch.rand(env.num_envs, env.action_space.shape[0], device=task.rl_device) - action_high
if time.time() - prev_time >= 1:
print("FPS:", num_frames, "FPS * num_envs:", env.num_envs * num_frames)
num_frames = 0
prev_time = time.time()
else:
num_frames += 1
env.step(actions)
else:
env.world.step(render=render)
env.simulation_app.close()
if __name__ == "__main__":
parse_hydra_configs()
| 5,069 | Python | 38.92126 | 139 | 0.688301 |
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/framework/limitations.md | ### API Limitations
#### omni.isaac.core Setter APIs
Setter APIs in omni.isaac.core for ArticulationView, RigidPrimView, and RigidContactView should only be called once per simulation step for
each view instance per API. This means that for use cases where multiple calls to the same setter API from the same view instance is required,
users will need to cache the states to be set for intermmediate calls, and make only one call to the setter API prior to stepping physics with
the complete buffer containing all cached states.
If multiple calls to the same setter API from the same view object are made within the simulation step,
subsequent calls will override the states that have been set by prior calls to the same API,
voiding the previous calls to the API. The API can be called again once a simulation step is made.
For example, the below code will override states.
```python
my_view.set_world_poses(positions=[[0, 0, 1]], orientations=[[1, 0, 0, 0]], indices=[0])
# this call will void the previous call
my_view.set_world_poses(positions=[[0, 1, 1]], orientations=[[1, 0, 0, 0]], indices=[1])
my_world.step()
```
Instead, the below code should be used.
```python
my_view.set_world_poses(positions=[[0, 0, 1], [0, 1, 1]], orientations=[[1, 0, 0, 0], [1, 0, 0, 0]], indices=[0, 1])
my_world.step()
```
#### omni.isaac.core Getter APIs
Getter APIs for cloth simulation may return stale states when used with the GPU pipeline. This is because the physics simulation requires a simulation step
to occur in order to refresh the GPU buffers with new states. Therefore, when a getter API is called after a setter API before a
simulation step, the states returned from the getter API may not reflect the values that were set using the setter API.
For example:
```python
my_view.set_world_positions(positions=[[0, 0, 1]], indices=[0])
# Values may be stale when called before step
positions = my_view.get_world_positions() # positions may not match [[0, 0, 1]]
my_world.step()
# Values will be updated when called after step
positions = my_view.get_world_positions() # positions will reflect the new states
```
#### Performing Resets
When resetting the states of actors, impulses generated by previous target or effort controls
will continue to be carried over from the previous states in simulation.
Therefore, depending on the time step, the masses of the objects, and the magnitude of the impulses,
the difference between the desired reset state and the observed first state after reset can be large.
To eliminate this issue, users should also reset any position/velocity targets or effort controllers
to the reset state or zero state when resetting actor states. For setting joint positions and velocities
using the omni.isaac.core ArticulationView APIs, position targets and velocity targets will
automatically be set to the same states as joint positions and velocities.
#### Massless Links
It may be helpful in some scenarios to introduce dummy bodies into articulations for
retrieving transformations at certain locations of the articulation. Although it is possible
to introduce rigid bodies with no mass and colliders APIs and attach them to the articulation
with fixed joints, this can sometimes cause physics instabilities in simulation. To prevent
instabilities from occurring, it is recommended to add a dummy geometry to the rigid body
and include both Mass and Collision APIs. The mass of the geometry can be set to a very
small value, such as 0.0001, to avoid modifying physical behaviors of the articulation.
Similarly, we can also disable collision on the Collision API of the geometry to preserve
contact behavior of the articulation. | 3,685 | Markdown | 52.420289 | 155 | 0.775577 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/README.md | # DEPRECATED
This repo has been deprecated. Please see [NVIDIA-Omniverse/blender_omniverse_addons](https://github.com/NVIDIA-Omniverse/blender_omniverse_addons)
| 164 | Markdown | 31.999994 | 148 | 0.804878 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/__init__.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
bl_info = {
"name": "Omni Panel",
"author": "NVIDIA Corporation",
"version": (1, 0, 0),
"blender": (3, 0, 0),
"location": "View3D > Toolbar > Omniverse",
"description": "Nvidia Omniverse bake materials for export to usd",
"warning": "",
"doc_url": "",
"category": "Omniverse",
}
import bpy
#Import classes
from .material_bake.operators import (OBJECT_OT_omni_bake_mapbake,
OBJECT_OT_omni_bake_bgbake_status, OBJECT_OT_omni_bake_bgbake_import, OBJECT_OT_omni_bake_bgbake_clear)
from .ui import (OBJECT_PT_omni_bake_panel, OmniBakePreferences)
from .particle_bake.operators import(MyProperties, PARTICLES_OT_omni_hair_bake)
#Classes list for register
#List of all classes that will be registered
classes = ([OBJECT_OT_omni_bake_mapbake, OBJECT_PT_omni_bake_panel, OmniBakePreferences, OBJECT_OT_omni_bake_bgbake_status,
OBJECT_OT_omni_bake_bgbake_import, OBJECT_OT_omni_bake_bgbake_clear, MyProperties, PARTICLES_OT_omni_hair_bake])
def ShowMessageBox(message = "", title = "Message Box", icon = 'INFO'):
def draw(self, context):
self.layout.label(text=message)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
#---------------------UPDATE FUNCTIONS--------------------------------------------
def prepmesh_update(self, context):
if context.scene.prepmesh == False:
context.scene.hidesourceobjects = False
else:
context.scene.hidesourceobjects = True
def texture_res_update(self, context):
if context.scene.texture_res == "0.5k":
context.scene.imgheight = 1024/2
context.scene.imgwidth = 1024/2
context.scene.render.bake.margin = 6
elif context.scene.texture_res == "1k":
context.scene.imgheight = 1024
context.scene.imgwidth = 1024
context.scene.render.bake.margin = 10
elif context.scene.texture_res == "2k":
context.scene.imgheight = 1024*2
context.scene.imgwidth = 1024*2
context.scene.render.bake.margin = 14
elif context.scene.texture_res == "4k":
context.scene.imgheight = 1024*4
context.scene.imgwidth = 1024*4
context.scene.render.bake.margin = 20
elif context.scene.texture_res == "8k":
context.scene.imgheight = 1024*8
context.scene.imgwidth = 1024*8
context.scene.render.bake.margin = 32
def newUVoption_update(self, context):
if bpy.context.scene.newUVoption == True:
bpy.context.scene.prefer_existing_sbmap = False
def all_maps_update(self,context):
bpy.context.scene.selected_col = True
bpy.context.scene.selected_metal = True
bpy.context.scene.selected_rough = True
bpy.context.scene.selected_normal = True
bpy.context.scene.selected_trans = True
bpy.context.scene.selected_transrough = True
bpy.context.scene.selected_emission = True
bpy.context.scene.selected_specular = True
bpy.context.scene.selected_alpha = True
bpy.context.scene.selected_sss = True
bpy.context.scene.selected_ssscol = True
#-------------------END UPDATE FUNCTIONS----------------------------------------------
def register():
#Register classes
global classes
for cls in classes:
bpy.utils.register_class(cls)
global bl_info
version = bl_info["version"]
version = str(version[0]) + str(version[1]) + str(version[2])
OBJECT_PT_omni_bake_panel.version = f"{str(version[0])}.{str(version[1])}.{str(version[2])}"
#Global variables
des = "Texture Resolution"
bpy.types.Scene.texture_res = bpy.props.EnumProperty(name="Texture Resolution", default="1k", description=des, items=[
("0.5k", "0.5k", f"Texture Resolution of {1024/2} x {1024/2}"),
("1k", "1k", f"Texture Resolution of 1024 x 1024"),
("2k", "2k", f"Texture Resolution of {1024*2} x {1024*2}"),
("4k", "4k", f"Texture Resolution of {1024*4} x {1024*4}"),
("8k", "8k", f"Texture Resolution of {1024*8} x {1024*8}")
], update = texture_res_update)
des = "Distance to cast rays from target object to selected object(s)"
bpy.types.Scene.ray_distance = bpy.props.FloatProperty(name="Ray Distance", default = 0.2, description=des)
bpy.types.Scene.ray_warning_given = bpy.props.BoolProperty(default = False)
#--- MAPS -----------------------
des = "Bake all maps (Diffuse, Metal, SSS, SSS Col. Roughness, Normal, Transmission, Transmission Roughness, Emission, Specular, Alpha, Displacement)"
bpy.types.Scene.all_maps = bpy.props.BoolProperty(name="Bake All Maps", default = True, description=des, update = all_maps_update)
des = "Bake a PBR Colour map"
bpy.types.Scene.selected_col = bpy.props.BoolProperty(name="Diffuse", default = True, description=des)
des = "Bake a PBR Metalness map"
bpy.types.Scene.selected_metal = bpy.props.BoolProperty(name="Metal", description=des, default= True)
des = "Bake a PBR Roughness or Glossy map"
bpy.types.Scene.selected_rough = bpy.props.BoolProperty(name="Roughness", description=des, default= True)
des = "Bake a Normal map"
bpy.types.Scene.selected_normal = bpy.props.BoolProperty(name="Normal", description=des, default= True)
des = "Bake a PBR Transmission map"
bpy.types.Scene.selected_trans = bpy.props.BoolProperty(name="Transmission", description=des, default= True)
des = "Bake a PBR Transmission Roughness map"
bpy.types.Scene.selected_transrough = bpy.props.BoolProperty(name="TR Rough", description=des, default= True)
des = "Bake an Emission map"
bpy.types.Scene.selected_emission = bpy.props.BoolProperty(name="Emission", description=des, default= True)
des = "Bake a Subsurface map"
bpy.types.Scene.selected_sss = bpy.props.BoolProperty(name="SSS", description=des, default= True)
des = "Bake a Subsurface colour map"
bpy.types.Scene.selected_ssscol = bpy.props.BoolProperty(name="SSS Col", description=des, default= True)
des = "Bake a Specular/Reflection map"
bpy.types.Scene.selected_specular = bpy.props.BoolProperty(name="Specular", description=des, default= True)
des = "Bake a PBR Alpha map"
bpy.types.Scene.selected_alpha = bpy.props.BoolProperty(name="Alpha", description=des, default= True)
#------------------------------------------UVs-----------------------------------------
des = "Use Smart UV Project to create a new UV map for your objects (or target object if baking to a target). See Blender Market FAQs for more details"
bpy.types.Scene.newUVoption = bpy.props.BoolProperty(name="New UV(s)", description=des, update=newUVoption_update, default= False)
des = "If one exists for the object being baked, use any existing UV maps called 'OmniBake' for baking (rather than the active UV map)"
bpy.types.Scene.prefer_existing_sbmap = bpy.props.BoolProperty(name="Prefer existing UV maps called OmniBake", description=des)
des = "New UV Method"
bpy.types.Scene.newUVmethod = bpy.props.EnumProperty(name="New UV Method", default="SmartUVProject_Individual", description=des, items=[
("SmartUVProject_Individual", "Smart UV Project (Individual)", "Each object gets a new UV map using Smart UV Project")])
des = "Margin between islands to use for Smart UV Project"
bpy.types.Scene.unwrapmargin = bpy.props.FloatProperty(name="Margin", default=0.03, description=des)
des = "Bake to normal UVs"
bpy.types.Scene.uv_mode = bpy.props.EnumProperty(name="UV Mode", default="normal", description=des, items=[
("normal", "Normal", "Normal UV maps")])
#--------------------------------Prep/CleanUp----------------------------------
des = "Create a copy of your selected objects in Blender (or target object if baking to a target) and apply the baked textures to it. If you are baking in the background, this happens after you import"
bpy.types.Scene.prepmesh = bpy.props.BoolProperty(name="Copy objects and apply bakes", default = True, description=des, update=prepmesh_update)
des = "Hide the source object that you baked from in the viewport after baking. If you are baking in the background, this happens after you import"
bpy.types.Scene.hidesourceobjects = bpy.props.BoolProperty(name="Hide source objects after bake", default = True, description=des)
des = "Set the height of the baked image that will be produced"
bpy.types.Scene.imgheight = bpy.props.IntProperty(name="Height", default=1024, description=des)
des = "Set the width of the baked image that will be produced"
bpy.types.Scene.imgwidth = bpy.props.IntProperty(name="Width", default=1024, description=des)
des="Name to apply to these bakes (is incorporated into the bakes file name, provided you have included this in the image format string - see addon preferences). NOTE: To maintain compatibility, only MS Windows acceptable characters will be used"
bpy.types.Scene.batchName = bpy.props.StringProperty(name="Batch name", description=des, default="Bake1", maxlen=20)
#---------------------Where To Bake?-------------------------------------------
bpy.types.Scene.bgbake = bpy.props.EnumProperty(name="Background Bake", default="fg", items=[
("fg", "Foreground", "Perform baking in the foreground. Blender will lock up until baking is complete"),
("bg", "Background", "Perform baking in the background, leaving you free to continue to work in Blender while the baking is being carried out")
])
#---------------------Filehanding & Particles------------------------------------------
bpy.types.Scene.particle_options = bpy.props.PointerProperty(type= MyProperties)
#-------------------Additional Shaders-------------------------------------------
des = "Allows for use of Add, Diffuse, Glossy, Glass, Refraction, Transparent, Anisotropic Shaders. May cause inconsistent results"
bpy.types.Scene.more_shaders = bpy.props.BoolProperty(name="Use Additional Shader Types", default=False, description=des)
def unregister():
#User preferences
global classes
for cls in classes:
bpy.utils.unregister_class(cls)
del bpy.types.Scene.particle_options
del bpy.types.Scene.more_shaders
del bpy.types.Scene.newUVoption
del bpy.types.Scene.prepmesh
del bpy.types.Scene.unwrapmargin
del bpy.types.Scene.texture_res
del bpy.types.Scene.hidesourceobjects
del bpy.types.Scene.batchName
del bpy.types.Scene.bgbake
del bpy.types.Scene.imgheight
del bpy.types.Scene.imgwidth | 11,397 | Python | 47.918455 | 250 | 0.675529 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/ui.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
import bpy
from .particle_bake.operators import*
from .material_bake.background_bake import bgbake_ops
from os.path import join, dirname
import bpy.utils.previews
#---------------Custom ICONs----------------------
def get_icons_directory():
icons_directory = join(dirname(__file__), "icons")
return icons_directory
#------------------------PANEL---------------------
class OBJECT_PT_omni_bake_panel(bpy.types.Panel):
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Omniverse"
bl_label = "NVIDIA OMNIVERSE"
version = "0.0.0"
#retrieve icons
icons = bpy.utils.previews.new()
icons_directory = get_icons_directory()
icons.load("OMNIBLEND", join(icons_directory, "BlenderOMNI.png"), 'IMAGE')
icons.load("OMNI", join(icons_directory, "ICON.png"), 'IMAGE')
icons.load("BAKE",join(icons_directory, "Oven.png"), 'IMAGE')
#draw the panel
def draw(self, context):
layout = self.layout
#--------File Handling-------------------
layout.label(text="Omniverse", icon_value=self.icons["OMNI"].icon_id)
impExpCol = self.layout.column(align=True)
impExpCol.label(text= "File Handling",
icon='FILEBROWSER')
impExpCol.operator('wm.usd_import',
text='Import USD',
icon='IMPORT')
impExpCol.operator('wm.usd_export',
text='Export USD',
icon='EXPORT')
#--------Particle Collection Instancing-------------------
layout.separator()
particleOptions = context.scene.particle_options
particleCol = self.layout.column(align=True)
particleCol.label(text = "Omni Particles",
icon='PARTICLES')
box = particleCol.box()
column= box.column(align= True)
column.prop(particleOptions, "deletePSystemAfterBake")
row = column.row()
row.prop(particleOptions, "animateData")
if particleOptions.animateData:
row = column.row(align=True)
row.prop(particleOptions, "selectedStartFrame")
row.prop(particleOptions, "selectedEndFrame")
row = column.row()
row.enabled = False
row.label(text="Increased Calculation Time", icon= 'ERROR')
row = column.row()
row.scale_y = 1.5
row.operator('omni.hair_bake',
text='Convert',
icon='MOD_PARTICLE_INSTANCE')
#Does not update while running. Set in "particle_bake.operators.py"
# row = column.row()
# row.scale_y = 1.2
# row.prop(particleOptions, "progressBar")
#--------PBR Bake Settings-------------------
layout.separator()
column = layout.column(align= True)
header = column.row()
header.label(text = "Material Bake", icon = 'UV_DATA')
box = column.box()
row = box.row()
if context.scene.all_maps == True:
row.prop(context.scene, "all_maps", icon = 'CHECKBOX_HLT')
if context.scene.all_maps == False:
row.prop(context.scene, "all_maps", icon = 'CHECKBOX_DEHLT')
column = box.column(align= True)
row = column.row()
row.prop(context.scene, "selected_col")
row.prop(context.scene, "selected_metal")
row = column.row()
row.prop(context.scene, "selected_sss")
row.prop(context.scene, "selected_ssscol")
row = column.row()
row.prop(context.scene, "selected_rough")
row.prop(context.scene, "selected_normal")
row = column.row()
row.prop(context.scene, "selected_trans")
row.prop(context.scene, "selected_transrough")
row = column.row()
row.prop(context.scene, "selected_emission")
row.prop(context.scene, "selected_specular")
row = column.row()
row.prop(context.scene, "selected_alpha")
row = column.row()
colm = box.column(align=True)
colm.prop(context.scene, "more_shaders")
row = colm.row()
row.enabled = False
if context.scene.more_shaders:
row.label(text="Inconsistent Results", icon= 'ERROR')
#--------Texture Settings-------------------
row = box.row()
row.label(text="Texture Resolution:")
row.scale_y = 0.5
row = box.row()
row.prop(context.scene, "texture_res", expand=True)
row.scale_y = 1
if context.scene.texture_res == "8k" or context.scene.texture_res == "4k":
row = box.row()
row.enabled = False
row.label(text="Long Bake Times", icon= 'ERROR')
#--------UV Settings-------------------
column = box.column(align = True)
row = column.row()
row.prop(context.scene, "newUVoption")
row.prop(context.scene, "unwrapmargin")
#--------Other Settings-------------------
column= box.column(align=True)
row = column.row()
if bpy.context.scene.bgbake == "fg":
text = "Copy objects and apply bakes"
else:
text = "Copy objects and apply bakes (after import)"
row.prop(context.scene, "prepmesh", text=text)
if (context.scene.prepmesh == True):
if bpy.context.scene.bgbake == "fg":
text = "Hide source objects after bake"
else:
text = "Hide source objects after bake (after import)"
row = column.row()
row.prop(context.scene, "hidesourceobjects", text=text)
#-------------Buttons-------------------------
row = box.row()
row.scale_y = 1.5
row.operator("object.omni_bake_mapbake", icon_value=self.icons["BAKE"].icon_id)
row = column.row()
row.scale_y = 1
row.prop(context.scene, "bgbake", expand=True)
if context.scene.bgbake == "bg":
row = column.row(align= True)
# - BG status button
col = row.column()
if len(bgbake_ops.bgops_list) == 0:
enable = False
icon = "TIME"
else:
enable = True
icon = "TIME"
col.operator("object.omni_bake_bgbake_status", text="", icon=icon)
col.enabled = enable
# - BG import button
col = row.column()
if len(bgbake_ops.bgops_list_finished) != 0:
enable = True
icon = "IMPORT"
else:
enable = False
icon = "IMPORT"
col.operator("object.omni_bake_bgbake_import", text="", icon=icon)
col.enabled = enable
#BG erase button
col = row.column()
if len(bgbake_ops.bgops_list_finished) != 0:
enable = True
icon = "TRASH"
else:
enable = False
icon = "TRASH"
col.operator("object.omni_bake_bgbake_clear", text="", icon=icon)
col.enabled = enable
row.alignment = 'CENTER'
row.label(text=f"Running {len(bgbake_ops.bgops_list)} | Finished {len(bgbake_ops.bgops_list_finished)}")
#-------------Other material options-------------------------
if len(bpy.context.selected_objects) != 0 and bpy.context.active_object != None:
if bpy.context.active_object.select_get() and bpy.context.active_object.type == "MESH":
layout.separator()
column= layout.column(align= True)
column.label(text= "Convert Material to:", icon= 'SHADING_RENDERED')
box = column.box()
materialCol = box.column(align=True)
materialCol.operator('universalmaterialmap.create_template_omnipbr',
text='OmniPBR')
materialCol.operator('universalmaterialmap.create_template_omniglass',
text='OmniGlass')
class OmniBakePreferences(bpy.types.AddonPreferences):
# this must match the add-on name, use '__package__'
# when defining this in a submodule of a python package.
bl_idname = __package__
img_name_format: bpy.props.StringProperty(name="Image format string",
default="%OBJ%_%BATCH%_%BAKEMODE%_%BAKETYPE%")
#Aliases
diffuse_alias: bpy.props.StringProperty(name="Diffuse", default="diffuse")
metal_alias: bpy.props.StringProperty(name="Metal", default="metalness")
roughness_alias: bpy.props.StringProperty(name="Roughness", default="roughness")
glossy_alias: bpy.props.StringProperty(name="Glossy", default="glossy")
normal_alias: bpy.props.StringProperty(name="Normal", default="normal")
transmission_alias: bpy.props.StringProperty(name="Transmission", default="transparency")
transmissionrough_alias: bpy.props.StringProperty(name="Transmission Roughness", default="transparencyroughness")
clearcoat_alias: bpy.props.StringProperty(name="Clearcost", default="clearcoat")
clearcoatrough_alias: bpy.props.StringProperty(name="Clearcoat Roughness", default="clearcoatroughness")
emission_alias: bpy.props.StringProperty(name="Emission", default="emission")
specular_alias: bpy.props.StringProperty(name="Specular", default="specular")
alpha_alias: bpy.props.StringProperty(name="Alpha", default="alpha")
sss_alias: bpy.props.StringProperty(name="SSS", default="sss")
ssscol_alias: bpy.props.StringProperty(name="SSS Colour", default="ssscol")
@classmethod
def reset_img_string(self):
prefs = bpy.context.preferences.addons[__package__].preferences
prefs.property_unset("img_name_format")
bpy.ops.wm.save_userpref()
| 10,922 | Python | 37.192308 | 117 | 0.568211 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/particle_bake/__init__.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. | 858 | Python | 44.210524 | 74 | 0.7331 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/particle_bake/operators.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
import time
import bpy
import numpy as np
class MyProperties(bpy.types.PropertyGroup):
deletePSystemAfterBake: bpy.props.BoolProperty(
name = "Delete PS after converting",
description = "Delete selected particle system after conversion",
default = False
)
progressBar: bpy.props.StringProperty(
name = "Progress",
description = "Progress of Particle Conversion",
default = "RUNNING"
)
animateData: bpy.props.BoolProperty(
name = "Keyframe Animation",
description = "Add a keyframe for each particle for each of the specified frames",
default = False
)
selectedStartFrame: bpy.props.IntProperty(
name = "Start",
description = "Frame to begin keyframes",
default = 1
)
selectedEndFrame: bpy.props.IntProperty(
name = "End",
description = "Frame to stop keyframes",
default = 3
)
# def fixEndFrame():
# particleOptions = context.particle_options
# particleOptions.selectedEndFrame = particleOptions.selectedStartFrame
particleSystemVisibility = []
particleSystemRender = []
def getOriginalModifiers(parent):
particleSystemVisibility.clear()
particleSystemRender.clear()
for mod in parent.modifiers:
if mod.type == 'PARTICLE_SYSTEM':
particleSystemVisibility.append(mod.show_viewport)
particleSystemRender.append(mod.show_render)
def restoreOriginalModifiers(parent):
count = 0
for mod in parent.modifiers:
if mod.type == 'PARTICLE_SYSTEM':
mod.show_viewport = particleSystemVisibility[count]
mod.show_render = particleSystemRender[count]
count+=1
def hideOtherModifiers(parent, countH):
count = 0
for mod in parent.modifiers:
if mod.type == 'PARTICLE_SYSTEM':
if countH != count:
mod.show_viewport = False
count += 1
def particleSystemVisible(parent, countP):
countS = 0
for mod in parent.modifiers:
if mod.type == 'PARTICLE_SYSTEM':
if countP == countS:
return mod.show_viewport
else:
countS += 1
# Omni Hair Bake
class PARTICLES_OT_omni_hair_bake(bpy.types.Operator):
"""Convert blender particles for Omni scene instancing"""
bl_idname = "omni.hair_bake"
bl_label = "Omni Hair Bake"
bl_options = {'REGISTER', 'UNDO'} # create undo state
def execute(self, context):
particleOptions = context.scene.particle_options
startTime= time.time()
print()
print("____BEGINING PARTICLE CONVERSION______")
#Deselect Non-meshes
for obj in bpy.context.selected_objects:
if obj.type != "MESH":
obj.select_set(False)
print("not mesh")
#Do we still have an active object?
if bpy.context.active_object == None:
#Pick arbitary
bpy.context.view_layer.objects.active = bpy.context.selected_objects[0]
for parentObj in bpy.context.selected_objects:
print()
print("--Staring " + parentObj.name + ":")
getOriginalModifiers(parentObj)
countH = 0
countP = 0
countPS = 0
showEmmiter = False
hasPS = False
for currentPS in parentObj.particle_systems:
hideOtherModifiers(parentObj, countH)
countH+=1
hasVisible = particleSystemVisible(parentObj, countP)
countP+=1
if currentPS != None and hasVisible:
hasPS = True
bpy.ops.object.select_all(action='DESELECT')
renderType = currentPS.settings.render_type
emmitOrHair = currentPS.settings.type
if parentObj.show_instancer_for_viewport == True:
showEmmiter = True
if renderType == 'OBJECT' or renderType == 'COLLECTION':
count = 0
listInst = []
listInstScale = []
# For Object Instances
if renderType == 'OBJECT':
instObj = currentPS.settings.instance_object
# Duplicate Instanced Object
dupInst = instObj.copy()
bpy.context.collection.objects.link(dupInst)
dupInst.select_set(True)
dupInst.location = (0,0,0)
bpy.ops.object.move_to_collection(collection_index=0, is_new=True, new_collection_name="INST_"+str(dupInst.name))
dupInst.select_set(False)
count += 1
listInst.append(dupInst)
listInstScale.append(instObj.scale)
# For Collection Instances
if renderType == 'COLLECTION':
instCol = currentPS.settings.instance_collection.objects
countW = 0
weight = 1
for obj in instCol:
# Duplicate Instanced Object
dupInst = obj.copy()
bpy.context.collection.objects.link(dupInst)
dupInst.select_set(True)
dupInst.location = (0,0,0)
bpy.ops.object.move_to_collection(collection_index=0, is_new=True, new_collection_name="INST_"+str(dupInst.name))
dupInst.select_set(False)
if parentObj.particle_systems.active.settings.use_collection_count:
weight = currentPS.settings.instance_weights[countW].count
print("Instance Count: " + str(weight))
for i in range(weight):
count += 1
listInst.append(dupInst)
listInstScale.append(obj.scale)
countW += 1
# For Path Instances *NOT SUPPORTED
if renderType == 'PATH':
print("path no good")
return {'FINISHED'}
if renderType == 'NONE':
print("no instances")
return {'FINISHED'}
#DOES NOTHING RIGHT NOW
#if overwriteExsisting:
#bpy.ops.outliner.delete(hierarchy=True)
# Variables
parentObj.select_set(True)
parentCollection = parentObj.users_collection[0]
nameP = parentObj.particle_systems[countPS].name # get name of object's particle system
# Create Empty as child
o = bpy.data.objects.new( "empty", None)
o.name = "EM_" + nameP
o.parent = parentObj
parentCollection.objects.link( o )
# FOR ANIMATED EMITTER DATA
if particleOptions.animateData and emmitOrHair == 'EMITTER':
print("--ANIMATED EMITTER--")
#Prep for Keyframing
collectionInstances = []
# Calculate Dependency Graph
degp = bpy.context.evaluated_depsgraph_get()
# Evaluate the depsgraph (Important step)
particle_systems = parentObj.evaluated_get(degp).particle_systems
# All particles of selected particle system
activePS = particle_systems[countPS]
particles = activePS.particles
# Total Particles
totalParticles = len(particles)
#Currently does NOT work
# if activePS.type == 'HAIR':
# hairLength = particles[0].hair_length
# print(hairLength)
# print(bpy.types.ParticleHairKey.co_object(parentObj,parentObj.modifiers[0], particles[0]))
# key = particles[0].hair_keys
# print(key)
# coo = key.co
# print(coo)
# print(particles[0].location)
#Beginings of supporting use random, requires more thought
# obInsttt = parentObj.evaluated_get(degp).object_instances
# for i in obInsttt:
# obj = i.object
# print(obj.name)
# for obj in degp.object_instances:
# print(obj.instance_object)
# print(obj.particle_system)
# Handle instances for construction of scene collections **Fast**
for i in range(totalParticles):
childObj = particles[i]
calculateChild = False
if childObj.birth_time <= particleOptions.selectedEndFrame and childObj.die_time > particleOptions.selectedStartFrame:
calculateChild = True
if calculateChild:
modInst = i % count
#Works for "use count" but not "pick random"
dupColName = str(listInst[modInst].users_collection[0].name)
#Create Collection Instance
source_collection = bpy.data.collections[dupColName]
instance_obj = bpy.data.objects.new(
name= "Inst_" + listInst[modInst].name + "." + str(i),
object_data=None
)
instance_obj.empty_display_type = 'SINGLE_ARROW'
instance_obj.empty_display_size = .1
instance_obj.instance_collection = source_collection
instance_obj.instance_type = 'COLLECTION'
parentCollection.objects.link(instance_obj)
instance_obj.parent = o
instance_obj.matrix_parent_inverse = o.matrix_world.inverted()
collectionInstances.append(instance_obj)
print("Using " + str(len(collectionInstances)))
print("Out of " + str(totalParticles) + " instances")
collectionCount = len(collectionInstances)
startFrame = particleOptions.selectedStartFrame
endFrame = particleOptions.selectedEndFrame
#Do we need to swap start and end frame?
if particleOptions.selectedStartFrame > particleOptions.selectedEndFrame:
endFrame = startFrame
startFrame = particleOptions.selectedEndFrame
for frame in range(startFrame, endFrame + 1):
print("frame = " + str(frame))
bpy.context.scene.frame_current = frame
# Calculate Dependency Graph for each frame
degp = bpy.context.evaluated_depsgraph_get()
particle_systems = parentObj.evaluated_get(degp).particle_systems
particles = particle_systems[countPS].particles
for i in range(collectionCount):
activeCol = collectionInstances[i]
activeDup = particles[i]
#Keyframe Visibility, Scale, Location, and Rotation
if activeDup.alive_state == 'UNBORN' or activeDup.alive_state == 'DEAD':
activeCol.scale = (0,0,0)
activeCol.keyframe_insert(data_path='scale')
activeCol.hide_viewport = True
activeCol.hide_render = True
activeCol.keyframe_insert("hide_viewport")
activeCol.keyframe_insert("hide_render")
else:
activeCol.hide_viewport = False
activeCol.hide_render = False
scale = activeDup.size
activeCol.location = activeDup.location
activeCol.rotation_mode = 'QUATERNION'
activeCol.rotation_quaternion = activeDup.rotation
activeCol.rotation_mode = 'XYZ'
activeCol.scale = (scale, scale, scale)
activeCol.keyframe_insert(data_path='location')
activeCol.keyframe_insert(data_path='rotation_euler')
activeCol.keyframe_insert(data_path='scale')
activeCol.keyframe_insert("hide_viewport")
activeCol.keyframe_insert("hide_render")
# FOR ANIMATED HAIR DATA
elif particleOptions.animateData and emmitOrHair == 'HAIR':
print("--ANIMATED HAIR--")
#Prep for Keyframing
bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles
dups = bpy.context.selected_objects
lengthDups = len(dups)
collectionInstances = []
# Handle instances for construction of scene collections **Fast**
for i in range(lengthDups):
childObj = dups.pop(0)
modInst = i % count
#Works for "use count" but not "pick random"
dupColName = str(listInst[modInst].users_collection[0].name)
#Create Collection Instance
source_collection = bpy.data.collections[dupColName]
instance_obj = bpy.data.objects.new(
name= "Inst_" + childObj.name,
object_data=None
)
instance_obj.empty_display_type = 'SINGLE_ARROW'
instance_obj.empty_display_size = .1
instance_obj.instance_collection = source_collection
instance_obj.instance_type = 'COLLECTION'
parentCollection.objects.link(instance_obj)
instance_obj.parent = o
bpy.data.objects.remove(childObj, do_unlink=True)
collectionInstances.append(instance_obj)
print(str(len(collectionInstances)) + " instances")
collectionCount = len(collectionInstances)
startFrame = particleOptions.selectedStartFrame
endFrame = particleOptions.selectedEndFrame
#Do we need to swap start and end frame?
if particleOptions.selectedStartFrame > particleOptions.selectedEndFrame:
endFrame = startFrame
startFrame = particleOptions.selectedEndFrame
for frame in range(startFrame, endFrame + 1):
print("frame = " + str(frame))
bpy.context.scene.frame_current = frame
# Calculate hairs for each frame
parentObj.select_set(True)
bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles
tempdups = bpy.context.selected_objects
for i in range(collectionCount):
activeDup = tempdups.pop(0)
activeCol = collectionInstances[i]
#Keyframe Scale, Location, and Rotation
activeCol.location = activeDup.location
activeCol.rotation_euler = activeDup.rotation_euler
activeCol.scale = activeDup.scale
activeCol.keyframe_insert(data_path='location')
activeCol.keyframe_insert(data_path='rotation_euler')
activeCol.keyframe_insert(data_path='scale')
bpy.data.objects.remove(activeDup, do_unlink=True)
# FOR SINGLE FRAME CONVERSION
else:
print("--SINGLE FRAME--")
bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles
dups = bpy.context.selected_objects
lengthDups = len(dups)
# Handle instances for construction of scene collections **Fast**
for i in range(lengthDups):
childObj = dups.pop(0)
modInst = i % count
dupColName = str(listInst[modInst].users_collection[0].name)
loc=childObj.location
rot=childObj.rotation_euler
newScale = np.divide(childObj.scale, listInstScale[modInst])
#Create Collection Instance
source_collection = bpy.data.collections[dupColName]
instance_obj = bpy.data.objects.new(
name= "Inst_" + childObj.name,
object_data=None
)
instance_obj.empty_display_type = 'SINGLE_ARROW'
instance_obj.empty_display_size = .1
instance_obj.instance_collection = source_collection
instance_obj.instance_type = 'COLLECTION'
instance_obj.location = loc
instance_obj.rotation_euler = rot
instance_obj.scale = newScale
parentCollection.objects.link(instance_obj)
instance_obj.parent = o
bpy.data.objects.remove(childObj, do_unlink=True)
for obj in listInst:
bpy.context.view_layer.layer_collection.children[obj.users_collection[0].name].exclude = True
#Make parent object active object again
parentObj.select_set(True)
bpy.context.view_layer.objects.active = parentObj
else:
print("Must be object or collection instance")
else:
print("Object has no active particle system")
restoreOriginalModifiers(parentObj)
countPS += 1
#Handle PS after converting
if particleOptions.deletePSystemAfterBake:
if showEmmiter == False and hasPS == True:
bpy.context.active_object.hide_render = True
bpy.context.active_object.hide_set(True)
countI = 0
for ps in range(len(parentObj.particle_systems)):
if particleSystemVisibility[ps] == True:
parentObj.particle_systems.active_index = countI
bpy.ops.object.particle_system_remove()
else:
countI+=1
else:
countI = 0
for mod in parentObj.modifiers:
if mod.type == 'PARTICLE_SYSTEM':
mod.show_viewport = False
if particleSystemVisibility[countI] == True:
mod.show_render = False
countI+=1
print ("My program took", time.time() - startTime, " seconds to run") # run time
return {'FINISHED'} | 23,439 | Python | 46.258064 | 150 | 0.462477 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/material_setup.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
import bpy
from . import functions
from .data import MasterOperation
def find_node_from_label(label, nodes):
for node in nodes:
if node.label == label:
return node
return False
def find_isocket_from_identifier(idname, node):
for inputsocket in node.inputs:
if inputsocket.identifier == idname:
return inputsocket
return False
def find_osocket_from_identifier(idname, node):
for outputsocket in node.outputs:
if outputsocket.identifier == idname:
return outputsocket
return False
def make_link(f_node_label, f_node_ident, to_node_label, to_node_ident, nodetree):
fromnode = find_node_from_label(f_node_label, nodetree.nodes)
if(fromnode == False):
return False
fromsocket = find_osocket_from_identifier(f_node_ident, fromnode)
tonode = find_node_from_label(to_node_label, nodetree.nodes)
if(tonode == False):
return False
tosocket = find_isocket_from_identifier(to_node_ident, tonode)
nodetree.links.new(fromsocket, tosocket)
return True
def wipe_labels(nodes):
for node in nodes:
node.label = ""
def get_image_from_tag(thisbake, objname):
current_bake_op = MasterOperation.current_bake_operation
global_mode = current_bake_op.bake_mode
objname = functions.untrunc_if_needed(objname)
batch_name = bpy.context.scene.batchName
result = []
result = [img for img in bpy.data.images if\
("SB_objname" in img and img["SB_objname"] == objname) and\
("SB_batch" in img and img["SB_batch"] == batch_name) and\
("SB_globalmode" in img and img["SB_globalmode"] == global_mode) and\
("SB_thisbake" in img and img["SB_thisbake"] == thisbake)\
]
if len(result) > 0:
return result[0]
functions.printmsg(f"ERROR: No image with matching tag ({thisbake}) found for object {objname}")
return False
def create_principled_setup(nodetree, obj):
functions.printmsg("Creating principled material")
nodes = nodetree.nodes
obj_name = obj.name.replace("_OmniBake", "")
obj.active_material.cycles.displacement_method = 'BOTH'
#First we wipe out any existing nodes
for node in nodes:
nodes.remove(node)
# Node Frame
node = nodes.new("NodeFrame")
node.location = (0,0)
node.use_custom_color = True
node.color = (0.149763, 0.214035, 0.0590617)
#Now create the Principled BSDF
pnode = nodes.new("ShaderNodeBsdfPrincipled")
pnode.location = (-25, 335)
pnode.label = "pnode"
pnode.use_custom_color = True
pnode.color = (0.3375297784805298, 0.4575316309928894, 0.08615386486053467)
pnode.parent = nodes["Frame"]
#And the output node
node = nodes.new("ShaderNodeOutputMaterial")
node.location = (500, 200)
node.label = "monode"
node.show_options = False
node.parent = nodes["Frame"]
#-----------------------------------------------------------------
#Node Image texture types Types
if(bpy.context.scene.selected_col):
image = get_image_from_tag("diffuse", obj_name)
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, 250)
node.label = "col_tex"
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_sss):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, 210)
node.label = "sss_tex"
image = get_image_from_tag("sss", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_ssscol):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, 170)
node.label = "ssscol_tex"
image = get_image_from_tag("ssscol", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_metal):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, 130)
node.label = "metal_tex"
image = get_image_from_tag("metalness", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_specular):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, 90)
node.label = "specular_tex"
image = get_image_from_tag("specular", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_rough):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, 50)
node.label = "roughness_tex"
image = get_image_from_tag("roughness", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_trans):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, -90)
node.label = "transmission_tex"
image = get_image_from_tag("transparency", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_transrough):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, -130)
node.label = "transmissionrough_tex"
image = get_image_from_tag("transparencyroughness", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_emission):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, -170)
node.label = "emission_tex"
image = get_image_from_tag("emission", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_alpha):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, -210)
node.label = "alpha_tex"
image = get_image_from_tag("alpha", obj_name)
node.image = image
node.parent = nodes["Frame"]
if(bpy.context.scene.selected_normal):
node = nodes.new("ShaderNodeTexImage")
node.hide = True
node.location = (-500, -318.7)
node.label = "normal_tex"
image = get_image_from_tag("normal", obj_name)
node.image = image
node.parent = nodes["Frame"]
#-----------------------------------------------------------------
# Additional normal map node for normal socket
if(bpy.context.scene.selected_normal):
node = nodes.new("ShaderNodeNormalMap")
node.location = (-220, -240)
node.label = "normalmap"
node.show_options = False
node.parent = nodes["Frame"]
#-----------------------------------------------------------------
make_link("emission_tex", "Color", "pnode", "Emission", nodetree)
make_link("col_tex", "Color", "pnode", "Base Color", nodetree)
make_link("metal_tex", "Color", "pnode", "Metallic", nodetree)
make_link("roughness_tex", "Color", "pnode", "Roughness", nodetree)
make_link("transmission_tex", "Color", "pnode", "Transmission", nodetree)
make_link("transmissionrough_tex", "Color", "pnode", "Transmission Roughness", nodetree)
make_link("normal_tex", "Color", "normalmap", "Color", nodetree)
make_link("normalmap", "Normal", "pnode", "Normal", nodetree)
make_link("specular_tex", "Color", "pnode", "Specular", nodetree)
make_link("alpha_tex", "Color", "pnode", "Alpha", nodetree)
make_link("sss_tex", "Color", "pnode", "Subsurface", nodetree)
make_link("ssscol_tex", "Color", "pnode", "Subsurface Color", nodetree)
make_link("pnode", "BSDF", "monode", "Surface", nodetree)
#---------------------------------------------------
wipe_labels(nodes)
node = nodes["Frame"]
node.label = "OMNI PBR" | 8,828 | Python | 33.088803 | 100 | 0.608518 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/data.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
from .bake_operation import bakestolist
class MasterOperation:
current_bake_operation = None
total_bake_operations = 0
this_bake_operation_num = 0
orig_UVs_dict = {}
baked_textures = []
prepared_mesh_objects = []
batch_name = ""
orig_objects = []
orig_active_object = ""
orig_sample_count = 0
@staticmethod
def clear():
# Master variables called throughout bake process
MasterOperation.orig_UVs_dict = {}
MasterOperation.total_bake_operations = 0
MasterOperation.current_bake_operation = None
MasterOperation.this_bake_operation_num = 0
MasterOperation.prepared_mesh_objects = []
MasterOperation.baked_textures = []
MasterOperation.batch_name = ""
# Variables to reset your scene to what it was before bake.
MasterOperation.orig_objects = []
MasterOperation.orig_active_object = ""
MasterOperation.orig_sample_count = 0
return True
class BakeOperation:
#Constants
PBR = "pbr"
def __init__(self):
#Mapping of object name to active UVs
self.bake_mode = BakeOperation.PBR #So the example in the user prefs will work
self.bake_objects = []
self.active_object = None
#normal
self.uv_mode = "normal"
#pbr stuff
self.pbr_selected_bake_types = []
def assemble_pbr_bake_list(self):
self.pbr_selected_bake_types = bakestolist() | 2,334 | Python | 28.935897 | 86 | 0.667095 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/operators.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
import bpy
import sys
import subprocess
import os
from .bake_operation import BakeStatus, bakestolist
from .data import MasterOperation, BakeOperation
from . import functions
from . import bakefunctions
from .background_bake import bgbake_ops
from pathlib import Path
import tempfile
class OBJECT_OT_omni_bake_mapbake(bpy.types.Operator):
"""Start the baking process"""
bl_idname = "object.omni_bake_mapbake"
bl_label = "Bake"
bl_options = {'REGISTER', 'UNDO'} # create undo state
def execute(self, context):
def commence_bake(needed_bake_modes):
#Prepare the BakeStatus tracker for progress bar
num_of_objects = 0
num_of_objects = len(bpy.context.selected_objects)
total_maps = 0
for need in needed_bake_modes:
if need == BakeOperation.PBR:
total_maps+=(bakestolist(justcount=True) * num_of_objects)
BakeStatus.total_maps = total_maps
#Clear the MasterOperation stuff
MasterOperation.clear()
#Need to know the total operations
MasterOperation.total_bake_operations = len(needed_bake_modes)
#Master list of all ops
bops = []
for need in needed_bake_modes:
#Create operation
bop = BakeOperation()
#Set master level attributes
#-------------------------------
bop.bake_mode = need
#-------------------------------
bops.append(bop)
functions.printmsg(f"Created operation for {need}")
#Run queued operations
for bop in bops:
MasterOperation.this_bake_operation_num+=1
MasterOperation.current_bake_operation = bop
if bop.bake_mode == BakeOperation.PBR:
functions.printmsg("Running PBR bake")
bakefunctions.doBake()
return True
######################TEMP###############################################
needed_bake_modes = []
needed_bake_modes.append(BakeOperation.PBR)
#Clear the progress stuff
BakeStatus.current_map = 0
BakeStatus.total_maps = 0
#If we have been called in background mode, just get on with it. Checks should be done.
if "--background" in sys.argv:
if "OmniBake_Bakes" in bpy.data.collections:
#Remove any prior baked objects
bpy.data.collections.remove(bpy.data.collections["OmniBake_Bakes"])
#Bake
commence_bake(needed_bake_modes)
self.report({"INFO"}, "Bake complete")
return {'FINISHED'}
functions.deselect_all_not_mesh()
#We are in foreground, do usual checks
result = True
for need in needed_bake_modes:
if not functions.startingChecks(bpy.context.selected_objects, need):
result = False
if not result:
return {"CANCELLED"}
#If the user requested background mode, fire that up now and exit
if bpy.context.scene.bgbake == "bg":
bpy.ops.wm.save_mainfile()
filepath = filepath = bpy.data.filepath
process = subprocess.Popen(
[bpy.app.binary_path, "--background",filepath, "--python-expr",\
"import bpy;\
import os;\
from pathlib import Path;\
savepath=Path(bpy.data.filepath).parent / (str(os.getpid()) + \".blend\");\
bpy.ops.wm.save_as_mainfile(filepath=str(savepath), check_existing=False);\
bpy.ops.object.omni_bake_mapbake();"],
shell=False)
bgbake_ops.bgops_list.append([process, bpy.context.scene.prepmesh, bpy.context.scene.hidesourceobjects])
self.report({"INFO"}, "Background bake process started")
return {'FINISHED'}
#If we are doing this here and now, get on with it
#Create a bake operation
commence_bake(needed_bake_modes)
self.report({"INFO"}, "Bake complete")
return {'FINISHED'}
#--------------------BACKGROUND BAKE----------------------------------
class OBJECT_OT_omni_bake_bgbake_status(bpy.types.Operator):
bl_idname = "object.omni_bake_bgbake_status"
bl_label = "Check on the status of bakes running in the background"
def execute(self, context):
msg_items = []
#Display remaining
if len(bgbake_ops.bgops_list) == 0:
msg_items.append("No background bakes are currently running")
else:
msg_items.append(f"--------------------------")
for p in bgbake_ops.bgops_list:
t = Path(tempfile.gettempdir())
t = t / f"OmniBake_Bgbake_{str(p[0].pid)}"
try:
with open(str(t), "r") as progfile:
progress = progfile.readline()
except:
#No file yet, as no bake operation has completed yet. Holding message
progress = 0
msg_items.append(f"RUNNING: Process ID: {str(p[0].pid)} - Progress {progress}%")
msg_items.append(f"--------------------------")
functions.ShowMessageBox(msg_items, "Background Bake Status(es)")
return {'FINISHED'}
class OBJECT_OT_omni_bake_bgbake_import(bpy.types.Operator):
bl_idname = "object.omni_bake_bgbake_import"
bl_label = "Import baked objects previously baked in the background"
bl_options = {'REGISTER', 'UNDO'} # create undo state
def execute(self, context):
if bpy.context.mode != "OBJECT":
self.report({"ERROR"}, "You must be in object mode")
return {'CANCELLED'}
for p in bgbake_ops.bgops_list_finished:
savepath = Path(bpy.data.filepath).parent
pid_str = str(p[0].pid)
path = savepath / (pid_str + ".blend")
path = str(path) + "\\Collection\\"
#Record the objects and collections before append (as append doesn't give us a reference to the new stuff)
functions.spot_new_items(initialise=True, item_type="objects")
functions.spot_new_items(initialise=True, item_type="collections")
functions.spot_new_items(initialise=True, item_type="images")
#Append
bpy.ops.wm.append(filename="OmniBake_Bakes", directory=path, use_recursive=False, active_collection=False)
#If we didn't actually want the objects, delete them
if not p[1]:
#Delete objects we just imported (leaving only textures)
for obj_name in functions.spot_new_items(initialise=False, item_type = "objects"):
bpy.data.objects.remove(bpy.data.objects[obj_name])
for col_name in functions.spot_new_items(initialise=False, item_type = "collections"):
bpy.data.collections.remove(bpy.data.collections[col_name])
#If we have to hide the source objects, do it
if p[2]:
#Get the newly introduced objects:
objects_before_names = functions.spot_new_items(initialise=False, item_type="objects")
for obj_name in objects_before_names:
#Try this in case there are issues with long object names.. better than a crash
try:
bpy.data.objects[obj_name.replace("_Baked", "")].hide_set(True)
except:
pass
#Delete the temp blend file
try:
os.remove(str(savepath / pid_str) + ".blend")
os.remove(str(savepath / pid_str) + ".blend1")
except:
pass
#Clear list for next time
bgbake_ops.bgops_list_finished = []
#Confirm back to user
self.report({"INFO"}, "Import complete")
messagelist = []
messagelist.append(f"{len(functions.spot_new_items(initialise=False, item_type='objects'))} objects imported")
messagelist.append(f"{len(functions.spot_new_items(initialise=False, item_type='images'))} textures imported")
functions.ShowMessageBox(messagelist, "Import complete", icon = 'INFO')
#If we imported an image, and we already had an image with the same name, get rid of the original in favour of the imported
new_images_names = functions.spot_new_items(initialise=False, item_type="images")
#Find any .001s
for imgname in new_images_names:
try:
int(imgname[-3:])
#Delete the existing version
bpy.data.images.remove(bpy.data.images[imgname[0:-4]])
#Rename our version
bpy.data.images[imgname].name = imgname[0:-4]
except ValueError:
pass
return {'FINISHED'}
class OBJECT_OT_omni_bake_bgbake_clear(bpy.types.Operator):
"""Delete the background bakes because you don't want to import them into Blender. NOTE: If you chose to save bakes or FBX externally, these are safe and NOT deleted. This is just if you don't want to import into this Blender session"""
bl_idname = "object.omni_bake_bgbake_clear"
bl_label = ""
bl_options = {'REGISTER', 'UNDO'} # create undo state
def execute(self, context):
savepath = Path(bpy.data.filepath).parent
for p in bgbake_ops.bgops_list_finished:
pid_str = str(p[0].pid)
try:
os.remove(str(savepath / pid_str) + ".blend")
os.remove(str(savepath / pid_str) + ".blend1")
except:
pass
bgbake_ops.bgops_list_finished = []
return {'FINISHED'} | 11,531 | Python | 38.493151 | 240 | 0.540976 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/bake_operation.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
import bpy
# Bake helper method
def bakestolist(justcount = False):
#Assemble properties into list
selectedbakes = []
selectedbakes.append("diffuse") if bpy.context.scene.selected_col else False
selectedbakes.append("metalness") if bpy.context.scene.selected_metal else False
selectedbakes.append("roughness") if bpy.context.scene.selected_rough else False
selectedbakes.append("normal") if bpy.context.scene.selected_normal else False
selectedbakes.append("transparency") if bpy.context.scene.selected_trans else False
selectedbakes.append("transparencyroughness") if bpy.context.scene.selected_transrough else False
selectedbakes.append("emission") if bpy.context.scene.selected_emission else False
selectedbakes.append("specular") if bpy.context.scene.selected_specular else False
selectedbakes.append("alpha") if bpy.context.scene.selected_alpha else False
selectedbakes.append("sss") if bpy.context.scene.selected_sss else False
selectedbakes.append("ssscol") if bpy.context.scene.selected_ssscol else False
if justcount:
return len(selectedbakes)
else:
return selectedbakes
class BakeStatus:
total_maps = 0
current_map = 0
| 2,095 | Python | 40.919999 | 101 | 0.741766 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/bakefunctions.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
import bpy
from . import functions
import sys
from .bake_operation import BakeStatus
from .data import MasterOperation, BakeOperation
def optimize():
current_bake_op = MasterOperation.current_bake_operation
MasterOperation.orig_sample_count = bpy.context.scene.cycles.samples
functions.printmsg("Reducing sample count to 16 for more efficient baking")
bpy.context.scene.cycles.samples = 16
return True
def undo_optimize():
#Restore sample count
bpy.context.scene.cycles.samples = MasterOperation.orig_sample_count
def common_bake_prep():
#--------------Set Bake Operation Variables----------------------------
current_bake_op = MasterOperation.current_bake_operation
functions.printmsg("================================")
functions.printmsg("---------Beginning Bake---------")
functions.printmsg(f"{current_bake_op.bake_mode}")
functions.printmsg("================================")
#Run information
op_num = MasterOperation.this_bake_operation_num
firstop = False
lastop = False
if op_num == 1: firstop = True
if op_num == MasterOperation.total_bake_operations: lastop = True
#If this is a pbr bake, gather the selected maps
if current_bake_op.bake_mode in {BakeOperation.PBR}:
current_bake_op.assemble_pbr_bake_list()
#Record batch name
MasterOperation.batch_name = bpy.context.scene.batchName
#Set values based on viewport selection
current_bake_op.orig_objects = bpy.context.selected_objects.copy()
current_bake_op.orig_active_object = bpy.context.active_object
current_bake_op.bake_objects = bpy.context.selected_objects.copy()
current_bake_op.active_object = bpy.context.active_object
current_bake_op.orig_engine = bpy.context.scene.render.engine
#Record original UVs for everyone
if firstop:
for obj in current_bake_op.bake_objects:
try:
MasterOperation.orig_UVs_dict[obj.name] = obj.data.uv_layers.active.name
except AttributeError:
MasterOperation.orig_UVs_dict[obj.name] = False
#Record the rendering engine
if firstop:
MasterOperation.orig_engine = bpy.context.scene.render.engine
current_bake_op.uv_mode = "normal"
#----------------------------------------------------------------------
#Force it to cycles
bpy.context.scene.render.engine = "CYCLES"
bpy.context.scene.render.bake.use_selected_to_active = False
functions.printmsg(f"Selected to active is now {bpy.context.scene.render.bake.use_selected_to_active}")
#If the user doesn't have a GPU, but has still set the render device to GPU, set it to CPU
if not bpy.context.preferences.addons["cycles"].preferences.has_active_device():
bpy.context.scene.cycles.device = "CPU"
#Clear the trunc num for this session
functions.trunc_num = 0
functions.trunc_dict = {}
#Turn off that dam use clear.
bpy.context.scene.render.bake.use_clear = False
#Do what we are doing with UVs (only if we are the primary op)
if firstop:
functions.processUVS()
#Optimize
optimize()
#Make sure the normal y setting is at default
bpy.context.scene.render.bake.normal_g = "POS_Y"
return True
def common_bake_finishing():
#Run information
current_bake_op = MasterOperation.current_bake_operation
op_num = MasterOperation.this_bake_operation_num
firstop = False
lastop = False
if op_num == 1: firstop = True
if op_num == MasterOperation.total_bake_operations: lastop = True
#Restore the original rendering engine
if lastop:
bpy.context.scene.render.engine = MasterOperation.orig_engine
undo_optimize()
#If prep mesh, or save object is selected, or running in the background, then do it
#We do this on primary run only
if firstop:
if(bpy.context.scene.prepmesh or "--background" in sys.argv):
functions.prepObjects(current_bake_op.bake_objects, current_bake_op.bake_mode)
#If the user wants it, restore the original active UV map so we don't confuse anyone
functions.restore_Original_UVs()
#Restore the original object selection so we don't confuse anyone
bpy.ops.object.select_all(action="DESELECT")
for obj in current_bake_op.orig_objects:
obj.select_set(True)
bpy.context.view_layer.objects.active = current_bake_op.orig_active_object
#Hide all the original objects
if bpy.context.scene.prepmesh and bpy.context.scene.hidesourceobjects and lastop:
for obj in current_bake_op.bake_objects:
obj.hide_set(True)
#Delete placeholder material
if lastop and "OmniBake_Placeholder" in bpy.data.materials:
bpy.data.materials.remove(bpy.data.materials["OmniBake_Placeholder"])
if "--background" in sys.argv:
bpy.ops.wm.save_mainfile()
def doBake():
current_bake_op = MasterOperation.current_bake_operation
#Do the prep we need to do for all bake types
common_bake_prep()
#Loop over the bake modes we are using
def doBake_actual():
IMGNAME = ""
for thisbake in current_bake_op.pbr_selected_bake_types:
for obj in current_bake_op.bake_objects:
#Reset the already processed list
mats_done = []
functions.printmsg(f"Baking object: {obj.name}")
#Truncate if needed from this point forward
OBJNAME = functions.trunc_if_needed(obj.name)
#Create the image we need for this bake (Delete if exists)
IMGNAME = functions.gen_image_name(obj.name, thisbake)
functions.create_Images(IMGNAME, thisbake, obj.name)
#Prep the materials one by one
materials = obj.material_slots
for matslot in materials:
mat = bpy.data.materials.get(matslot.name)
if mat.name in mats_done:
functions.printmsg(f"Skipping material {mat.name}, already processed")
#Skip this loop
#We don't want to process any materials more than once or bad things happen
continue
else:
mats_done.append(mat.name)
#Make sure we are using nodes
if not mat.use_nodes:
functions.printmsg(f"Material {mat.name} wasn't using nodes. Have enabled nodes")
mat.use_nodes = True
nodetree = mat.node_tree
nodes = nodetree.nodes
#Take a copy of material to restore at the end of the process
functions.backupMaterial(mat)
#Create the image node and set to the bake texutre we are using
imgnode = nodes.new("ShaderNodeTexImage")
imgnode.image = bpy.data.images[IMGNAME]
imgnode.label = "OmniBake"
#Remove all disconnected nodes so don't interfere with typing the material
functions.removeDisconnectedNodes(nodetree)
#Use additional shader types
functions.useAdditionalShaderTypes(nodetree, nodes)
#Normal and emission bakes require no further material prep. Just skip the rest
if(thisbake != "normal" and thisbake != "emission"):
#Work out what type of material we are dealing with here and take correct action
mat_type = functions.getMatType(nodetree)
if(mat_type == "MIX"):
functions.setup_mix_material(nodetree, thisbake)
elif(mat_type == "PURE_E"):
functions.setup_pure_e_material(nodetree, thisbake)
elif(mat_type == "PURE_P"):
functions.setup_pure_p_material(nodetree, thisbake)
#Last action before leaving this material, make the image node selected and active
functions.deselectAllNodes(nodes)
imgnode.select = True
nodetree.nodes.active = imgnode
#Select only this object
functions.selectOnlyThis(obj)
#We are done with this image, set colour space
functions.set_image_internal_col_space(bpy.data.images[IMGNAME], thisbake)
#Bake the object for this bake mode
functions.bakeoperation(thisbake, bpy.data.images[IMGNAME])
#Update tracking
BakeStatus.current_map+=1
functions.printmsg(f"Bake maps {BakeStatus.current_map} of {BakeStatus.total_maps} complete")
functions.write_bake_progress(BakeStatus.current_map, BakeStatus.total_maps)
#Restore the original materials
functions.printmsg("Restoring original materials")
functions.restoreAllMaterials()
functions.printmsg("Restore complete")
#Last thing we do with this image is scale it
functions.sacle_image_if_needed(bpy.data.images[IMGNAME])
#Do the bake at least once
doBake_actual()
#Finished baking. Perform wind down actions
common_bake_finishing() | 10,620 | Python | 36.932143 | 109 | 0.608004 |
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/functions.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
from pathlib import Path
from ..ui import OmniBakePreferences
import bpy
import os
import sys
import tempfile
from . import material_setup
from .data import MasterOperation
#Global variables
psocketname = {
"diffuse": "Base Color",
"metalness": "Metallic",
"roughness": "Roughness",
"normal": "Normal",
"transparency": "Transmission",
"transparencyroughness": "Transmission Roughness",
"specular": "Specular",
"alpha": "Alpha",
"sss": "Subsurface",
"ssscol": "Subsurface Color",
"displacement": "Displacement"
}
def printmsg(msg):
print(f"BAKE: {msg}")
def gen_image_name(obj_name, baketype):
current_bake_op = MasterOperation.current_bake_operation
#First, let's get the format string we are working with
prefs = bpy.context.preferences.addons[OmniBakePreferences.bl_idname].preferences
image_name = prefs.img_name_format
#The easy ones
image_name = image_name.replace("%OBJ%", obj_name)
image_name = image_name.replace("%BATCH%", bpy.context.scene.batchName)
#Bake mode
image_name = image_name.replace("%BAKEMODE%", current_bake_op.bake_mode)
#The hard ones
if baketype == "diffuse":
image_name = image_name.replace("%BAKETYPE%", prefs.diffuse_alias)
elif baketype == "metalness":
image_name = image_name.replace("%BAKETYPE%", prefs.metal_alias)
elif baketype == "roughness":
image_name = image_name.replace("%BAKETYPE%", prefs.roughness_alias)
elif baketype == "normal":
image_name = image_name.replace("%BAKETYPE%", prefs.normal_alias)
elif baketype == "transparency":
image_name = image_name.replace("%BAKETYPE%", prefs.transmission_alias)
elif baketype == "transparencyroughness":
image_name = image_name.replace("%BAKETYPE%", prefs.transmissionrough_alias)
elif baketype == "emission":
image_name = image_name.replace("%BAKETYPE%", prefs.emission_alias)
elif baketype == "specular":
image_name = image_name.replace("%BAKETYPE%", prefs.specular_alias)
elif baketype == "alpha":
image_name = image_name.replace("%BAKETYPE%", prefs.alpha_alias)
elif baketype == "sss":
image_name = image_name.replace("%BAKETYPE%", prefs.sss_alias)
elif baketype == "ssscol":
image_name = image_name.replace("%BAKETYPE%", prefs.ssscol_alias)
#Displacement is not currently Implemented
elif baketype == "displacement":
image_name = image_name.replace("%BAKETYPE%", prefs.displacement_alias)
else:
image_name = image_name.replace("%BAKETYPE%", baketype)
return image_name
def removeDisconnectedNodes(nodetree):
nodes = nodetree.nodes
#Loop through nodes
repeat = False
for node in nodes:
if node.type == "BSDF_PRINCIPLED" and len(node.outputs[0].links) == 0:
#Not a player, delete node
nodes.remove(node)
repeat = True
elif node.type == "EMISSION" and len(node.outputs[0].links) == 0:
#Not a player, delete node
nodes.remove(node)
repeat = True
elif node.type == "MIX_SHADER" and len(node.outputs[0].links) == 0:
#Not a player, delete node
nodes.remove(node)
repeat = True
elif node.type == "ADD_SHADER" and len(node.outputs[0].links) == 0:
#Not a player, delete node
nodes.remove(node)
repeat = True
#Displacement is not currently Implemented
elif node.type == "DISPLACEMENT" and len(node.outputs[0].links) == 0:
#Not a player, delete node
nodes.remove(node)
repeat = True
#If we removed any nodes, we need to do this again
if repeat:
removeDisconnectedNodes(nodetree)
def backupMaterial(mat):
dup = mat.copy()
dup.name = mat.name + "_OmniBake"
def restoreAllMaterials():
#Not efficient but, if we are going to do things this way, we need to loop over every object in the scene
dellist = []
for obj in bpy.data.objects:
for slot in obj.material_slots:
origname = slot.name
#Try to set to the corresponding material that was the backup
try:
slot.material = bpy.data.materials[origname + "_OmniBake"]
#If not already on our list, log the original material (that we messed with) for mass deletion
if origname not in dellist:
dellist.append(origname)
except KeyError:
#Not been backed up yet. Must not have processed an object with that material yet
pass
#Delete the unused materials
for matname in dellist:
bpy.data.materials.remove(bpy.data.materials[matname])
#Rename all materials to the original name, leaving us where we started
for mat in bpy.data.materials:
if "_OmniBake" in mat.name:
mat.name = mat.name.replace("_OmniBake", "")
def create_Images(imgname, thisbake, objname):
#thisbake is subtype e.g. diffuse, ao, etc.
current_bake_op = MasterOperation.current_bake_operation
global_mode = current_bake_op.bake_mode
batch = MasterOperation.batch_name
printmsg(f"Creating image {imgname}")
#Get the image height and width from the interface
IMGHEIGHT = bpy.context.scene.imgheight
IMGWIDTH = bpy.context.scene.imgwidth
#If it already exists, remove it.
if(imgname in bpy.data.images):
bpy.data.images.remove(bpy.data.images[imgname])
#Create image 32 bit or not 32 bit
if thisbake == "normal" :
image = bpy.data.images.new(imgname, IMGWIDTH, IMGHEIGHT, float_buffer=True)
else:
image = bpy.data.images.new(imgname, IMGWIDTH, IMGHEIGHT, float_buffer=False)
#Set tags
image["SB_objname"] = objname
image["SB_batch"] = batch
image["SB_globalmode"] = global_mode
image["SB_thisbake"] = thisbake
#Always mark new images fake user when generated in the background
if "--background" in sys.argv:
image.use_fake_user = True
#Store it at bake operation level
MasterOperation.baked_textures.append(image)
def deselectAllNodes(nodes):
for node in nodes:
node.select = False
def findSocketConnectedtoP(pnode, thisbake):
#Get socket name for this bake mode
socketname = psocketname[thisbake]
#Get socket of the pnode
socket = pnode.inputs[socketname]
fromsocket = socket.links[0].from_socket
#Return the socket connected to the pnode
return fromsocket
def createdummynodes(nodetree, thisbake):
#Loop through pnodes
nodes = nodetree.nodes
for node in nodes:
if node.type == "BSDF_PRINCIPLED":
pnode = node
#Get socket name for this bake mode
socketname = psocketname[thisbake]
#Get socket of the pnode
psocket = pnode.inputs[socketname]
#If it has something plugged in, we can leave it here
if(len(psocket.links) > 0):
continue
#Get value of the unconnected socket
val = psocket.default_value
#If this is base col or ssscol, add an RGB node and set it's value to that of the socket
if(socketname == "Base Color" or socketname == "Subsurface Color"):
rgb = nodetree.nodes.new("ShaderNodeRGB")
rgb.outputs[0].default_value = val
rgb.label = "OmniBake"
nodetree.links.new(rgb.outputs[0], psocket)
#If this is anything else, use a value node
else:
vnode = nodetree.nodes.new("ShaderNodeValue")
vnode.outputs[0].default_value = val
vnode.label = "OmniBake"
nodetree.links.new(vnode.outputs[0], psocket)
def bakeoperation(thisbake, img):
printmsg(f"Beginning bake for {thisbake}")
if(thisbake != "normal"):
bpy.ops.object.bake(type="EMIT", save_mode="INTERNAL", use_clear=True)
else:
bpy.ops.object.bake(type="NORMAL", save_mode="INTERNAL", use_clear=True)
#Always pack the image for now
img.pack()
def startingChecks(objects, bakemode):
messages = []
if len(objects) == 0:
messages.append("ERROR: Nothing selected for bake")
#Are any of our objects hidden?
for obj in objects:
if (obj.hide_viewport == True) or (obj.hide_get(view_layer=bpy.context.view_layer) == True):
messages.append(f"ERROR: Object '{obj.name}' is hidden in viewport (eye icon in outliner) or in the current view lawyer (computer screen icon in outliner)")
#What about hidden from rendering?
for obj in objects:
if obj.hide_render:
messages.append(f"ERROR: Object '{obj.name}' is hidden for rendering (camera icon in outliner)")
#None of the objects can have zero faces
for obj in objects:
if len(obj.data.polygons) < 1:
messages.append(f"ERROR: Object '{obj.name}' has no faces")
if(bpy.context.mode != "OBJECT"):
messages.append("ERROR: Not in object mode")
#PBR Bake Checks
for obj in objects:
#Is it mesh?
if obj.type != "MESH":
messages.append(f"ERROR: Object {obj.name} is not mesh")
#Must continue here - other checks will throw exceptions
continue
#Are UVs OK?
if bpy.context.scene.newUVoption == False and len(obj.data.uv_layers) == 0:
messages.append(f"ERROR: Object {obj.name} has no UVs, and you aren't generating new ones")
continue
#Are materials OK? Fix if not
if not checkObjectValidMaterialConfig(obj):
fix_invalid_material_config(obj)
#Do all materials have valid PBR config?
if bpy.context.scene.more_shaders == False:
for slot in obj.material_slots:
mat = slot.material
result = checkMatsValidforPBR(mat)
if len(result) > 0:
for node_name in result:
messages.append(f"ERROR: Node '{node_name}' in material '{mat.name}' on object '{obj.name}' is not valid for PBR bake. In order to use more than just Princpled, Emission, and Mix Shaders, turn on 'Use additional Shader Types'!")
else:
for slot in obj.material_slots:
mat = slot.material
result = checkExtraMatsValidforPBR(mat)
if len(result) > 0:
for node_name in result:
messages.append(f"ERROR: Node '{node_name}' in material '{mat.name}' on object '{obj.name}' is not supported")
#Let's report back
if len(messages) != 0:
ShowMessageBox(messages, "Errors occured", "ERROR")
return False
else:
#If we get here then everything looks good
return True
#------------------------------------------
def processUVS():
current_bake_op = MasterOperation.current_bake_operation
#------------------NEW UVS ------------------------------------------------------------
if bpy.context.scene.newUVoption:
printmsg("We are generating new UVs")
printmsg("We are unwrapping each object individually with Smart UV Project")
objs = current_bake_op.bake_objects
for obj in objs:
if("OmniBake" in obj.data.uv_layers):
obj.data.uv_layers.remove(obj.data.uv_layers["OmniBake"])
obj.data.uv_layers.new(name="OmniBake")
obj.data.uv_layers["OmniBake"].active = True
#Will set active object
selectOnlyThis(obj)
#Blender 2.91 kindly breaks Smart UV Project in object mode so... yeah... thanks
bpy.ops.object.mode_set(mode="EDIT", toggle=False)
#Unhide any geo that's hidden in edit mode or it'll cause issues.
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action="SELECT")
bpy.ops.mesh.reveal()
bpy.ops.uv.smart_project(island_margin=bpy.context.scene.unwrapmargin)
bpy.ops.object.mode_set(mode="OBJECT", toggle=False)
#------------------END NEW UVS ------------------------------------------------------------
else: #i.e. New UV Option was not selected
printmsg("We are working with the existing UVs")
if bpy.context.scene.prefer_existing_sbmap:
printmsg("We are preferring existing UV maps called OmniBake. Setting them to active")
for obj in current_bake_op.bake_objects:
if("OmniBake" in obj.data.uv_layers):
obj.data.uv_layers["OmniBake"].active = True
#Before we finish, restore the original selected and active objects
bpy.ops.object.select_all(action="DESELECT")
for obj in current_bake_op.orig_objects:
obj.select_set(True)
bpy.context.view_layer.objects.active = current_bake_op.orig_active_object
#Done
return True
def restore_Original_UVs():
current_bake_op = MasterOperation.current_bake_operation
#First the bake objects
for obj in current_bake_op.bake_objects:
if MasterOperation.orig_UVs_dict[obj. name] != None:
original_uv = MasterOperation.orig_UVs_dict[obj.name]
obj.data.uv_layers.active = obj.data.uv_layers[original_uv]
def setupEmissionRunThrough(nodetree, m_output_node, thisbake, ismix=False):
nodes = nodetree.nodes
pnode = find_pnode(nodetree)
#Create emission shader
emissnode = nodes.new("ShaderNodeEmission")
emissnode.label = "OmniBake"
#Connect to output
if(ismix):
#Find the existing mix node before we create a new one
existing_m_node = find_mnode(nodetree)
#Add a mix shader node and label it
mnode = nodes.new("ShaderNodeMixShader")
mnode.label = "OmniBake"
#Connect new mix node to the output
fromsocket = mnode.outputs[0]
tosocket = m_output_node.inputs[0]
nodetree.links.new(fromsocket, tosocket)
#Connect new emission node to the first mix slot (leaving second empty)
fromsocket = emissnode.outputs[0]
tosocket = mnode.inputs[1]
nodetree.links.new(fromsocket, tosocket)
#If there is one, plug the factor from the original mix node into our new mix node
if(len(existing_m_node.inputs[0].links) > 0):
fromsocket = existing_m_node.inputs[0].links[0].from_socket
tosocket = mnode.inputs[0]
nodetree.links.new(fromsocket, tosocket)
#If no input, add a value node set to same as the mnode factor
else:
val = existing_m_node.inputs[0].default_value
vnode = nodes.new("ShaderNodeValue")
vnode.label = "OmniBake"
vnode.outputs[0].default_value = val
fromsocket = vnode.outputs[0]
tosocket = mnode.inputs[0]
nodetree.links.new(fromsocket, tosocket)
else:
#Just connect our new emission to the output
fromsocket = emissnode.outputs[0]
tosocket = m_output_node.inputs[0]
nodetree.links.new(fromsocket, tosocket)
#Create dummy nodes for the socket for this bake if needed
createdummynodes(nodetree, pnode, thisbake)
#Connect whatever is in Principled Shader for this bakemode to the emission
fromsocket = findSocketConnectedtoP(pnode, thisbake)
tosocket = emissnode.inputs[0]
nodetree.links.new(fromsocket, tosocket)
#---------------------Node Finders---------------------------
def find_pnode(nodetree):
nodes = nodetree.nodes
for node in nodes:
if(node.type == "BSDF_PRINCIPLED"):
return node
#We never found it
return False
def find_enode(nodetree):
nodes = nodetree.nodes
for node in nodes:
if(node.type == "EMISSION"):
return node
#We never found it
return False
def find_mnode(nodetree):
nodes = nodetree.nodes
for node in nodes:
if(node.type == "MIX_SHADER"):
return node
#We never found it
return False
def find_onode(nodetree):
nodes = nodetree.nodes
for node in nodes:
if(node.type == "OUTPUT_MATERIAL"):
return node
#We never found it
return False
def checkObjectValidMaterialConfig(obj):
#Firstly, check it actually has material slots
if len(obj.material_slots) == 0:
return False
#Check the material slots all have a material assigned
for slot in obj.material_slots:
if slot.material == None:
return False
#All materials must be using nodes
for slot in obj.material_slots:
if slot.material.use_nodes == False:
return False
#If we get here, everything looks good
return True
def getMatType(nodetree):
if (find_pnode(nodetree) and find_mnode(nodetree)):
return "MIX"
elif(find_pnode(nodetree)):
return "PURE_P"
elif(find_enode(nodetree)):
return "PURE_E"
else:
return "INVALID"
def prepObjects(objs, baketype):
current_bake_op = MasterOperation.current_bake_operation
printmsg("Creating prepared object")
#First we prepare objectes
export_objects = []
for obj in objs:
#-------------Create the prepared mesh----------------------------------------
#Object might have a truncated name. Should use this if it's there
objname = trunc_if_needed(obj.name)
new_obj = obj.copy()
new_obj.data = obj.data.copy()
new_obj["SB_createdfrom"] = obj.name
#clear all materials
new_obj.data.materials.clear()
new_obj.name = objname + "_OmniBake"
#Create a collection for our baked objects if it doesn't exist
if "OmniBake_Bakes" not in bpy.data.collections:
c = bpy.data.collections.new("OmniBake_Bakes")
bpy.context.scene.collection.children.link(c)
#Make sure it's visible and enabled for current view laywer or it screws things up
bpy.context.view_layer.layer_collection.children["OmniBake_Bakes"].exclude = False
bpy.context.view_layer.layer_collection.children["OmniBake_Bakes"].hide_viewport = False
c = bpy.data.collections["OmniBake_Bakes"]
#Link object to our new collection
c.objects.link(new_obj)
#Append this object to the export list
export_objects.append(new_obj)
#---------------------------------UVS--------------------------------------
uvlayers = new_obj.data.uv_layers
#If we generated new UVs, it will be called "OmniBake" and we are using that. End of.
#Same if we are being called for Sketchfab upload, and last bake used new UVs
if bpy.context.scene.newUVoption:
pass
#If there is an existing map called OmniBake, and we are preferring it, use that
elif ("OmniBake" in uvlayers) and bpy.context.scene.prefer_existing_sbmap:
pass
#Even if we are not preferring it, if there is just one map called OmniBake, we are using that
elif ("OmniBake" in uvlayers) and len(uvlayers) <2:
pass
#If there is an existing map called OmniBake, and we are not preferring it, it has to go
#Active map becommes OmniBake
elif ("OmniBake" in uvlayers) and not bpy.context.scene.prefer_existing_sbmap:
uvlayers.remove(uvlayers["OmniBake"])
active_layer = uvlayers.active
active_layer.name = "OmniBake"
#Finally, if none of the above apply, we are just using the active map
#Active map becommes OmniBake
else:
active_layer = uvlayers.active
active_layer.name = "OmniBake"
#In all cases, we can now delete everything other than OmniBake
deletelist = []
for uvlayer in uvlayers:
if (uvlayer.name != "OmniBake"):
deletelist.append(uvlayer.name)
for uvname in deletelist:
uvlayers.remove(uvlayers[uvname])
#---------------------------------END UVS--------------------------------------
#Create a new material
#call it same as object + batchname + baked
mat = bpy.data.materials.get(objname + "_" + bpy.context.scene.batchName + "_baked")
if mat is None:
mat = bpy.data.materials.new(name=objname + "_" + bpy.context.scene.batchName +"_baked")
# Assign it to object
mat.use_nodes = True
new_obj.data.materials.append(mat)
#Set up the materials for each object
for obj in export_objects:
#Should only have one material
mat = obj.material_slots[0].material
nodetree = mat.node_tree
material_setup.create_principled_setup(nodetree, obj)
#Change object name to avoid collisions
obj.name = obj.name.replace("_OmniBake", "_Baked")
bpy.ops.object.select_all(action="DESELECT")
for obj in export_objects:
obj.select_set(state=True)
if (not bpy.context.scene.prepmesh) and (not "--background" in sys.argv):
#Deleted duplicated objects
for obj in export_objects:
bpy.data.objects.remove(obj)
#Add the created objects to the bake operation list to keep track of them
else:
for obj in export_objects:
MasterOperation.prepared_mesh_objects.append(obj)
def selectOnlyThis(obj):
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(state=True)
bpy.context.view_layer.objects.active = obj
def setup_pure_p_material(nodetree, thisbake):
#Create dummy nodes as needed
createdummynodes(nodetree, thisbake)
#Create emission shader
nodes = nodetree.nodes
m_output_node = find_onode(nodetree)
loc = m_output_node.location
#Create an emission shader
emissnode = nodes.new("ShaderNodeEmission")
emissnode.label = "OmniBake"
emissnode.location = loc
emissnode.location.y = emissnode.location.y + 200
#Connect our new emission to the output
fromsocket = emissnode.outputs[0]
tosocket = m_output_node.inputs[0]
nodetree.links.new(fromsocket, tosocket)
#Connect whatever is in Principled Shader for this bakemode to the emission
fromsocket = findSocketConnectedtoP(find_pnode(nodetree), thisbake)
tosocket = emissnode.inputs[0]
nodetree.links.new(fromsocket, tosocket)
def setup_pure_e_material(nodetree, thisbake):
#If baking something other than emission, mute the emission modes so they don't contaiminate our bake
if thisbake != "Emission":
nodes = nodetree.nodes
for node in nodes:
if node.type == "EMISSION":
node.mute = True
node.label = "OmniBakeMuted"
def setup_mix_material(nodetree, thisbake):
#No need to mute emission nodes. They are automuted by setting the RGBMix to black
nodes = nodetree.nodes
#Create dummy nodes as needed
createdummynodes(nodetree, thisbake)
#For every mix shader, create a mixrgb above it
#Also connect the factor input to the same thing
created_mix_nodes = {}
for node in nodes:
if node.type == "MIX_SHADER":
loc = node.location
rgbmix = nodetree.nodes.new("ShaderNodeMixRGB")
rgbmix.label = "OmniBake"
rgbmix.location = loc
rgbmix.location.y = rgbmix.location.y + 200
#If there is one, plug the factor from the original mix node into our new mix node
if(len(node.inputs[0].links) > 0):
fromsocket = node.inputs[0].links[0].from_socket
tosocket = rgbmix.inputs["Fac"]
nodetree.links.new(fromsocket, tosocket)
#If no input, add a value node set to same as the mnode factor
else:
val = node.inputs[0].default_value
vnode = nodes.new("ShaderNodeValue")
vnode.label = "OmniBake"
vnode.outputs[0].default_value = val
fromsocket = vnode.outputs[0]
tosocket = rgbmix.inputs[0]
nodetree.links.new(fromsocket, tosocket)
#Keep a dictionary with paired shader mix node
created_mix_nodes[node.name] = rgbmix.name
#Loop over the RGBMix nodes that we created
for node in created_mix_nodes:
mshader = nodes[node]
rgb = nodes[created_mix_nodes[node]]
#Mshader - Socket 1
#First, check if there is anything plugged in at all
if len(mshader.inputs[1].links) > 0:
fromnode = mshader.inputs[1].links[0].from_node
if fromnode.type == "BSDF_PRINCIPLED":
#Get the socket we are looking for, and plug it into RGB socket 1
fromsocket = findSocketConnectedtoP(fromnode, thisbake)
nodetree.links.new(fromsocket, rgb.inputs[1])
elif fromnode.type == "MIX_SHADER":
#If it's a mix shader on the other end, connect the equivilent RGB node
#Get the RGB node for that mshader
fromrgb = nodes[created_mix_nodes[fromnode.name]]
fromsocket = fromrgb.outputs[0]
nodetree.links.new(fromsocket, rgb.inputs[1])
elif fromnode.type == "EMISSION":
#Set this input to black
rgb.inputs[1].default_value = (0.0, 0.0, 0.0, 1)
else:
printmsg("Error, invalid node config")
else:
rgb.inputs[1].default_value = (0.0, 0.0, 0.0, 1)
#Mshader - Socket 2
if len(mshader.inputs[2].links) > 0:
fromnode = mshader.inputs[2].links[0].from_node
if fromnode.type == "BSDF_PRINCIPLED":
#Get the socket we are looking for, and plug it into RGB socket 2
fromsocket = findSocketConnectedtoP(fromnode, thisbake)
nodetree.links.new(fromsocket, rgb.inputs[2])
elif fromnode.type == "MIX_SHADER":
#If it's a mix shader on the other end, connect the equivilent RGB node
#Get the RGB node for that mshader
fromrgb = nodes[created_mix_nodes[fromnode.name]]
fromsocket = fromrgb.outputs[0]
nodetree.links.new(fromsocket, rgb.inputs[2])
elif fromnode.type == "EMISSION":
#Set this input to black
rgb.inputs[2].default_value = (0.0, 0.0, 0.0, 1)
else:
printmsg("Error, invalid node config")
else:
rgb.inputs[2].default_value = (0.0, 0.0, 0.0, 1)
#Find the output node with location
m_output_node = find_onode(nodetree)
loc = m_output_node.location
#Create an emission shader
emissnode = nodes.new("ShaderNodeEmission")
emissnode.label = "OmniBake"
emissnode.location = loc
emissnode.location.y = emissnode.location.y + 200
#Get the original mix node that was connected to the output node
socket = m_output_node.inputs["Surface"]
fromnode = socket.links[0].from_node
#Find our created mix node that is paired with it
rgbmix = nodes[created_mix_nodes[fromnode.name]]
#Plug rgbmix into emission
nodetree.links.new(rgbmix.outputs[0], emissnode.inputs[0])
#Plug emission into output
nodetree.links.new(emissnode.outputs[0], m_output_node.inputs[0])
#------------Long Name Truncation-----------------------
trunc_num = 0
trunc_dict = {}
def trunc_if_needed(objectname):
global trunc_num
global trunc_dict
#If we already truncated this, just return that
if objectname in trunc_dict:
printmsg(f"Object name {objectname} was previously truncated. Returning that.")
return trunc_dict[objectname]
#If not, let's see if we have to truncate it
elif len(objectname) >= 38:
printmsg(f"Object name {objectname} is too long and will be truncated")
trunc_num += 1
truncdobjectname = objectname[0:34] + "~" + str(trunc_num)
trunc_dict[objectname] = truncdobjectname
return truncdobjectname
#If nothing else, just return the original name
else:
return objectname
def untrunc_if_needed(objectname):
global trunc_num
global trunc_dict
for t in trunc_dict:
if trunc_dict[t] == objectname:
printmsg(f"Returning untruncated value {t}")
return t
return objectname
def ShowMessageBox(messageitems_list, title, icon = 'INFO'):
def draw(self, context):
for m in messageitems_list:
self.layout.label(text=m)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
#---------------Bake Progress--------------------------------------------
def write_bake_progress(current_operation, total_operations):
progress = int((current_operation / total_operations) * 100)
t = Path(tempfile.gettempdir())
t = t / f"OmniBake_Bgbake_{os.getpid()}"
with open(str(t), "w") as progfile:
progfile.write(str(progress))
#---------------End Bake Progress--------------------------------------------
past_items_dict = {}
def spot_new_items(initialise=True, item_type="images"):
global past_items_dict
if item_type == "images":
source = bpy.data.images
elif item_type == "objects":
source = bpy.data.objects
elif item_type == "collections":
source = bpy.data.collections
#First run
if initialise:
#Set to empty list for this item type
past_items_dict[item_type] = []
for source_item in source:
past_items_dict[item_type].append(source_item.name)
return True
else:
#Get the list of items for this item type from the dict
past_items_list = past_items_dict[item_type]
new_item_list_names = []
for source_item in source:
if source_item.name not in past_items_list:
new_item_list_names.append(source_item.name)
return new_item_list_names
#---------------Validation Checks-------------------------------------------
def checkMatsValidforPBR(mat):
nodes = mat.node_tree.nodes
valid = True
invalid_node_names = []
for node in nodes:
if len(node.outputs) > 0:
if node.outputs[0].type == "SHADER" and not (node.bl_idname == "ShaderNodeBsdfPrincipled" or node.bl_idname == "ShaderNodeMixShader" or node.bl_idname == "ShaderNodeEmission"):
#But is it actually connected to anything?
if len(node.outputs[0].links) >0:
invalid_node_names.append(node.name)
return invalid_node_names
def checkExtraMatsValidforPBR(mat):
nodes = mat.node_tree.nodes
valid = True
invalid_node_names = []
for node in nodes:
if len(node.outputs) > 0:
if node.outputs[0].type == "SHADER" and not (node.bl_idname == "ShaderNodeBsdfPrincipled" or
node.bl_idname == "ShaderNodeMixShader" or
node.bl_idname == "ShaderNodeAddShader" or
node.bl_idname == "ShaderNodeEmission" or
node.bl_idname == "ShaderNodeBsdfGlossy" or
node.bl_idname == "ShaderNodeBsdfGlass" or
node.bl_idname == "ShaderNodeBsdfRefraction" or
node.bl_idname == "ShaderNodeBsdfDiffuse" or
node.bl_idname == "ShaderNodeBsdfAnisotropic" or
node.bl_idname == "ShaderNodeBsdfTransparent"):
#But is it actually connected to anything?
if len(node.outputs[0].links) >0:
invalid_node_names.append(node.name)
print(invalid_node_names)
return invalid_node_names
def deselect_all_not_mesh():
import bpy
for obj in bpy.context.selected_objects:
if obj.type != "MESH":
obj.select_set(False)
#Do we still have an active object?
if bpy.context.active_object == None:
#Pick arbitary
bpy.context.view_layer.objects.active = bpy.context.selected_objects[0]
def fix_invalid_material_config(obj):
if "OmniBake_Placeholder" in bpy.data.materials:
mat = bpy.data.materials["OmniBake_Placeholder"]
else:
mat = bpy.data.materials.new("OmniBake_Placeholder")
bpy.data.materials["OmniBake_Placeholder"].use_nodes = True
# Assign it to object
if len(obj.material_slots) > 0:
#Assign it to every empty slot
for slot in obj.material_slots:
if slot.material == None:
slot.material = mat
else:
# no slots
obj.data.materials.append(mat)
#All materials must use nodes
for slot in obj.material_slots:
mat = slot.material
if mat.use_nodes == False:
mat.use_nodes = True
return True
def sacle_image_if_needed(img):
printmsg("Scaling images if needed")
context = bpy.context
width = img.size[0]
height = img.size[1]
proposed_width = 0
proposed_height = 0
if context.scene.texture_res == "0.5k": proposed_width, proposed_height = 512,512
if context.scene.texture_res == "1k": proposed_width, proposed_height = 1024,1024
if context.scene.texture_res == "2k": proposed_width, proposed_height = 1024*2,1024*2
if context.scene.texture_res == "4k": proposed_width, proposed_height = 1024*4,1024*4
if context.scene.texture_res == "8k": proposed_width, proposed_height = 1024*8,1024*8
if width != proposed_width or height != proposed_height:
img.scale(proposed_width, proposed_height)
def set_image_internal_col_space(image, thisbake):
if thisbake != "diffuse":
image.colorspace_settings.name = "Non-Color"
#------------------------Allow Additional Shaders----------------------------
def findProperInput(OName, pnode):
for input in pnode.inputs:
if OName == "Anisotropy":
OName = "Anisotropic"
if OName == "Rotation":
OName = "Anisotropic Rotation"
if OName == "Color":
OName = "Base Color"
if input.identifier == OName:
return input
def useAdditionalShaderTypes(nodetree, nodes):
count = 0
for node in nodes:
if (node.type == "BSDF_GLOSSY" or
node.type == "BSDF_GLASS" or
node.type == "BSDF_REFRACTION" or
node.type == "BSDF_DIFFUSE" or
node.type == "BSDF_ANISOTROPIC" or
node.type == "BSDF_TRANSPARENT" or
node.type == "ADD_SHADER"):
if node.type == "ADD_SHADER":
pnode = nodes.new("ShaderNodeMixShader")
pnode.label = "mixNew" + str(count)
else:
pnode = nodes.new("ShaderNodeBsdfPrincipled")
pnode.label = "BsdfNew" + str(count)
pnode.location = node.location
pnode.use_custom_color = True
pnode.color = (0.3375297784805298, 0.4575316309928894, 0.08615386486053467)
for input in node.inputs:
if len(input.links) != 0:
fromNode = input.links[0].from_node
for output in fromNode.outputs:
if len(output.links) != 0:
for linkOut in output.links:
if linkOut.to_node == node:
inSocket = findProperInput(input.identifier, pnode)
nodetree.links.new(output, inSocket)
else:
inSocket = findProperInput(input.identifier, pnode)
if inSocket.name != "Shader":
inSocket.default_value = input.default_value
if len(node.outputs[0].links) != 0:
for link in node.outputs[0].links:
toNode = link.to_node
for input in toNode.inputs:
if len(input.links) != 0:
if input.links[0].from_node == node:
nodetree.links.new(pnode.outputs[0], input)
if node.type == "BSDF_REFRACTION" or node.type == "BSDF_GLASS":
pnode.inputs[15].default_value = 1
if node.type == "BSDF_DIFFUSE":
pnode.inputs[5].default_value = 0
if node.type == "BSDF_ANISOTROPIC" or node.type == "BSDF_GLOSSY":
pnode.inputs[4].default_value = 1
pnode.inputs[5].default_value = 0
if node.type == "BSDF_TRANSPARENT":
pnode.inputs[7].default_value = 0
pnode.inputs[15].default_value = 1
pnode.inputs[14].default_value = 1
pnode.hide = True
pnode.select = False
nodetree.nodes.remove(node)
count += 1 | 38,803 | Python | 36.419479 | 252 | 0.592093 |
NVIDIA-Omniverse/blender_omniverse_addons/README.md | # blender_omniverse_addons
This repository contains the source code for NVIDIA Omniverse Add-ons for Blender, including:
* [Omni Panel](https://docs.omniverse.nvidia.com/con_connect/con_connect/blender/omni-panel.html) - Utility functions for particles and material conversions.
* [Audio2Face Panel](https://docs.omniverse.nvidia.com/con_connect/con_connect/blender/audio2face.html) - A tool that helps get characters into Audio2Face, as well as assisting in the import of shape keys and animation clips onto rigged Blender characters.
* [Scene Optimizer](https://docs.omniverse.nvidia.com/con_connect/con_connect/blender/scene-optimizer.html) - A tool for quickly optimizing meshes, correcting bad geometry, creating automated UVs, and generating collision/proxy geometry. The user can pick any of six optional tools to run, and run them all on either selected meshes or all meshes in a given scene.
* UMM - The Universal Material Mapper Add-on for Blender.
## Usage
For information on usage, including video tutorials, please see the [Blender Omniverse documentation](https://docs.omniverse.nvidia.com/con_connect/con_connect/blender.html).
| 1,150 | Markdown | 70.937496 | 364 | 0.797391 |
NVIDIA-Omniverse/blender_omniverse_addons/omni_audio2face/__init__.py |
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
bl_info = {
"name": "Audio2Face Tools",
"author": "NVIDIA Corporation",
"version": (1, 0, 1),
"blender": (3, 4, 0),
"location": "View3D > Toolbar > Omniverse",
"description": "NVIDIA Omniverse tools for working with Audio2Face",
"warning": "",
"doc_url": "",
"category": "Omniverse",
}
## ======================================================================
import sys
from importlib import reload
import bpy
from bpy.props import (BoolProperty, CollectionProperty, EnumProperty, FloatProperty,
IntProperty, PointerProperty, StringProperty)
from omni_audio2face import (operators, ui)
for module in (operators, ui):
reload(module)
from omni_audio2face.ui import OBJECT_PT_Audio2FacePanel
from omni_audio2face.operators import (
OMNI_OT_PrepareScene,
OMNI_OT_MarkExportMesh,
OMNI_OT_ExportPreparedScene,
OMNI_OT_ChooseUSDFile,
OMNI_OT_ChooseAnimCache,
OMNI_OT_ImportRigFile,
OMNI_OT_TransferShapeData,
OMNI_OT_ImportAnimation,
)
## ======================================================================
class Audio2FaceToolsSettings(bpy.types.PropertyGroup):
## shapes stuff
use_face_selection: BoolProperty(description="Use Face Selection")
export_project: BoolProperty(description="Export Project File", default=True)
export_filepath: StringProperty(description="Export Path")
import_filepath: StringProperty(description="Shapes Import Path")
## anim import settings
import_anim_path: StringProperty(description="Anim Cache Path")
anim_start_type: EnumProperty(
items=[("CURRENT", "At Play Head", "Load Clip at the playhead"),
("CUSTOM", "Custom", "Choose a custom start frame")],
default="CURRENT")
anim_start_frame: IntProperty(default=0)
anim_frame_rate: FloatProperty(default=60.0, min=1.0)
anim_apply_scale: BoolProperty(default=True)
anim_set_range: BoolProperty(default=False)
anim_load_to: EnumProperty(
items=[("CURRENT", "Current Action", "Load curves onto current Action"),
("CLIP", "Clip", "Load curves as a new Action for NLE use")],
default="CURRENT")
anim_overwrite: BoolProperty(default=False, name="Overwrite Existing Clips")
## Store pointers to all the meshes for the full setup.
mesh_skin: PointerProperty(type=bpy.types.Object)
mesh_tongue: PointerProperty(type=bpy.types.Object)
mesh_eye_left: PointerProperty(type=bpy.types.Object)
mesh_eye_right: PointerProperty(type=bpy.types.Object)
mesh_gums_lower: PointerProperty(type=bpy.types.Object)
transfer_apply_fix: BoolProperty(name="Apply Fix",
description="Apply Basis to points not part of the head during transfer",
default=False)
## ======================================================================
classes = (
Audio2FaceToolsSettings,
OBJECT_PT_Audio2FacePanel,
OMNI_OT_PrepareScene,
OMNI_OT_MarkExportMesh,
OMNI_OT_ExportPreparedScene,
OMNI_OT_ChooseUSDFile,
OMNI_OT_ChooseAnimCache,
OMNI_OT_ImportRigFile,
OMNI_OT_TransferShapeData,
OMNI_OT_ImportAnimation,
)
def register():
unregister()
for item in classes:
bpy.utils.register_class(item)
bpy.types.Scene.audio2face = bpy.props.PointerProperty(type=Audio2FaceToolsSettings)
bpy.types.Object.a2f_original = bpy.props.PointerProperty(type=bpy.types.Object)
version = bl_info["version"]
version = str(version[0]) + str(version[1]) + str(version[2])
OBJECT_PT_Audio2FacePanel.version = f"{str(version[0])}.{str(version[1])}.{str(version[2])}"
## ======================================================================
def unregister():
# User preferences
for item in classes:
try:
bpy.utils.unregister_class(item)
except:
continue
if hasattr(bpy.types.Scene, "audio2face"):
del bpy.types.Scene.audio2face
if hasattr(bpy.types.Object, "a2f_original"):
del bpy.types.Object.a2f_original
| 3,862 | Python | 30.153226 | 93 | 0.682289 |
NVIDIA-Omniverse/blender_omniverse_addons/omni_audio2face/operators.py |
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import json
import os
import re
import sys
from typing import *
import numpy as np
import bpy
import bmesh
from bpy.props import (BoolProperty, EnumProperty, FloatProperty, IntProperty, StringProperty)
from bpy.types import (Collection, Context, Event, Mesh, Object, Scene)
from mathutils import *
## ======================================================================
def _get_filepath(scene:Scene, as_import:bool=False) -> str:
if as_import:
result = scene.audio2face.import_filepath.strip()
else:
result = scene.audio2face.export_filepath.strip()
return result
## ======================================================================
def _get_or_create_collection(collection:Collection, name:str) -> Collection:
"""Find a child collection of the specified collection, or create it if it does not exist."""
result = collection.children.get(name, None)
if not result:
result = bpy.data.collections.new(name)
collection.children.link(result)
## Make sure this is visible or things'll break in other ways down the line
if result.is_evaluated:
result = result.original
result.hide_render = result.hide_viewport = result.hide_select = False
result_lc = [x for x in bpy.context.view_layer.layer_collection.children if x.collection is result]
if len(result_lc):
result_lc = result_lc[0]
result_lc.exclude = False
result_lc.hide_viewport = False
else:
print(f"-- Warning: No layer collection found for {result.name}")
return result
## ======================================================================
def ensure_scene_collections(scene:Scene) -> Tuple[bpy.types.Collection]:
"""Make sure that all Audio2Face scene collections exist."""
a2f_collection = _get_or_create_collection(scene.collection, "Audio2Face")
a2f_export = _get_or_create_collection(a2f_collection, "A2F Export")
a2f_export_static = _get_or_create_collection(a2f_export, "A2F Export Static")
a2f_export_dynamic = _get_or_create_collection(a2f_export, "A2F Export Dynamic")
return a2f_collection, a2f_export, a2f_export_static, a2f_export_dynamic
## ======================================================================
def _get_base_collection() -> Collection:
return bpy.data.collections.get("Audio2Face", None)
def _get_import_collection() -> Collection:
return bpy.data.collections.get("A2F Import", None)
def _get_export_collection() -> Collection:
return bpy.data.collections.get("A2F Export", None)
## ======================================================================
class OMNI_OT_PrepareScene(bpy.types.Operator):
"""Prepares the active scene for interaction with Audio2Face"""
bl_idname = "audio2face.prepare_scene"
bl_label = "Prepare Scene for Audio2Face"
bl_options = {"REGISTER", "UNDO"}
@classmethod
def poll(cls, context:Context) -> bool:
return bool(context.scene)
def execute(self, context:Context) -> Set[str]:
scene = context.scene
ensure_scene_collections(scene)
self.report({"INFO"}, "A2F: Scene is prepped.")
return {'FINISHED'}
## ======================================================================
def selected_mesh_objects(context:Context) -> List[Object]:
"""Return a filtered list of Mesh objects from the context."""
a2f_collection = bpy.data.collections.get("Audio2Face", None)
export_objects = {x.name for x in a2f_collection.all_objects} if a2f_collection else {}
result = [x for x in context.selected_objects if x.data and isinstance(x.data, bpy.types.Mesh)]
result = list(filter(lambda x: not x.name in export_objects and x.data and isinstance(x.data, bpy.types.Mesh), result))
return result
## ======================================================================
def export_mesh_poll(context:Context) -> bool:
"""
Check for a mesh object selection if use_face_selection is false,
or an edit mode face selection otherwise.
"""
valid_mesh = len(selected_mesh_objects(context))
is_poly_edit_mode = context.tool_settings.mesh_select_mode[2]
if context.scene.audio2face.use_face_selection:
if (context.mode == "EDIT_MESH"
and is_poly_edit_mode
and valid_mesh
and len(context.active_object.data.count_selected_items())
and context.active_object.data.count_selected_items()[2]):
return True
else:
if context.mode == "OBJECT" and valid_mesh:
return True
return False
## ======================================================================
def make_valid_name(name:str) -> str:
result = name.replace("-","_").replace(" ","_").replace(".","_")
return result
## ======================================================================
def process_export_mesh(orig:Object, target_collection:Collection, is_dynamic:bool, split:bool):
"""
Processes the selected mesh for export, adding original vertex
indices and copying it over into the target collection.
"""
assert isinstance(orig.data, bpy.types.Mesh)
obj_dupe_name = make_valid_name(orig.name) + "__Audio2Face_EX"
if obj_dupe_name in bpy.data.objects:
bpy.data.objects.remove(bpy.data.objects[obj_dupe_name])
mesh_dupe = orig.data.copy()
mesh_dupe.name = make_valid_name(orig.data.name) + "__Audio2Face_EX"
obj_dupe = bpy.data.objects.new(obj_dupe_name, mesh_dupe)
target_collection.objects.link(obj_dupe)
obj_dupe.a2f_original = orig
bpy.ops.object.mode_set(mode="OBJECT")
orig.select_set(False)
obj_dupe.select_set(True)
## Clean out all extraneous data.
for item in obj_dupe.modifiers, obj_dupe.vertex_groups:
item.clear()
obj_dupe.shape_key_clear()
## Add a custom data layer to remember the original point indices.
attr = obj_dupe.data.attributes.get("index_orig",
obj_dupe.data.attributes.new("index_orig", "INT", "POINT"))
vertex_count = len(obj_dupe.data.vertices)
attr.data.foreach_set("value", np.arange(vertex_count))
bpy.ops.object.mode_set(mode="OBJECT")
if split:
## Delete all unselected faces.
deps = bpy.context.evaluated_depsgraph_get()
indices = [x.index for x in orig.data.polygons if not x.select]
bm = bmesh.new()
bm.from_object(obj_dupe, deps)
bm.faces.ensure_lookup_table()
## Must convert to list; delete does not accept map objects
selected = list(map(lambda x: bm.faces[x], indices))
bpy.ops.object.mode_set(mode="EDIT")
bmesh.ops.delete(bm, geom=selected, context="FACES")
bpy.ops.object.mode_set(mode="OBJECT")
bm.to_mesh(obj_dupe.data)
## Make sure to snap the object into place.
obj_dupe.matrix_world = orig.matrix_world.copy()
return obj_dupe
## =====================================================a=================
class OMNI_OT_MarkExportMesh(bpy.types.Operator):
"""Tags the selected mesh as static for Audio2Face."""
bl_idname = "audio2face.mark_export_mesh"
bl_label = "Mark Mesh for Export"
bl_options = {"REGISTER", "UNDO"}
is_dynamic: BoolProperty(description="Mesh is Dynamic", default=False)
@classmethod
def poll(cls, context:Context) -> bool:
return export_mesh_poll(context)
def execute(self, context:Context) -> Set[str]:
a2f_collection, a2f_export, a2f_export_static, a2f_export_dynamic = ensure_scene_collections(context.scene)
target_collection = a2f_export_dynamic if self.is_dynamic else a2f_export_static
split = context.scene.audio2face.use_face_selection
processed_meshes = []
for mesh in selected_mesh_objects(context):
context.view_layer.objects.active = mesh
result = process_export_mesh(mesh, target_collection, self.is_dynamic, split)
processed_meshes.append(result)
context.view_layer.objects.active = processed_meshes[-1]
return {'FINISHED'}
## ======================================================================
class OMNI_OT_ChooseUSDFile(bpy.types.Operator):
"""File chooser with proper extensions."""
bl_idname = "collections.usd_choose_file"
bl_label = "Choose USD File"
bl_options = {"REGISTER"}
## Required for specifying extensions.
filepath: StringProperty(subtype="FILE_PATH")
operation: EnumProperty(items=[("IMPORT", "Import", ""),("EXPORT", "Export", "")], default="IMPORT", options={"HIDDEN"})
filter_glob: StringProperty(default="*.usd;*.usda;*.usdc", options={"HIDDEN"})
check_existing: BoolProperty(default=True, options={"HIDDEN"})
def execute(self, context:Context):
real_path = os.path.abspath(bpy.path.abspath(self.filepath))
real_path = real_path.replace("\\", "/")
if self.operation == "EXPORT":
context.scene.audio2face.export_filepath = real_path
else:
context.scene.audio2face.import_filepath = real_path
return {"FINISHED"}
def invoke(self, context:Context, event:Event) -> Set[str]:
if len(self.filepath.strip()) == 0:
self.filepath = "untitled.usdc"
context.window_manager.fileselect_add(self)
return {"RUNNING_MODAL"}
## ======================================================================
class OMNI_OT_ChooseAnimCache(bpy.types.Operator):
"""File chooser with proper extensions."""
bl_idname = "collections.usd_choose_anim_cache"
bl_label = "Choose Animation Cache"
bl_options = {"REGISTER"}
## Required for specifying extensions.
filepath: StringProperty(subtype="FILE_PATH")
filter_glob: StringProperty(default="*.usd;*.usda;*.usdc;*.json", options={"HIDDEN"})
check_existing: BoolProperty(default=True, options={"HIDDEN"})
def execute(self, context:Context):
real_path = os.path.abspath(bpy.path.abspath(self.filepath))
real_path = real_path.replace("\\", "/")
context.scene.audio2face.import_anim_path = real_path
return {"FINISHED"}
def invoke(self, context:Context, event:Event) -> Set[str]:
context.window_manager.fileselect_add(self)
return {"RUNNING_MODAL"}
## ======================================================================
class OMNI_OT_ExportPreparedScene(bpy.types.Operator):
"""Exports prepared scene as USD for Audio2Face."""
bl_idname = "audio2face.export_prepared_scene"
bl_label = "Export Prepared Scene"
bl_options = {"REGISTER"}
@classmethod
def poll(cls, context:Context) -> bool:
a2f_export = _get_export_collection()
child_count = len(a2f_export.all_objects) if a2f_export else 0
path = _get_filepath(context.scene)
return a2f_export and child_count and len(path)
def execute(self, context:Context) -> Set[str]:
## Grab filepath before the scene switches
scene = context.scene
filepath = _get_filepath(scene)
export_scene = bpy.data.scenes.get("a2f_export",
bpy.data.scenes.new("a2f_export"))
for child_collection in list(export_scene.collection.children):
export_scene.collection.children.remove(child_collection)
export_collection = _get_export_collection()
export_scene.collection.children.link(export_collection)
context.window.scene = export_scene
args = {
"filepath": filepath,
"start": scene.frame_current,
"end": scene.frame_current,
"convert_to_cm": False,
"export_lights": False,
"export_cameras": False,
"export_materials": False,
"export_textures": False,
"default_prim_path": "/World",
"root_prim_path": "/World",
}
result = bpy.ops.wm.usd_export(**args)
context.window.scene = scene
bpy.data.scenes.remove(export_scene)
export_scene = None
## generate the project file
if scene.audio2face.export_project:
project_filename = os.path.basename(filepath)
skin = scene.audio2face.mesh_skin
tongue = scene.audio2face.mesh_tongue
eye_left = scene.audio2face.mesh_eye_left
eye_right= scene.audio2face.mesh_eye_right
gums = scene.audio2face.mesh_gums_lower
a2f_export_static = bpy.data.collections.get("A2F Export Static", None)
static_objects = list(a2f_export_static.objects) if a2f_export_static else []
a2f_export_dynamic = bpy.data.collections.get("A2F Export Dynamic", None)
dynamic_objects = list(a2f_export_dynamic.objects) if a2f_export_dynamic else []
for mesh in skin, tongue:
if mesh in dynamic_objects:
dynamic_objects.pop(dynamic_objects.index(mesh))
for mesh in eye_left, eye_right, gums:
if mesh in static_objects:
static_objects.pop(static_objects.index(mesh))
transfer_data = ""
if skin:
transfer_data += '\t\tstring mm:skin = "/World/character_root/{}/{}"\n'.format(make_valid_name(skin.name),
make_valid_name(skin.data.name))
if tongue:
transfer_data += '\t\tstring mm:tongue = "/World/character_root/{}/{}"\n'.format(make_valid_name(tongue.name),
make_valid_name(tongue.data.name))
if eye_left:
transfer_data += '\t\tstring[] mm:l_eye = ["/World/character_root/{}/{}"]\n'.format(make_valid_name(eye_left.name),
make_valid_name(eye_left.data.name))
if eye_right:
transfer_data += '\t\tstring[] mm:r_eye = ["/World/character_root/{}/{}"]\n'.format(make_valid_name(eye_right.name),
make_valid_name(eye_right.data.name))
if gums:
transfer_data += '\t\tstring[] mm:gums = ["/World/character_root/{}/{}"]\n'.format(make_valid_name(gums.name),
make_valid_name(gums.data.name))
if len(static_objects):
transfer_data += '\t\tstring[] mm:extra_static = [{}]\n'.format(
', '.join(['"/World/character_root/{}/{}"'.format(make_valid_name(x.name), make_valid_name(x.data.name))
for x in static_objects])
)
if len(dynamic_objects):
transfer_data += '\t\tstring[] mm:extra_dynamic = [{}]\n'.format(
', '.join(['"/World/character_root/{}/{}"'.format(make_valid_name(x.name), make_valid_name(x.data.name))
for x in dynamic_objects])
)
template = ""
template_path = os.sep.join([os.path.dirname(os.path.abspath(__file__)), "templates", "project_template.usda"])
with open(template_path, "r") as fp:
template = fp.read()
template = template.replace("%filepath%", project_filename)
template = template.replace("%transfer_data%", transfer_data)
project_usd_filepath = filepath.rpartition(".")[0] + "_project.usda"
with open(project_usd_filepath, "w") as fp:
fp.write(template)
self.report({"INFO"}, f"Exported project to: '{project_usd_filepath}'")
else:
self.report({"INFO"}, f"Exported head to: '{filepath}'")
return result
## ======================================================================
def _abs_path(file_path:str) -> str:
if not len(file_path) > 2:
return file_path
if file_path[0] == '/' and file_path[1] == '/':
file_path = bpy.path.abspath(file_path)
return os.path.abspath(file_path)
## ======================================================================
class OMNI_OT_ImportRigFile(bpy.types.Operator):
"""Imports a rigged USD file from Audio2Face"""
bl_idname = "audio2face.import_rig"
bl_label = "Import Rig File"
bl_options = {"REGISTER", "UNDO"}
@classmethod
def poll(cls, context:Context) -> bool:
return len(_get_filepath(context.scene, as_import=True))
def execute(self, context:Context) -> Set[str]:
filepath = _get_filepath(context.scene, as_import=True)
args = {
"filepath": filepath,
"import_skeletons": False,
"import_materials": False,
}
scene = context.scene
## Switching the active collection requires this odd code.
base = _get_or_create_collection(scene.collection, "Audio2Face")
import_col = _get_or_create_collection(base, "A2F Import")
base_lc = [x for x in context.view_layer.layer_collection.children if x.collection is base][0]
import_lc = [x for x in base_lc.children if x.collection is import_col][0]
context.view_layer.active_layer_collection = import_lc
if not context.mode == 'OBJECT':
try:
bpy.ops.object.mode_set(mode="OBJECT")
except RuntimeError:
pass
if len(import_col.all_objects):
bpy.ops.object.select_all(action="DESELECT")
## Let's clean out the import collection on each go to keep things simple
bpy.ops.object.select_same_collection(collection=import_col.name)
bpy.ops.object.delete()
## Make sure the import collection is selected so the imported objects
## get assigned to it.
# scene.view_layers[0].active_layer_collection.collection = import_col
bpy.ops.object.select_all(action='DESELECT')
override = context.copy()
override["collection"] = bpy.data.collections["A2F Import"]
result = bpy.ops.wm.usd_import(**args)
roots = [x for x in import_col.objects if not x.parent]
for root in roots:
## bugfix: don't reset rotation, since there may have been a rotation
## carried over from the blender scene and we want to line up visibly
## even though it has no bearing on the shape transfer.
root.scale = [1.0, 1.0, 1.0]
## Strip out any childless empties, like joint1.
empties = [x for x in import_col.objects if not len(x.children) and x.type == "EMPTY"]
for empty in empties:
bpy.data.objects.remove(empty)
self.report({"INFO"}, f"Imported Rig from: {filepath}")
return {"FINISHED"}
## ======================================================================
class AnimData:
"""Small data holder unifying what's coming in from JSON and USD(A)"""
def __init__(self, clip_name:str, shapes:List[str], key_data:List[List[float]], start_frame:int=0, frame_rate:float=60.0):
self.clip_name = clip_name
self.shapes = shapes
self.num_frames = len(key_data)
self.key_data = self._swizzle_data(key_data)
self.start_frame = start_frame
self.frame_rate = frame_rate
def curves(self):
for index, name in enumerate(self.shapes):
yield f'key_blocks["{name}"].value', self.key_data[index]
def _swizzle_data(self, data:List[List[float]]) -> List[List[float]]:
"""Massage the data a bit for writing directly to the curves"""
result = []
for index, _ in enumerate(self.shapes):
result.append( [data[frame][index] for frame in range(self.num_frames)] )
return result
class OMNI_OT_ImportAnimation(bpy.types.Operator):
"""Imports a shape key animation from an Audio2Face USDA file or JSON"""
bl_idname = "audio2face.import_animation"
bl_label = "Import Animation"
bl_options = {"REGISTER", "UNDO"}
start_type: EnumProperty(
name="Start Type",
items=[("CURRENT", "Current Action", "Load Clip at the playhead"),
("CUSTOM", "Custom", "Choose a custom start frame")],
default="CURRENT")
start_frame: IntProperty(default=1, name="Start Frame", description="Align start of animation to this frame")
frame_rate: FloatProperty(default=60.0, min=1.0, name="Frame Rate", description="Frame Rate of file you're importing")
set_range: BoolProperty(default=False, name="Set Range", description="If checked, set the scene animation frame range to the imported file's range")
apply_scale: BoolProperty(default=False, name="Apply Clip Scale",
description="If checked and the clip framerate differs from the scene, scale the keys to match")
load_to: EnumProperty(
name="Load To",
description="Load animation to current Action, or to a new Action Clip",
items=[("CURRENT", "Current Action", "Load curves onto current Action"),
("CLIP", "Clip", "Load curves as a new Action Clip (for NLE use)")],
default="CURRENT")
overwrite: BoolProperty(default=False, name="Overwrite Existing Clips")
@classmethod
def poll(cls, context:Context) -> bool:
have_file = len(context.scene.audio2face.import_anim_path)
have_mesh = context.active_object and context.active_object.type == "MESH"
have_selection = context.active_object in context.selected_objects
is_object_mode = context.mode == "OBJECT"
return all([have_file, have_mesh, have_selection, is_object_mode])
def apply_animation(self, animation:AnimData, ob:Object):
shapes = ob.data.shape_keys
action = None
start_frame = bpy.context.scene.frame_current if self.start_type == "CURRENT" else self.start_frame
if shapes.animation_data is None:
shapes.animation_data_create()
nla_tracks = shapes.animation_data.nla_tracks
if self.load_to == "CLIP":
def _predicate(track):
for strip in track.strips:
if strip.action and strip.action.name == animation.clip_name:
return True
return False
if len(nla_tracks):
existing_tracks = list(filter(_predicate, nla_tracks))
if len(existing_tracks) and not self.overwrite:
self.report({"ERROR"}, f"Clip named {animation.clip_name} already exists; aborting.")
return False
else:
## remove the track(s) specified for overwrites
for track in existing_tracks:
self.report({"INFO"}, f"Removing old track {track.name}")
nla_tracks.remove(track)
if not animation.clip_name in bpy.data.actions:
bpy.data.actions.new(animation.clip_name)
action = bpy.data.actions[animation.clip_name]
offset = 0
else:
if not shapes.animation_data.action:
bpy.data.actions.new(animation.clip_name)
action = shapes.animation_data.action = bpy.data.actions[animation.clip_name]
else:
action = shapes.animation_data.action
offset = start_frame
## clean out old curves
to_clean = []
for curve in action.fcurves:
for name in animation.shapes:
if f'["{name}"]' in curve.data_path:
to_clean.append(curve)
for curve in to_clean:
action.fcurves.remove(curve)
scene_framerate = bpy.context.scene.render.fps
clip_scale = 1.0
clip_to_scene_scale = scene_framerate / animation.frame_rate
if self.apply_scale and self.load_to == "CURRENT" and not (int(animation.frame_rate) == int(scene_framerate)):
clip_scale = clip_to_scene_scale
for data_path, values in animation.curves():
curve = action.fcurves.new(data_path)
curve.keyframe_points.add(len(values))
for index, value in enumerate(values):
curve.keyframe_points[index].co = (float(index) * clip_scale + offset, value)
if self.load_to == "CLIP":
## I'm really not sure if this is the correct idea, but when loading as clip
## we push a new NLA_Track and add the action as a strip, then offset it using
## the strip frame start.
track = nla_tracks.new()
track.name = animation.clip_name + "_NLE"
strip = track.strips.new(animation.clip_name, start_frame, action)
if self.apply_scale:
strip.scale = clip_to_scene_scale
for item in [x for x in nla_tracks if not x == track]:
item.select = False
track.select = True
def load_animation_usda(self, clip_name:str, file_path:str) -> AnimData:
"""
Do a quick parse of the input USDA file in plain text, as we can't use the USD Python API yet.
!TODO: When the USD Python API is available, switch to it instead.
"""
with open(file_path, "r") as fp:
source = fp.read().strip()
## quick sanity checks; not robust!
if not all([
source.startswith("#usda"),
"framesPerSecond = " in source,
"uniform token[] blendShapes = [" in source,
"float[] blendShapeWeights.timeSamples = {" in source,
"token[] custom:mh_curveNames = [" in source,
"float[] custom:mh_curveValues.timeSamples = {" in source]):
self.report({"ERROR"}, f"USDA not a weights animation cache: {file_path}")
return None
end_time = int(source.partition("endTimeCode = ")[-1].partition("\n")[0])
frame_rate = int(source.partition("framesPerSecond = ")[-1].partition("\n")[0])
start_frame = int(source.partition("startTimeCode = ")[-1].partition("\n")[0])
shape_names = source.partition("uniform token[] blendShapes = [")[-1].partition("]")[0]
shape_names = shape_names.replace('"','').replace(' ', '').split(',')
## strip to timeSamples, split lines, then split off the index and parse out the arrays into floats
samples = source.partition("float[] blendShapeWeights.timeSamples = {")[-1].partition("}")[0].strip().split('\n')
weights = [list(map(float, x.partition(": [")[-1].rpartition("]")[0].replace(" ", "").split(","))) for x in samples]
## capture frame rate
frame_rate = float(source.partition("framesPerSecond = ")[-1].partition("\n")[0])
return AnimData(clip_name=clip_name, shapes=shape_names, key_data=weights, frame_rate=frame_rate)
def load_animation_json(self, clip_name:str, file_path:str) -> AnimData:
assert file_path.lower().endswith(".json")
file_path = _abs_path(file_path)
data = None
with open(file_path, "r") as fp:
try:
data = json.load(fp)
except:
return None
if not "facsNames" in data or not "weightMat" in data or not "numFrames" in data:
self.report({"ERROR"}, f"Malformed JSON file (missing data): {file_path}")
return None
if not data["numFrames"] == len(data["weightMat"]):
self.report({"ERROR"}, f"Malformed JSON: malformed file. Expected {data['numFrames']} frames, found {len(data['weightMat'])} -- {file_path}")
return None
return AnimData(clip_name=clip_name, shapes=data["facsNames"], key_data=data["weightMat"],
frame_rate=self.frame_rate)
def load_animation(self, file_path:str, ob:Object) -> bool:
assert ob and isinstance(ob, (bpy.types.Object))
if not file_path.endswith((".usda", ".json")):
self.report({"Error"}, f"Path should point to a USDA or JSON file: {file_path}")
return False
clip_name = os.path.basename(file_path).partition(".")[0]
self.report({"INFO"}, f"Loading anim: {file_path}")
if file_path.endswith(".json"):
data = self.load_animation_json(clip_name, file_path)
else:
data = self.load_animation_usda(clip_name, file_path)
if data is None:
self.report({"ERROR"}, f"Unable to load data from file {file_path}")
return False
self.apply_animation(data, ob)
return True
def execute(self, context:Context) -> Set[str]:
scene = context.scene
ob = context.active_object
if not self.load_animation(scene.audio2face.import_anim_path, ob):
return {"CANCELLED"}
return {"FINISHED"}
## ======================================================================
class OMNI_OT_TransferShapeData(bpy.types.Operator):
"""Transfers shape data from imported rig heads to the original meshes."""
bl_idname = "audio2face.transfer_shape_data"
bl_label = "Transfer Shape Data"
bl_options = {"REGISTER", "UNDO"}
apply_fix: BoolProperty(name="Apply Fix",
description="Propate Basis shape to all parts of the mesh not covered by the head, to prevent vertex vomit.",
default=False)
@classmethod
def poll(cls, context:Context) -> bool:
collection = _get_import_collection()
if collection is None:
return False
meshes = [x.name for x in collection.objects if x.type == "MESH"]
return bool(len(meshes))
def _get_collection_meshes(self, collection:Collection) -> List["bpy.data.Mesh"]:
result = [x for x in collection.all_objects if x.type == "MESH"]
return result
def _build_mapping_table(self, import_meshes:Collection, export_meshes:Collection) -> Dict:
result = {}
for imported in import_meshes:
## Intentionally doing the exported data name but the import object name
## because of how the imports work on both sides.
token = imported.name.rpartition("__Audio2Face_EX")[0]
for exported in export_meshes:
exported_token = exported.data.name.rpartition("__Audio2Face_EX")[0]
if exported_token == token:
result[imported] = exported
return result
def _transfer_shapes(self, context:Context, source:Object, target:Object, mapping_object:Object) -> int:
"""
Transfers shapes from the source mesh to the target.
:returns: The number of shapes transferred.
"""
assert source.data and source.data.shape_keys, "Source object has no shape key data."
wm = context.window_manager
result = 0
## Run these to make sure they're all visible, checked, and in the view layer
a2f_collection, _, _, _ = ensure_scene_collections(context.scene)
_get_or_create_collection(a2f_collection, "A2F Import")
blocks = source.data.shape_keys.key_blocks
total_shapes = len(blocks)
if not context.mode == "OBJECT" and context.active_object:
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.select_all(action="DESELECT")
source.select_set(True)
target.select_set(True)
context.view_layer.objects.active = target
basis = target.data.shape_keys.key_blocks["Basis"]
wm.progress_begin(0, total_shapes)
start_index = len(target.data.shape_keys.key_blocks)
## Grab the mapping array using the new Attributes API.
mapping_indices = np.zeros(len(source.data.vertices), dtype=np.int32)
attr = mapping_object.data.attributes['index_orig']
attr.data.foreach_get("value", mapping_indices)
for index, block in enumerate(blocks):
if block.name == "Basis":
continue
target.shape_key_add(name=block.name, from_mix=False)
target_key_block = target.data.shape_keys.key_blocks[block.name]
target_key_block.relative_key = basis
for index, target_index in enumerate(mapping_indices):
target_key_block.data[target_index].co = block.data[index].co
self.report({"INFO"}, f"Transferred shape {block.name} from {source.name} to {target.name}")
result += 1
wm.progress_update(index)
wm.progress_end()
if self.apply_fix:
self._select_verts_inverse(target, mapping_indices)
bpy.ops.object.mode_set(mode="EDIT")
wm.progress_begin(0, total_shapes)
for index in range(start_index, start_index+total_shapes-1):
shape = target.data.shape_keys.key_blocks[index]
self.report({"INFO"}, f"Fixing shape: {shape.name}")
target.active_shape_key_index = index
bpy.ops.mesh.blend_from_shape(shape='Basis', blend=1.0, add=False)
wm.progress_update(index)
bpy.ops.object.mode_set(mode="OBJECT")
wm.progress_end()
return result
def _select_verts_inverse(self, ob:Object, mapping_indices:Iterable[int]) -> int:
"""
Set the vertex selection of the target object to the inverse of
what's in mapping_indices through the bmesh API.
:returns: The number of vertices selected.
"""
result = 0
bm = bmesh.new()
bm.from_mesh(ob.data)
for v in bm.verts:
should_set = not (v.index in mapping_indices)
v.select_set(should_set)
result += int(should_set)
bm.to_mesh(ob.data)
def _clean_shapes(self, ob:Object, shapes_list:List[str]) -> int:
"""
For each named shape, remove it from ob's shape keys.
:returns: The number of shapes removed
"""
self.report({"INFO"}, f"Cleaning {', '.join(shapes_list)}")
if ob.data.shape_keys is None:
return 0
result = 0
for shape in shapes_list:
key = ob.data.shape_keys.key_blocks.get(shape)
if key:
ob.shape_key_remove(key)
result +=1
return result
def execute(self, context:Context) -> Set[str]:
## Transfer shape data over automatically
scene = context.scene
export_meshes = self._get_collection_meshes(_get_export_collection())
import_meshes = self._get_collection_meshes(_get_import_collection())
total = 0
mapping_table = self._build_mapping_table(import_meshes, export_meshes).items()
self.report({"INFO"}, f"{mapping_table}")
for source, mapping_object in mapping_table:
## hop to the true original mesh
target = mapping_object.a2f_original
source_shapes = [x.name for x in source.data.shape_keys.key_blocks if not x.name == "Basis"]
count = self._clean_shapes(target, source_shapes)
self.report({"INFO"}, f"Cleaned {count} shape{'' if count == 1 else 's'} from {target.name}")
## regrab the target object now that it's been modified and we're
## holding onto an old pointer
target = mapping_object.a2f_original
## bugfix: add a Basis target if none exists
if target.data.shape_keys is None or not "Basis" in target.data.shape_keys.key_blocks:
target.shape_key_add(name="Basis", from_mix=False)
result = self._transfer_shapes(context, source, target, mapping_object)
self.report({"INFO"}, f"Transferred {result} shape{'' if result == 1 else 's'} from {source.name} to {target.name}")
total += result
self.report({"INFO"}, f"Transferred {total} total shape{'' if total == 1 else 's'}")
return {"FINISHED"}
| 31,692 | Python | 35.220571 | 151 | 0.669033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.