def testBatching(self):
        self._StartRecording()
        with mayaUsdLib.DiagnosticBatchContext():
            Tf.Warn("spooky warning")
            Tf.Status("informative status")

            for i in range(5):
                Tf.Status("repeated status %d" % i)

            for i in range(3):
                Tf.Warn("spam warning %d" % i)

            try:
                Tf.RaiseCodingError("coding error!")
            except:
                pass
        log = self._StopRecording()

        # Note: we use assertItemsEqual because coalescing may re-order the
        # diagnostic messages.
        self.assertItemsEqual(log, [
            ("spooky warning", OM.MCommandMessage.kWarning),
            ("informative status", OM.MCommandMessage.kInfo),
            ("repeated status 0 -- and 4 similar", OM.MCommandMessage.kInfo),
            ("spam warning 0 -- and 2 similar", OM.MCommandMessage.kWarning)
        ])
示例#2
0
 def testStatus(self):
     """Statuses should become Maya statuses."""
     self._StartRecording()
     Tf.Status("test status 1")
     Tf.Status("another test status")
     Tf.Status("yay for statuses!")
     log = self._StopRecording()
     self.assertListEqual(
         log, [("test status 1", OM.MCommandMessage.kInfo),
               ("another test status", OM.MCommandMessage.kInfo),
               ("yay for statuses!", OM.MCommandMessage.kInfo)])
    def _RunPlaybackTest(self):
        numFrames = self.animEndTime - self.animStartTime + 1.0

        profileScopeName = '%s Proxy Orbit Playback Time' % self._testName

        with self._ProfileScope(profileScopeName):
            for frame in xrange(int(self.animStartTime), int(self.animEndTime + 1.0)):
                cmds.currentTime(frame, edit=True)

        playElapsedTime = self._profileScopeMetrics[profileScopeName]

        Tf.Status("Number of frames: %f" % numFrames)
        Tf.Status("Playback Elapsed Time: %f" % playElapsedTime)
        Tf.Status("Playback FPS: %f" % (numFrames / playElapsedTime))
    def test_Notices(self):
        self.log.info("Issuing a couple of different types of errors.")

        try:
            Tf.RaiseRuntimeError("Runtime error!")
            assert False, "expected exception"
        except Tf.ErrorException:
            pass

        try:
            Tf.RaiseCodingError("Coding error!")
            assert False, "expected exception"
        except Tf.ErrorException:
            pass

        self.log.info("Issuing a few generic warnings.")
        Tf.Warn("Warning 1")
        Tf.Warn("Warning 2")
        Tf.Warn("Warning 3")

        self.log.info("Issuing a status message.")
        Tf.Status("Status: Almost done testing.")

        # Assert that two errors, three warnings and one status message were
        # issued.
        self.assertNotIn('IssuedError', self.notices)
        self.assertEqual(self.notices['IssuedWarning'], 3)
        self.assertEqual(self.notices['IssuedStatus'], 1)

        self.outputFile.close()
    def _ProfileScope(self, profileScopeName):
        """
        A context manager that measures the execution time between enter and
        exit and stores the elapsed time in the class' metrics dictionary.
        """
        stopwatch = Tf.Stopwatch()
        collector = Trace.Collector()

        try:
            stopwatch.Start()
            collector.enabled = True
            collector.BeginEvent(profileScopeName)
            yield
        finally:
            collector.EndEvent(profileScopeName)
            collector.enabled = False
            stopwatch.Stop()
            elapsedTime = stopwatch.seconds
            self._profileScopeMetrics[profileScopeName] = elapsedTime
            Tf.Status('%s: %f' % (profileScopeName, elapsedTime))

            traceFilePath = os.path.join(self._testDir,
                '%s.trace' % profileScopeName)
            Trace.Reporter.globalReporter.Report(traceFilePath)
            collector.Clear()
            Trace.Reporter.globalReporter.ClearTree()
    def testDrawAndTransformCube(self):
        """
        Tests drawing a USD proxy shape node before and after applying a
        transform to it.

        This ensures that changes in the proxy shape's transform node are
        propagated to Hydra correctly when using Viewport 2.0.
        """
        self._testName = 'ProxyShapeDrawAndTransformTest'

        mayaSceneFile = '%s.ma' % self._testName
        mayaSceneFullPath = os.path.abspath(mayaSceneFile)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        Tf.Status("Maya Scene File: %s" % mayaSceneFile)

        self._LoadAssemblies()

        self._WriteViewportImage(self._testName, 'initial')

        cmds.setAttr('Cube_1.tz', 5.0)

        self._WriteViewportImage(self._testName, 'tz_5')

        cmds.setAttr('Cube_1.tz', 10)

        self._WriteViewportImage(self._testName, 'tz_10')
示例#7
0
    def test_StaticMethodPosting(self):
        with self.assertRaises(Tf.ErrorException):
            Tf._TestStaticMethodError.Error()

        Tf.Warn("expected warning, for coverage")

        Tf.Status("expected status message, for coverage")
