예제 #1
0
    def testCopyFrom(self):

        c = GafferImage.Catalogue()
        c["images"].addChild(
            c.Image.load(
                "${GAFFER_ROOT}/python/GafferImageTest/images/checker.exr"))
        c["images"][0]["description"].setValue("test")

        c["images"].addChild(
            c.Image(flags=Gaffer.Plug.Flags.Default
                    | Gaffer.Plug.Flags.Dynamic))
        c["images"][1].copyFrom(c["images"][0])

        self.assertEqual(c["images"][1]["description"].getValue(),
                         c["images"][0]["description"].getValue())
        self.assertEqual(c["images"][1]["fileName"].getValue(),
                         c["images"][0]["fileName"].getValue())
예제 #2
0
    def testDontSerialiseUnsavedRenders(self):

        s = Gaffer.ScriptNode()
        s["c"] = GafferImage.Catalogue()

        constant = GafferImage.Constant()
        constant["format"].setValue(GafferImage.Format(100, 100))
        self.sendImage(
            constant["out"],
            s["c"],
        )

        self.assertEqual(len(s["c"]["images"]), 1)

        s2 = Gaffer.ScriptNode()
        s2.execute(s.serialise())

        self.assertEqual(len(s2["c"]["images"]), 0)
예제 #3
0
	def testDontSerialiseUnsavedRenders( self ) :

		s = Gaffer.ScriptNode()
		s["c"] = GafferImage.Catalogue()

		constant = GafferImage.Constant()
		constant["format"].setValue( GafferImage.Format( 100, 100 ) )
		GafferImageTest.DisplayTest.sendImage(
			constant["out"],
			GafferImage.Catalogue.displayDriverServer().portNumber(),
		)

		self.assertEqual( len( s["c"]["images"] ), 1 )

		s2 = Gaffer.ScriptNode()
		s2.execute( s.serialise() )

		self.assertEqual( len( s2["c"]["images"] ), 0 )
예제 #4
0
	def testDontSavePromotedUnsavedRenders( self ) :

		s = Gaffer.ScriptNode()
		s["b"] = Gaffer.Box()
		s["b"]["c"] = GafferImage.Catalogue()
		promotedImages = Gaffer.PlugAlgo.promote( s["b"]["c"]["images"] )
		promotedImageIndex = Gaffer.PlugAlgo.promote( s["b"]["c"]["imageIndex"] )
		promotedOut = Gaffer.PlugAlgo.promote( s["b"]["c"]["out"] )

		r = GafferImage.ImageReader()
		r["fileName"].setValue( "${GAFFER_ROOT}/python/GafferImageTest/images/checker.exr" )
		self.sendImage( r["out"], s["b"]["c"] )

		self.assertEqual( len( promotedImages ), 1 )

		s2 = Gaffer.ScriptNode()
		s2.execute( s.serialise() )

		self.assertEqual( len( s2["b"]["images"] ), 0 )
예제 #5
0
	def testImageName( self ) :

		catalogue = GafferImage.Catalogue()
		self.assertEqual( len( catalogue["images"] ), 0 )

		constant = GafferImage.Constant()
		constant["format"].setValue( GafferImage.Format( 64, 64 ) )
		self.sendImage(
			constant["out"],
			catalogue,
			{
				"catalogue:imageName" : "testName",
			}
		)

		self.assertEqual( len( catalogue["images"] ), 1 )
		self.assertEqual( catalogue["images"][0].getName(), "testName" )

		self.sendImage(
			constant["out"],
			catalogue,
			{
				"catalogue:imageName" : "!invalid&^ Name[]",
			}
		)

		self.assertEqual( len( catalogue["images"] ), 2 )
		self.assertEqual( catalogue["images"][0].getName(), "testName" )
		self.assertEqual( catalogue["images"][1].getName(), "_invalid_Name_" )

		self.sendImage(
			constant["out"],
			catalogue,
			{
				"catalogue:imageName" : "5IsntAValidStartingCharacter",
			}
		)

		self.assertEqual( len( catalogue["images"] ), 3 )
		self.assertEqual( catalogue["images"][0].getName(), "testName" )
		self.assertEqual( catalogue["images"][1].getName(), "_invalid_Name_" )
		self.assertEqual( catalogue["images"][2].getName(), "_IsntAValidStartingCharacter" )
예제 #6
0
    def testDeleteBeforeSaveCompletesWithScriptVariables(self):

        s = Gaffer.ScriptNode()
        s["fileName"].setValue(
            "testDeleteBeforeSaveCompletesWithScriptVariables")
        self.assertEqual(s.context().substitute("${script:name}"),
                         "testDeleteBeforeSaveCompletesWithScriptVariables")

        baseDirectory = os.path.join(self.temporaryDirectory(), "catalogue")
        # we don't expect to need to write here, but to ensure
        # we didn't even try to do so we make it read only.
        os.mkdir(baseDirectory)
        os.chmod(baseDirectory, stat.S_IREAD)
        directory = os.path.join(baseDirectory, "${script:name}", "images")

        s["c"] = GafferImage.Catalogue()
        s["c"]["directory"].setValue(directory)

        fullDirectory = s.context().substitute(s["c"]["directory"].getValue())
        self.assertNotEqual(directory, fullDirectory)
        self.assertFalse(os.path.exists(directory))
        self.assertFalse(os.path.exists(fullDirectory))

        r = GafferImage.ImageReader()
        r["fileName"].setValue(
            "${GAFFER_ROOT}/python/GafferImageTest/images/checker.exr")

        driver = self.sendImage(r["out"],
                                s["c"],
                                waitForSave=False,
                                close=False)
        # Simulate deletion by removing it from the script but keeping it alive.
        # This would typically be fine, but we've setup the directory to require
        # a script and then removed the script prior to closing the driver. Note
        # we can't actually delete the catalogue yet or `driver.close()` would
        # hang indefinitely waiting for an imageReceivedSignal.
        c = s["c"]
        s.removeChild(s["c"])
        driver.close()

        self.assertFalse(os.path.exists(directory))
        self.assertFalse(os.path.exists(fullDirectory))
예제 #7
0
	def testDisplayDriverSaveToFile( self ) :

		s = Gaffer.ScriptNode()
		s["c"] = GafferImage.Catalogue()
		s["c"]["directory"].setValue( os.path.join( self.temporaryDirectory(), "catalogue" ) )

		r = GafferImage.ImageReader()
		r["fileName"].setValue( "${GAFFER_ROOT}/python/GafferImageTest/images/blurRange.exr" )
		self.sendImage( r["out"], s["c"] )

		self.assertEqual( len( s["c"]["images"] ), 1 )
		self.assertEqual( os.path.dirname( s["c"]["images"][0]["fileName"].getValue() ), s["c"]["directory"].getValue() )
		self.assertImagesEqual( s["c"]["out"], r["out"], ignoreMetadata = True, maxDifference = 0.0003 )

		s2 = Gaffer.ScriptNode()
		s2.execute( s.serialise() )

		self.assertEqual( len( s2["c"]["images"] ), 1 )
		self.assertEqual( s2["c"]["images"][0]["fileName"].getValue(), s["c"]["images"][0]["fileName"].getValue() )
		self.assertImagesEqual( s2["c"]["out"], r["out"], ignoreMetadata = True, maxDifference = 0.0003 )
예제 #8
0
	def testDescriptionLoading( self ) :

		c = GafferImage.Constant()

		m = GafferImage.ImageMetadata()
		m["in"].setInput( c["out"] )
		m["metadata"].addChild( Gaffer.NameValuePlug( "ImageDescription", "i am a description" ) )

		w = GafferImage.ImageWriter()
		w["in"].setInput( m["out"] )
		w["fileName"].setValue( os.path.join( self.temporaryDirectory(), "description.exr" ) )
		w["task"].execute()

		r = GafferImage.ImageReader()
		r["fileName"].setValue( w["fileName"].getValue() )

		c = GafferImage.Catalogue()
		c["images"].addChild( GafferImage.Catalogue.Image.load( w["fileName"].getValue() ) )
		self.assertEqual( c["images"][0]["description"].getValue(), "" )
		self.assertEqual( c["out"]["metadata"].getValue()["ImageDescription"].value, "i am a description" )
예제 #9
0
    def testInvalidColumns(self):

        # Check we don't abort - columns may have been removed
        # from config but still be referenced by plug metadata.

        s = Gaffer.ScriptNode()
        s["c"] = GafferImage.Catalogue()

        Gaffer.Metadata.registerValue(
            s["c"]["imageIndex"], "catalogue:columns",
            IECore.StringVectorData(["Name", "Unknown"]))

        sw = GafferUI.ScriptWindow.acquire(s)

        with IECore.CapturingMessageHandler() as mh:
            ne = GafferUI.NodeEditor.acquire(s["c"])

        self.assertEqual(len(mh.messages), 1)
        self.assertEqual(mh.messages[0].level, IECore.Msg.Level.Error)
        self.assertTrue("Unknown" in mh.messages[0].message)
예제 #10
0
    def testPromotion(self):

        s = Gaffer.ScriptNode()
        s["b"] = Gaffer.Box()
        s["b"]["c"] = GafferImage.Catalogue()
        promotedImages = Gaffer.PlugAlgo.promote(s["b"]["c"]["images"])
        promotedImageIndex = Gaffer.PlugAlgo.promote(s["b"]["c"]["imageIndex"])
        promotedOut = Gaffer.PlugAlgo.promote(s["b"]["c"]["out"])

        images = []
        readers = []
        for i, fileName in enumerate(
            ["checker.exr", "blurRange.exr", "noisyRamp.exr"]):
            images.append(
                GafferImage.Catalogue.Image.load(
                    "${GAFFER_ROOT}/python/GafferImageTest/images/" +
                    fileName))
            readers.append(GafferImage.ImageReader())
            readers[-1]["fileName"].setValue(images[-1]["fileName"].getValue())

        for image in images:
            promotedImages.addChild(image)
            self.assertImagesEqual(readers[0]["out"], promotedOut)

        for i, reader in enumerate(readers):
            promotedImageIndex.setValue(i)
            self.assertImagesEqual(readers[i]["out"], promotedOut)

        s2 = Gaffer.ScriptNode()
        s2.execute(s.serialise())

        for i, reader in enumerate(readers):
            s2["b"]["imageIndex"].setValue(i)
            self.assertImagesEqual(readers[i]["out"], s2["b"]["out"])

        s3 = Gaffer.ScriptNode()
        s3.execute(s.serialise())

        for i, reader in enumerate(readers):
            s3["b"]["imageIndex"].setValue(i)
            self.assertImagesEqual(readers[i]["out"], s3["b"]["out"])