示例#8
0
    def testSceneImportAndReference(self):
        """
        Tests that importing or referencing a Maya scene does not reset the
        batch renderer.

        The batch renderer listens for kBeforeFileRead scene messages, but
        those are also emitted when a scene is imported or referenced into the
        current scene. In that case, we want to make sure that the batch
        renderer does not get reset.
        """
        mayaSceneFile = '%s.ma' % self._testName
        mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile)
        Tf.Status('Opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)
        currentTime = cmds.playbackOptions(query=True, animationStartTime=True)

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)

        # Import another scene file into the current scene.
        mayaSceneFile = 'EmptyScene.ma'
        mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile)
        Tf.Status('Importing Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, i=True)

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)

        # Try to select the proxy shape.
        cmds.select('CubeProxyShape')

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)

        # Reference another scene file into the current scene.
        Tf.Status('Referencing Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, reference=True)

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)

        # Try to select the proxy shape.
        cmds.select('CubeProxyShape')
    def _LoadAssemblies(self):
        loadStartTime = cmds.timerX()

        UsdMaya.LoadReferenceAssemblies()

        loadElapsedTime = cmds.timerX(startTime=loadStartTime)

        Tf.Status("Load Elapsed Time: %f" % loadElapsedTime)
示例#10
0
    def _GetViewWidgetCenter(self, viewWidget):
        width = viewWidget.width()
        height = viewWidget.height()
        viewSize = Gf.Vec2f(width, height)
        Tf.Status("Maya Viewport Widget Dimensions: %s" % viewSize)

        viewCenter = viewSize / 2.0

        return viewCenter
    def _RunPerfTest(self):
        mayaSceneFile = 'Grid_5_of_CubeGrid%s_10.ma' % self._testName
        mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        Tf.Status("Maya Scene File: %s" % mayaSceneFile)

        # Get the QWidget for the viewport window.
        self.assertTrue(self._IsViewportRendererViewport20())
        self._viewWidget = self._GetViewportWidget(self._cameraName,
            'vp2Renderer')
        self.assertTrue(self._viewWidget)

        # Force the initial view to draw so that the viewport size stabilizes.
        animStartTime = cmds.playbackOptions(query=True,
            animationStartTime=True)
        cmds.currentTime(animStartTime, edit=True)
        QApplication.processEvents()

        # Render an image and validate that nothing is selected to start.
        self._WriteViewportImage(self._testName, 'before_selection')
        expectedSelection = set()
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)


        self._TestSelectCenterSingle()
        expectedSelection = set(['AssetRef_2_0_2'])
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)


        self._TestSelectCenterArea()
        expectedSelection = set([
            'AssetRef_2_0_2',
            'AssetRef_2_1_2',
            'AssetRef_2_2_2',
            'AssetRef_2_3_2',
            'AssetRef_2_4_2'])
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)


        self._TestUnselect()
        expectedSelection = set()
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)


        self._TestSelectionAppend()
        expectedSelection = set([
            'AssetRef_0_0_4',
            'AssetRef_4_0_4',
            'AssetRef_4_0_0',
            'AssetRef_0_0_0'])
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)
示例#12
0
    def testSceneOpenAndReopen(self):
        """
        Tests opening and then re-opening scenes after having drawn a USD proxy
        shape.

        The batch renderer needs to be reset when opening a new scene, but
        kBeforeOpen and kAfterOpen scene messages are not always delivered at
        the right time. With the former, the current scene may still be active
        when the message is received in which case another draw may occur
        before the scene is finally closed. With the latter, the scene may have
        been fully read and an initial draw may have happened by the time the
        message is received. Either case results in the batch renderer being
        reset in the middle of an active scene and a possible crash.

        This test depends on the proxy shape node directly and not the assembly
        node. The proxy shape will be drawn immediately when the scene is
        opened, as opposed to an assembly that must first be loaded to create
        the proxy shape node underneath it.
        """
        mayaSceneFile = 'ProxyShapeBatchRendererResetTest.ma'
        mayaSceneFullPath = os.path.abspath(mayaSceneFile)
        Tf.Status('Opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        # Force a draw to complete by switching frames.
        animStartTime = cmds.playbackOptions(query=True,
                                             animationStartTime=True)
        cmds.currentTime(animStartTime + 1.0, edit=True)

        # Re-open the same scene.
        Tf.Status('Re-opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        # Force a draw to complete by switching frames.
        animStartTime = cmds.playbackOptions(query=True,
                                             animationStartTime=True)
        cmds.currentTime(animStartTime + 1.0, edit=True)

        # Try to select the proxy shape.
        cmds.select('CubeProxy')

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)
示例#13
0
    def testSaveSceneAs(self):
        """
        Tests performing a "Save Scene As..." after having drawn a USD proxy
        shape.

        Previously, the batch renderer listened for kSceneUpdate Maya scene
        messages so that it could reset itself when the scene was changed. This
        was intended to fire for new empty scenes or when opening a different
        scene file. It turns out Maya also emits that message during
        "Save Scene As..." operations, in which case we do *not* want to reset
        the batch renderer, as doing so would lead to a crash, since all of the
        proxy shapes are still in the DAG.

        This test ensures that the batch renderer does not reset and Maya does
        not crash when doing a "Save Scene As..." operation.
        """
        mayaSceneFile = 'AssemblySaveAsTest.ma'
        mayaSceneFullPath = os.path.abspath(mayaSceneFile)
        Tf.Status('Opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        animStartTime = cmds.playbackOptions(query=True,
                                             animationStartTime=True)

        UsdMaya.LoadReferenceAssemblies()

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)

        saveAsMayaSceneFile = 'SavedScene.ma'
        saveAsMayaSceneFullPath = os.path.abspath(saveAsMayaSceneFile)
        Tf.Status('Saving Maya Scene File As: %s' % saveAsMayaSceneFullPath)
        cmds.file(rename=saveAsMayaSceneFullPath)
        cmds.file(save=True)

        # Try to select the USD assembly/proxy. This will cause the proxy's
        # shape adapter's Sync() method to be called, which would fail if the
        # batch renderer had been reset out from under the shape adapter.
        cmds.select('CubeAssembly')

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)
    def testBatching_DelegateRemoved(self):
        """Tests removing the diagnostic delegate when the batch context is
        still open."""
        self._StartRecording()
        with mayaUsdLib.DiagnosticBatchContext():
            Tf.Warn("this warning won't be lost")
            Tf.Status("this status won't be lost")

            cmds.unloadPlugin('pxrUsd', force=True)

            for i in range(5):
                Tf.Status("no delegate, this will be lost %d" % i)
        log = self._StopRecording()

        # Note: we use assertItemsEqual because coalescing may re-order the
        # diagnostic messages.
        self.assertItemsEqual(log, [
            ("this warning won't be lost", OM.MCommandMessage.kWarning),
            ("this status won't be lost", OM.MCommandMessage.kInfo),
        ])