예제 #11
0
    def testUndoRedo(self):

        s = Gaffer.ScriptNode()
        s["c"] = GafferImage.Catalogue()
        s["c"]["images"].addChild(s["c"].Image.load(
            "${GAFFER_ROOT}/python/GafferImageTest/images/checker.exr"))

        r = GafferImage.ImageReader()
        r["fileName"].setValue(
            "${GAFFER_ROOT}/python/GafferImageTest/images/blurRange.exr")

        def assertPreconditions():

            self.assertEqual(len(s["c"]["images"]), 1)
            self.assertEqual(s["c"]["imageIndex"].getValue(), 0)

        assertPreconditions()

        with Gaffer.UndoScope(s):
            s["c"]["images"].addChild(s["c"].Image.load(
                r["fileName"].getValue()))
            s["c"]["imageIndex"].setValue(1)

        def assertPostConditions():

            self.assertEqual(len(s["c"]["images"]), 2)
            self.assertEqual(s["c"]["imageIndex"].getValue(), 1)
            self.assertImagesEqual(s["c"]["out"],
                                   r["out"],
                                   ignoreMetadata=True)

        assertPostConditions()

        s.undo()
        assertPreconditions()

        s.redo()
        assertPostConditions()

        s.undo()
        assertPreconditions()
예제 #12
0
	def testSelection( self ):

		# Set up Catalogue with images that we can select

		images = []
		readers = []
		fileNames = [ "checker.exr", "blurRange.exr", "noisyRamp.exr", "resamplePatterns.exr" ]
		for fileName in fileNames :
			images.append( GafferImage.Catalogue.Image.load( "${GAFFER_ROOT}/python/GafferImageTest/images/" + fileName ) )
			readers.append( GafferImage.ImageReader() )
			readers[-1]["fileName"].setValue( images[-1]["fileName"].getValue() )

		c = GafferImage.Catalogue()

		for image in images :
			c["images"].addChild( image )

		# Pulling out images by name

		for i, fileName in enumerate( fileNames ) :
			catalogueSelect = GafferImage.CatalogueSelect()
			catalogueSelect["in"].setInput( c["out"] )
			catalogueSelect["imageName"].setValue( fileName.split( "." )[0] )

			self.assertImagesEqual( catalogueSelect["out"], readers[i]["out"], ignoreMetadata = True )

		# Pulling out image that is selected in the Catalogue UI

		catalogueSelect = GafferImage.CatalogueSelect()
		catalogueSelect["in"].setInput( c["out"] )
		catalogueSelect["imageName"].setValue( "" )

		self.assertImagesEqual( catalogueSelect["out"], c["out"] )

		# Pulling out invalid image

		catalogueSelect["imageName"].setValue("nope")
		with self.assertRaises( Exception ) as cm:
			GafferImage.ImageAlgo.image( catalogueSelect["out"] )

		self.assertEqual( str( cm.exception ), 'Catalogue.__imageIndex : Unknown image name "nope".' )
예제 #13
0
	def testDisplayDriver( self ) :

		c = GafferImage.Catalogue()
		self.assertEqual( len( c["images"] ), 0 )

		r = GafferImage.ImageReader()
		r["fileName"].setValue( "${GAFFER_ROOT}/python/GafferImageTest/images/checker.exr" )
		GafferImageTest.DisplayTest.sendImage( r["out"], c.displayDriverServer().portNumber() )

		self.assertEqual( len( c["images"] ), 1 )
		self.assertEqual( c["images"][0]["fileName"].getValue(), "" )
		self.assertEqual( c["imageIndex"].getValue(), 0 )
		self.assertImagesEqual( r["out"], c["out"], ignoreMetadata = True )

		r["fileName"].setValue( "${GAFFER_ROOT}/python/GafferImageTest/images/blurRange.exr" )
		GafferImageTest.DisplayTest.sendImage( r["out"], c.displayDriverServer().portNumber() )

		self.assertEqual( len( c["images"] ), 2 )
		self.assertEqual( c["images"][1]["fileName"].getValue(), "" )
		self.assertEqual( c["imageIndex"].getValue(), 1 )
		self.assertImagesEqual( r["out"], c["out"], ignoreMetadata = True )
예제 #14
0
    def testDisplayDriverAOVGrouping(self):

        c = GafferImage.Catalogue()
        self.assertEqual(len(c["images"]), 0)

        aov1 = GafferImage.Constant()
        aov1["format"].setValue(GafferImage.Format(100, 100))
        aov1["color"].setValue(imath.Color4f(1, 0, 0, 1))

        aov2 = GafferImage.Constant()
        aov2["format"].setValue(GafferImage.Format(100, 100))
        aov2["color"].setValue(imath.Color4f(0, 1, 0, 1))
        aov2["layer"].setValue("diffuse")

        self.sendImage(aov1["out"], c)
        self.sendImage(aov2["out"], c)

        self.assertEqual(len(c["images"]), 1)
        self.assertEqual(
            set(c["out"]["channelNames"].getValue()),
            set(aov1["out"]["channelNames"].getValue())
            | set(aov2["out"]["channelNames"].getValue()))
예제 #15
0
	def testDisplayDriverAndPromotion( self ) :

		s = Gaffer.ScriptNode()
		s["b"] = Gaffer.Box()
		s["b"]["c"] = GafferImage.Catalogue()
		s["b"]["c"]["directory"].setValue( os.path.join( self.temporaryDirectory(), "catalogue" ) )
		promotedImages = Gaffer.PlugAlgo.promote( s["b"]["c"]["images"] )
		promotedImageIndex = Gaffer.PlugAlgo.promote( s["b"]["c"]["imageIndex"] )
		promotedOut = Gaffer.PlugAlgo.promote( s["b"]["c"]["out"] )

		r = GafferImage.ImageReader()
		r["fileName"].setValue( "${GAFFER_ROOT}/python/GafferImageTest/images/checker.exr" )
		self.sendImage( r["out"], s["b"]["c"] )

		self.assertEqual( len( promotedImages ), 1 )
		self.assertEqual( promotedImageIndex.getValue(), 0 )
		self.assertImagesEqual( r["out"], promotedOut, ignoreMetadata = True )

		r["fileName"].setValue( "${GAFFER_ROOT}/python/GafferImageTest/images/blurRange.exr" )
		self.sendImage( r["out"], s["b"]["c"] )

		self.assertEqual( len( promotedImages ), 2 )
		self.assertEqual( promotedImageIndex.getValue(), 1 )
		self.assertImagesEqual( r["out"], promotedOut, ignoreMetadata = True )

		s2 = Gaffer.ScriptNode()
		s2.execute( s.serialise() )

		self.assertEqual( len( s2["b"]["images"] ), 2 )
		self.assertEqual( s2["b"]["imageIndex"].getValue(), 1 )
		self.assertImagesEqual( promotedOut, s2["b"]["c"]["out"], ignoreMetadata = True, maxDifference = 0.0003 )

		s3 = Gaffer.ScriptNode()
		s3.execute( s2.serialise() )

		self.assertEqual( len( s3["b"]["images"] ), 2 )
		self.assertEqual( s3["b"]["imageIndex"].getValue(), 1 )
		self.assertImagesEqual( promotedOut, s3["b"]["c"]["out"], ignoreMetadata = True, maxDifference = 0.0003 )
예제 #16
0
    def testImages(self):

        images = []
        readers = []
        for i, fileName in enumerate([
                "checker.exr", "blurRange.exr", "noisyRamp.exr",
                "resamplePatterns.exr"
        ]):
            images.append(
                GafferImage.Catalogue.Image.load(
                    "${GAFFER_ROOT}/python/GafferImageTest/images/" +
                    fileName))
            readers.append(GafferImage.ImageReader())
            readers[-1]["fileName"].setValue(images[-1]["fileName"].getValue())

        c = GafferImage.Catalogue()

        for image in images:
            c["images"].addChild(image)
            self.assertImagesEqual(readers[0]["out"],
                                   c["out"],
                                   ignoreMetadata=True)

        def assertExpectedImages():

            for i, reader in enumerate(readers):
                c["imageIndex"].setValue(i)
                self.assertImagesEqual(readers[i]["out"],
                                       c["out"],
                                       ignoreMetadata=True)

        assertExpectedImages()

        for i in [1, 0, 1, 0]:
            c["images"].removeChild(c["images"][i])
            del readers[i]
            assertExpectedImages()
    def testQuadLightTextureEdits(self):

        # Quad light texture edits don't currently update correctly in Arnold.
        # Check that our workaround is working

        s = Gaffer.ScriptNode()
        s["catalogue"] = GafferImage.Catalogue()

        s["s"] = GafferScene.Sphere()

        s["PathFilter"] = GafferScene.PathFilter("PathFilter")
        s["PathFilter"]["paths"].setValue(IECore.StringVectorData(['/sphere']))

        s["ShaderAssignment"] = GafferScene.ShaderAssignment(
            "ShaderAssignment")
        s["ShaderAssignment"]["in"].setInput(s["s"]["out"])
        s["ShaderAssignment"]["filter"].setInput(s["PathFilter"]["out"])

        s["lambert"], _ = self._createMatteShader()
        s["ShaderAssignment"]["shader"].setInput(s["lambert"]["out"])

        s["Tex"] = GafferArnold.ArnoldShader("image")
        s["Tex"].loadShader("image")
        s["Tex"]["parameters"]["filename"].setValue(
            "${GAFFER_ROOT}/python/GafferArnoldTest/images/sphereLightBake.exr"
        )
        s["Tex"]["parameters"]["multiply"].setValue(imath.Color3f(1, 0, 0))

        s["Light"] = GafferArnold.ArnoldLight("quad_light")
        s["Light"].loadShader("quad_light")
        s["Light"]["transform"]["translate"]["z"].setValue(2)
        s["Light"]["parameters"]["color"].setInput(s["Tex"]["out"])
        s["Light"]["parameters"]["exposure"].setValue(4)

        s["c"] = GafferScene.Camera()
        s["c"]["transform"]["translate"]["z"].setValue(2)

        s["group"] = GafferScene.Group()
        s["group"]["in"][0].setInput(s["ShaderAssignment"]["out"])
        s["group"]["in"][1].setInput(s["Light"]["out"])
        s["group"]["in"][2].setInput(s["c"]["out"])

        s["o"] = GafferScene.Outputs()
        s["o"].addOutput(
            "beauty",
            IECoreScene.Output(
                "test", "ieDisplay", "rgba", {
                    "driverType":
                    "ClientDisplayDriver",
                    "displayHost":
                    "localhost",
                    "displayPort":
                    str(s['catalogue'].displayDriverServer().portNumber()),
                    "remoteDisplayType":
                    "GafferImage::GafferDisplayDriver",
                }))
        s["o"]["in"].setInput(s["group"]["out"])

        s["so"] = GafferScene.StandardOptions()
        s["so"]["options"]["renderCamera"]["value"].setValue("/group/camera")
        s["so"]["options"]["renderCamera"]["enabled"].setValue(True)
        s["so"]["in"].setInput(s["o"]["out"])

        s["r"] = self._createInteractiveRender()
        s["r"]["in"].setInput(s["so"]["out"])

        # Start rendering and make sure the light is linked to the sphere

        s["r"]["state"].setValue(s["r"].State.Running)

        self.uiThreadCallHandler.waitFor(1.0)

        initialColor = self._color4fAtUV(s["catalogue"], imath.V2f(0.5))
        self.assertAlmostEqual(initialColor.r, 0.09, delta=0.013)
        self.assertAlmostEqual(initialColor.g, 0, delta=0.01)

        # Edit texture network and make sure the changes take effect

        s["Tex"]["parameters"]["multiply"].setValue(imath.Color3f(0, 1, 0))

        self.uiThreadCallHandler.waitFor(1.0)

        updateColor = self._color4fAtUV(s["catalogue"], imath.V2f(0.5))
        self.assertAlmostEqual(updateColor.r, 0, delta=0.01)
        self.assertAlmostEqual(updateColor.g, 0.06, delta=0.022)

        s["r"]["state"].setValue(s["r"].State.Stopped)
    def testLightLinkingAfterParameterUpdates(self):

        s = Gaffer.ScriptNode()
        s["catalogue"] = GafferImage.Catalogue()

        s["s"] = GafferScene.Sphere()

        s["PathFilter"] = GafferScene.PathFilter("PathFilter")
        s["PathFilter"]["paths"].setValue(IECore.StringVectorData(['/sphere']))

        s["ShaderAssignment"] = GafferScene.ShaderAssignment(
            "ShaderAssignment")
        s["ShaderAssignment"]["in"].setInput(s["s"]["out"])
        s["ShaderAssignment"]["filter"].setInput(s["PathFilter"]["out"])

        s["lambert"], _ = self._createMatteShader()
        s["ShaderAssignment"]["shader"].setInput(s["lambert"]["out"])

        s["StandardAttributes"] = GafferScene.StandardAttributes(
            "StandardAttributes")
        s["StandardAttributes"]["attributes"]["linkedLights"][
            "enabled"].setValue(True)
        s["StandardAttributes"]["attributes"]["linkedLights"][
            "value"].setValue("defaultLights")
        s["StandardAttributes"]["filter"].setInput(s["PathFilter"]["out"])
        s["StandardAttributes"]["in"].setInput(s["ShaderAssignment"]["out"])

        s["Light"] = GafferArnold.ArnoldLight("skydome_light")
        s["Light"].loadShader("skydome_light")

        s["c"] = GafferScene.Camera()
        s["c"]["transform"]["translate"]["z"].setValue(2)

        s["group"] = GafferScene.Group()
        s["group"]["in"][0].setInput(s["StandardAttributes"]["out"])
        s["group"]["in"][1].setInput(s["Light"]["out"])
        s["group"]["in"][2].setInput(s["c"]["out"])

        s["o"] = GafferScene.Outputs()
        s["o"].addOutput(
            "beauty",
            IECoreScene.Output(
                "test", "ieDisplay", "rgba", {
                    "driverType":
                    "ClientDisplayDriver",
                    "displayHost":
                    "localhost",
                    "displayPort":
                    str(s['catalogue'].displayDriverServer().portNumber()),
                    "remoteDisplayType":
                    "GafferImage::GafferDisplayDriver",
                }))
        s["o"]["in"].setInput(s["group"]["out"])

        s["so"] = GafferScene.StandardOptions()
        s["so"]["options"]["renderCamera"]["value"].setValue("/group/camera")
        s["so"]["options"]["renderCamera"]["enabled"].setValue(True)
        s["so"]["in"].setInput(s["o"]["out"])

        s["r"] = self._createInteractiveRender()
        s["r"]["in"].setInput(s["so"]["out"])

        # Start rendering and make sure the light is linked to the sphere

        s["r"]["state"].setValue(s["r"].State.Running)

        self.uiThreadCallHandler.waitFor(1.0)

        self.assertAlmostEqual(self._color4fAtUV(s["catalogue"],
                                                 imath.V2f(0.5)).r,
                               1,
                               delta=0.01)

        # Change a value on the light. The light should still be linked to the sphere
        # and we should get the same result as before.
        s["Light"]['parameters']['shadow_density'].setValue(0.0)

        self.uiThreadCallHandler.waitFor(1.0)

        self.assertAlmostEqual(self._color4fAtUV(s["catalogue"],
                                                 imath.V2f(0.5)).r,
                               1,
                               delta=0.01)

        s["r"]["state"].setValue(s["r"].State.Stopped)
    def testEditSubdivisionAttributes(self):

        script = Gaffer.ScriptNode()

        script["cube"] = GafferScene.Cube()
        script["cube"]["dimensions"].setValue(imath.V3f(2))

        script["meshType"] = GafferScene.MeshType()
        script["meshType"]["in"].setInput(script["cube"]["out"])
        script["meshType"]["meshType"].setValue("catmullClark")

        script["attributes"] = GafferArnold.ArnoldAttributes()
        script["attributes"]["in"].setInput(script["meshType"]["out"])
        script["attributes"]["attributes"]["subdivIterations"][
            "enabled"].setValue(True)

        script["catalogue"] = GafferImage.Catalogue()

        script["outputs"] = GafferScene.Outputs()
        script["outputs"].addOutput(
            "beauty",
            IECoreScene.Output(
                "test", "ieDisplay", "rgba", {
                    "driverType":
                    "ClientDisplayDriver",
                    "displayHost":
                    "localhost",
                    "displayPort":
                    str(script['catalogue'].displayDriverServer().portNumber()
                        ),
                    "remoteDisplayType":
                    "GafferImage::GafferDisplayDriver",
                }))
        script["outputs"]["in"].setInput(script["attributes"]["out"])

        script["imageStats"] = GafferImage.ImageStats()
        script["imageStats"]["in"].setInput(script["catalogue"]["out"])
        script["imageStats"]["channels"].setValue(
            IECore.StringVectorData(["R", "G", "B", "A"]))
        script["imageStats"]["area"].setValue(
            imath.Box2i(imath.V2i(0), imath.V2i(640, 480)))

        script["options"] = GafferScene.StandardOptions()
        script["options"]["in"].setInput(script["outputs"]["out"])
        script["options"]["options"]["filmFit"]["enabled"].setValue(True)
        script["options"]["options"]["filmFit"]["value"].setValue(
            IECoreScene.Camera.FilmFit.Fit)

        script["render"] = self._createInteractiveRender()
        script["render"]["in"].setInput(script["options"]["out"])

        # Render the cube with one level of subdivision. Check we get roughly the
        # alpha coverage we expect.

        script["render"]["state"].setValue(script["render"].State.Running)

        self.uiThreadCallHandler.waitFor(1)

        self.assertAlmostEqual(script["imageStats"]["average"][3].getValue(),
                               0.381,
                               delta=0.001)

        # Now up the number of subdivision levels. The alpha coverage should
        # increase as the shape tends towards the limit surface.

        script["attributes"]["attributes"]["subdivIterations"][
            "value"].setValue(4)
        self.uiThreadCallHandler.waitFor(1)

        self.assertAlmostEqual(script["imageStats"]["average"][3].getValue(),
                               0.424,
                               delta=0.001)

        script["render"]["state"].setValue(script["render"].State.Stopped)