示例#15
0
    def testSceneOpenAndReopen(self):
        """
        Tests opening and then re-opening scenes after having drawn a USD proxy
        shape.

        The batch renderer needs to be reset when opening a new scene, but
        kBeforeOpen and kAfterOpen scene messages are not always delivered at
        the right time. With the former, the current scene may still be active
        when the message is received in which case another draw may occur
        before the scene is finally closed. With the latter, the scene may have
        been fully read and an initial draw may have happened by the time the
        message is received. Either case results in the batch renderer being
        reset in the middle of an active scene and a possible crash.
        """
        mayaSceneFile = '%s.ma' % self._testName
        mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile)
        Tf.Status('Opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)
        currentTime = cmds.playbackOptions(query=True, animationStartTime=True)

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)

        # Re-open the same scene.
        Tf.Status('Re-opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)
        currentTime = cmds.playbackOptions(query=True, animationStartTime=True)

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)

        # Try to select the proxy shape.
        cmds.select('CubeProxyShape')

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)
示例#16
0
    def _ProfileScope(self, profileScopeName):
        """
        A context manager that measures the execution time between enter and
        exit and stores the elapsed time in the class' metrics dictionary.
        """
        stopwatch = Tf.Stopwatch()

        try:
            stopwatch.Start()
            yield
        finally:
            stopwatch.Stop()
            elapsedTime = stopwatch.seconds
            self._profileScopeMetrics[profileScopeName] = elapsedTime
            Tf.Status("%s: %f" % (profileScopeName, elapsedTime))
示例#17
0
    def _RunPerfTest(self):
        mayaSceneFile = 'Grid_5_of_CubeGrid%s_10.ma' % self._testName
        mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        Tf.Status("Maya Scene File: %s" % mayaSceneFile)

        self.animStartTime = cmds.playbackOptions(query=True,
                                                  animationStartTime=True)
        self.animEndTime = cmds.playbackOptions(query=True,
                                                animationEndTime=True)

        self._RunTimeToFirstDrawTest()

        self._RunPlaybackTest()

        cmds.currentTime(self.animStartTime, edit=True)
        self._WriteViewportImage(self._testName)
    def testPerfGridOfCubeModelDuplicate(self):
        """
        Tests speed of duplicating a USD proxy shape when many such nodes are
        present.

        The geometry in this scene is a grid of grids. The top-level grid is
        made up of USD proxy shape nodes. Each of those proxy shape nodes
        references a USD file with many references to a "CubeModel" asset USD
        file.
        """
        self._testName = 'ModelRefs'
        mayaSceneFile = 'Grid_5_of_CubeGrid%s_10.ma' % self._testName
        mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        Tf.Status("Maya Scene File: %s" % mayaSceneFile)

        self._WriteViewportImage(self._testName, 'initial')

        self._RunDuplicateTest()
示例#19
0
def testCase16():
    print("Case16: test Status NEVER aborts")
    delegate = delegateSetup(None, ["*test*"], ["*not*"], None)
    Tf.Status("Does not abort, even though word not excluded")