예제 #20
0
    def testCannotViewCatalogue(self):

        view = GafferSceneUI.ShaderView()
        catalogue = GafferImage.Catalogue()
        self.assertFalse(view["in"].acceptsInput(catalogue["out"]))
예제 #21
0
    def testCacheReuse(self):

        # Send an image to the catalogue, and also
        # capture the display driver that we used to
        # send it.

        c = GafferImage.Catalogue()
        c["directory"].setValue(
            os.path.join(self.temporaryDirectory(), "catalogue"))

        drivers = GafferTest.CapturingSlot(
            GafferImage.Display.driverCreatedSignal())

        r = GafferImage.ImageReader()
        r["fileName"].setValue(
            "${GAFFER_ROOT}/python/GafferImageTest/images/checker.exr")
        self.sendImage(r["out"], c)

        self.assertEqual(len(drivers), 1)

        # The image will have been saved to disk so it can persist between sessions,
        # and the Catalogue should have dropped any reference it has to the driver,
        # in order to save memory.

        self.assertEqual(len(c["images"]), 1)
        self.assertEqual(
            os.path.dirname(c["images"][0]["fileName"].getValue()),
            c["directory"].getValue())

        self.assertEqual(drivers[0][0].refCount(), 1)

        # But we don't want the Catalogue to immediately reload the image from
        # disk, because for large images with many AOVs this is a huge overhead.
        # We want to temporarily reuse the cache entries that were created from
        # the data in the display driver. These should be identical to a regular
        # Display node containing the same driver.

        display = GafferImage.Display()
        display.setDriver(drivers[0][0])

        self.assertEqual(display["out"].channelDataHash("R", imath.V2i(0)),
                         c["out"].channelDataHash("R", imath.V2i(0)))
        self.assertTrue(display["out"].channelData(
            "R", imath.V2i(0),
            _copy=False).isSame(c["out"].channelData("R",
                                                     imath.V2i(0),
                                                     _copy=False)))

        # This applies to copies too

        c["images"].addChild(
            GafferImage.Catalogue.Image(flags=Gaffer.Plug.Flags.Default
                                        | Gaffer.Plug.Flags.Dynamic))
        self.assertEqual(len(c["images"]), 2)
        c["images"][1].copyFrom(c["images"][0])

        c["imageIndex"].setValue(1)
        self.assertEqual(display["out"].channelDataHash("R", imath.V2i(0)),
                         c["out"].channelDataHash("R", imath.V2i(0)))
        self.assertTrue(display["out"].channelData(
            "R", imath.V2i(0),
            _copy=False).isSame(c["out"].channelData("R",
                                                     imath.V2i(0),
                                                     _copy=False)))
예제 #22
0
    def testRenamePromotedImages(self):

        # Create boxed Catalogue with promoted `images` plug.

        box = Gaffer.Box()

        box["catalogue"] = GafferImage.Catalogue()
        box["catalogue"]["directory"].setValue(
            os.path.join(self.temporaryDirectory(), "catalogue"))

        images = Gaffer.PlugAlgo.promote(box["catalogue"]["images"])

        # Send 2 images and name them using the promoted plugs.

        red = GafferImage.Constant()
        red["format"].setValue(GafferImage.Format(64, 64))
        red["color"]["r"].setValue(1)
        self.sendImage(red["out"], box["catalogue"])
        images[-1].setName("Red")

        green = GafferImage.Constant()
        green["format"].setValue(GafferImage.Format(64, 64))
        green["color"]["g"].setValue(1)
        self.sendImage(green["out"], box["catalogue"])
        images[-1].setName("Green")

        # Assert that images are accessible under those names.

        with Gaffer.Context() as c:
            c["catalogue:imageName"] = "Red"
            self.assertImagesEqual(box["catalogue"]["out"],
                                   red["out"],
                                   ignoreMetadata=True)
            c["catalogue:imageName"] = "Green"
            self.assertImagesEqual(box["catalogue"]["out"],
                                   green["out"],
                                   ignoreMetadata=True)

        # And that invalid names generate errors.

        with six.assertRaisesRegex(self, RuntimeError,
                                   'Unknown image name "Blue"'):
            with Gaffer.Context() as c:
                c["catalogue:imageName"] = "Blue"
                box["catalogue"]["out"].metadata()

        # Assert that we can rename the images and get them under the new name.

        images[0].setName("Crimson")
        images[1].setName("Emerald")

        with Gaffer.Context() as c:
            c["catalogue:imageName"] = "Crimson"
            self.assertImagesEqual(box["catalogue"]["out"],
                                   red["out"],
                                   ignoreMetadata=True)
            c["catalogue:imageName"] = "Emerald"
            self.assertImagesEqual(box["catalogue"]["out"],
                                   green["out"],
                                   ignoreMetadata=True)

        # And that the old names are now invalid.

        with six.assertRaisesRegex(self, RuntimeError,
                                   'Unknown image name "Red"'):
            with Gaffer.Context() as c:
                c["catalogue:imageName"] = "Red"
                box["catalogue"]["out"].metadata()
예제 #23
0
    def testDeleteKeepsOrder(self):

        # Send 4 images to a Catalogue : red, green, blue, yellow

        script = Gaffer.ScriptNode()
        script["catalogue"] = GafferImage.Catalogue()
        script["catalogue"]["directory"].setValue(
            os.path.join(self.temporaryDirectory(), "catalogue"))

        script["red"] = GafferImage.Constant()
        script["red"]["format"].setValue(GafferImage.Format(64, 64))
        script["red"]["color"]["r"].setValue(1)
        self.sendImage(script["red"]["out"], script["catalogue"])
        script["catalogue"]["images"][-1].setName("Red")

        script["green"] = GafferImage.Constant()
        script["green"]["format"].setValue(GafferImage.Format(64, 64))
        script["green"]["color"]["g"].setValue(1)
        self.sendImage(script["green"]["out"], script["catalogue"])
        script["catalogue"]["images"][-1].setName("Green")

        script["blue"] = GafferImage.Constant()
        script["blue"]["format"].setValue(GafferImage.Format(64, 64))
        script["blue"]["color"]["b"].setValue(1)
        self.sendImage(script["blue"]["out"], script["catalogue"])
        script["catalogue"]["images"][-1].setName("Blue")

        script["yellow"] = GafferImage.Constant()
        script["yellow"]["format"].setValue(GafferImage.Format(64, 64))
        script["yellow"]["color"].setValue(imath.Color4f(1, 1, 0, 1))
        self.sendImage(script["yellow"]["out"], script["catalogue"])
        script["catalogue"]["images"][-1].setName("Yellow")

        script["fileName"].setValue("/tmp/ttt.gfr")
        script.save()

        # Check it worked

        def assertPreconditions():

            self.assertEqual(len(script["catalogue"]["images"]), 4)
            self.assertEqual(script["catalogue"]["images"][0].getName(), "Red")
            self.assertEqual(script["catalogue"]["images"][1].getName(),
                             "Green")
            self.assertEqual(script["catalogue"]["images"][2].getName(),
                             "Blue")
            self.assertEqual(script["catalogue"]["images"][3].getName(),
                             "Yellow")

            script["catalogue"]["imageIndex"].setValue(0)
            self.assertImagesEqual(script["catalogue"]["out"],
                                   script["red"]["out"],
                                   ignoreMetadata=True)
            script["catalogue"]["imageIndex"].setValue(1)
            self.assertImagesEqual(script["catalogue"]["out"],
                                   script["green"]["out"],
                                   ignoreMetadata=True)
            script["catalogue"]["imageIndex"].setValue(2)
            self.assertImagesEqual(script["catalogue"]["out"],
                                   script["blue"]["out"],
                                   ignoreMetadata=True)
            script["catalogue"]["imageIndex"].setValue(3)
            self.assertImagesEqual(script["catalogue"]["out"],
                                   script["yellow"]["out"],
                                   ignoreMetadata=True)

            with Gaffer.Context(script.context()) as c:
                c["catalogue:imageName"] = "Red"
                self.assertImagesEqual(script["catalogue"]["out"],
                                       script["red"]["out"],
                                       ignoreMetadata=True)
                c["catalogue:imageName"] = "Green"
                self.assertImagesEqual(script["catalogue"]["out"],
                                       script["green"]["out"],
                                       ignoreMetadata=True)
                c["catalogue:imageName"] = "Blue"
                self.assertImagesEqual(script["catalogue"]["out"],
                                       script["blue"]["out"],
                                       ignoreMetadata=True)
                c["catalogue:imageName"] = "Yellow"
                self.assertImagesEqual(script["catalogue"]["out"],
                                       script["yellow"]["out"],
                                       ignoreMetadata=True)

        assertPreconditions()

        # Delete green, then blue, then yellow

        script["catalogue"]["imageIndex"].setValue(0)

        with Gaffer.UndoScope(script):
            del script["catalogue"]["images"][1]
            del script["catalogue"]["images"][1]
            del script["catalogue"]["images"][1]

        # Check it worked

        def assertPostConditions():

            self.assertEqual(len(script["catalogue"]["images"]), 1)
            self.assertEqual(script["catalogue"]["images"][0].getName(), "Red")

            script["catalogue"]["imageIndex"].setValue(0)
            self.assertImagesEqual(script["catalogue"]["out"],
                                   script["red"]["out"],
                                   ignoreMetadata=True)

            with Gaffer.Context(script.context()) as c:
                c["catalogue:imageName"] = "Red"
                self.assertImagesEqual(script["catalogue"]["out"],
                                       script["red"]["out"],
                                       ignoreMetadata=True)

        assertPostConditions()

        # Check that undo and redo work

        script.undo()
        assertPreconditions()

        script.redo()
        assertPostConditions()

        script.undo()
        assertPreconditions()
예제 #24
0
    def runInteractive(self, useUI, useBlur, resolution):

        script = Gaffer.ScriptNode()

        script["Camera"] = GafferScene.Camera()
        script["Camera"]["transform"]["translate"]["z"].setValue(6)

        script["Sphere"] = GafferScene.Sphere("Sphere")
        script["Sphere"]["radius"].setValue(10)

        script["ImageShader"] = GafferArnold.ArnoldShader()
        script["ImageShader"].loadShader("image")
        script["ImageShader"]["parameters"]["filename"].setValue(
            os.path.dirname(__file__) +
            "/../GafferImageTest/images/GafferChecker.exr")
        script["ImageShader"]["parameters"]["sscale"].setValue(16)
        script["ImageShader"]["parameters"]["tscale"].setValue(16)

        script["ShaderAssignment"] = GafferScene.ShaderAssignment()
        script["ShaderAssignment"]["in"].setInput(script["Sphere"]["out"])
        script["ShaderAssignment"]["shader"].setInput(
            script["ImageShader"]["out"])

        script["Group"] = GafferScene.Group()
        script["Group"]["in"][0].setInput(script["Camera"]["out"])
        script["Group"]["in"][1].setInput(script["ShaderAssignment"]["out"])

        script["StandardOptions"] = GafferScene.StandardOptions()
        script["StandardOptions"]["in"].setInput(script["Group"]["out"])
        script["StandardOptions"]["options"]["renderCamera"]["value"].setValue(
            '/group/camera')
        script["StandardOptions"]["options"]["renderCamera"][
            "enabled"].setValue(True)
        script["StandardOptions"]["options"]["renderResolution"][
            "value"].setValue(imath.V2i(resolution, resolution))
        script["StandardOptions"]["options"]["renderResolution"][
            "enabled"].setValue(True)

        script["ArnoldOptions"] = GafferArnold.ArnoldOptions("ArnoldOptions")
        script["ArnoldOptions"]["in"].setInput(
            script["StandardOptions"]["out"])
        # Make sure we leave some CPU available for Gaffer
        script["ArnoldOptions"]["options"]["threads"]["value"].setValue(-1)
        script["ArnoldOptions"]["options"]["threads"]["enabled"].setValue(True)

        script["Outputs"] = GafferScene.Outputs()
        script["Outputs"].addOutput(
            "beauty",
            IECoreScene.Output(
                "Interactive/Beauty", "ieDisplay", "rgba", {
                    "quantize":
                    IECore.IntVectorData([0, 0, 0, 0]),
                    "driverType":
                    'ClientDisplayDriver',
                    "displayHost":
                    'localhost',
                    "displayPort":
                    str(GafferImage.Catalogue.displayDriverServer().portNumber(
                    )),
                    "remoteDisplayType":
                    'GafferImage::GafferDisplayDriver',
                    "filter":
                    'box',
                }))
        script["Outputs"]["in"].setInput(script["ArnoldOptions"]["out"])

        script[
            "InteractiveArnoldRender"] = GafferArnold.InteractiveArnoldRender(
            )
        script["InteractiveArnoldRender"]["in"].setInput(
            script["Outputs"]["out"])

        script["Catalogue"] = GafferImage.Catalogue("Catalogue")
        script["Catalogue"]["directory"].setValue(self.temporaryDirectory() +
                                                  "/catalogues/test")

        script["Blur"] = GafferImage.Blur("Blur")
        script["Blur"]["in"].setInput(script["Catalogue"]["out"])
        script["Blur"]["radius"]["x"].setValue(1.0)
        script["Blur"]["radius"]["y"].setValue(1.0)

        watchNode = script["Blur"] if useBlur else script["Catalogue"]

        if useUI:

            with GafferUI.Window() as window:
                window.setFullScreen(True)
                viewer = GafferUI.Viewer(script)

            window.setVisible(True)
            viewer.setNodeSet(Gaffer.StandardSet([watchNode]))

            script['InteractiveArnoldRender']['state'].setValue(
                GafferScene.InteractiveRender.State.Running)
            self.waitForIdle(10)

            viewer.view().viewportGadget().frame(
                viewer.view().viewportGadget().getPrimaryChild().bound(),
                imath.V3f(0, 0, 1))

            frameCounter = {'i': 0}

            def testFunc():
                frameCounter['i'] += 1
                script["Camera"]["transform"]["translate"]["x"].setValue(
                    math.sin(frameCounter['i'] * 0.1))
                if frameCounter['i'] >= 50:
                    GafferUI.EventLoop.mainEventLoop().stop()

            timer = QtCore.QTimer()
            timer.setInterval(20)
            timer.timeout.connect(testFunc)

            GafferImageUI.ImageGadget.resetTileUpdateCount()
            timer.start()

            with GafferTest.TestRunner.PerformanceScope() as ps:
                GafferUI.EventLoop.mainEventLoop().start()
                ps.setNumIterations(
                    GafferImageUI.ImageGadget.tileUpdateCount())

            script['InteractiveArnoldRender']['state'].setValue(
                GafferScene.InteractiveRender.State.Stopped)

            del window, viewer, timer
            self.waitForIdle(10)

        else:
            with GafferTest.ParallelAlgoTest.UIThreadCallHandler() as h:

                with IECore.CapturingMessageHandler() as mh:
                    script['InteractiveArnoldRender']['state'].setValue(
                        GafferScene.InteractiveRender.State.Running)
                    h.waitFor(2)
                arnoldStartupErrors = mh.messages

                tc = Gaffer.ScopedConnection(
                    GafferImageTest.connectProcessTilesToPlugDirtiedSignal(
                        watchNode["out"]))

                with GafferTest.TestRunner.PerformanceScope() as ps:
                    with Gaffer.PerformanceMonitor() as m:
                        for i in range(250):
                            script["Camera"]["transform"]["translate"][
                                "x"].setValue(math.sin((i + 1) * 0.1))
                            h.waitFor(0.02)

                    ps.setNumIterations(
                        m.plugStatistics(
                            watchNode["out"]
                            ["channelData"].source()).computeCount)

                script['InteractiveArnoldRender']['state'].setValue(
                    GafferScene.InteractiveRender.State.Stopped)