Пример #1
0
	def testSerialisationPlugAccumulation( self ) :

		s = Gaffer.ScriptNode()

		s["n"] = Gaffer.Node()
		s["n"]["user"].addChild( Gaffer.FloatPlug( "f", flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) )

		s["e"] = Gaffer.Expression()
		s["e"]["engine"].setValue( "python" )

		s["e"]["expression"].setValue( "parent[\"n\"][\"user\"][\"f\"] = 2" )

		self.assertEqual( s["n"]["user"]["f"].getValue(), 2 )

		ss = s.serialise()

		s2 = Gaffer.ScriptNode()
		s2.execute( ss )

		self.assertEqual( s2["n"]["user"]["f"].getValue(), 2 )

		self.failUnless( s2["e"].getChild("out1") is None )
		self.failUnless( s2["e"].getChild("in1") is None )
Пример #2
0
    def testSerialisationCreationOrder(self):

        # Create a script where the expression node is created before the nodes it's targeting,
        # and make sure it still serialises/loads correctly.
        s = Gaffer.ScriptNode()

        s["e"] = Gaffer.Expression()

        s["m1"] = GafferTest.MultiplyNode()
        s["m1"]["op1"].setValue(10)
        s["m1"]["op2"].setValue(20)

        s["m2"] = GafferTest.MultiplyNode()
        s["m2"]["op2"].setValue(1)

        s["e"].setExpression(
            "parent[\"m2\"][\"op1\"] = parent[\"m1\"][\"product\"] * 2",
            "python")
        self.assertEqual(s["m2"]["product"].getValue(), 400)

        s2 = Gaffer.ScriptNode()
        s2.execute(s.serialise())
        self.assertEqual(s2["m2"]["product"].getValue(), 400)
Пример #3
0
	def testGlobalContext( self ) :

		script = Gaffer.ScriptNode()

		script["shader"] = GafferSceneTest.TestShader()
		script["shader"]["type"].setValue( "shader" )

		script["expression"] = Gaffer.Expression()
		script["expression"].setExpression( 'parent["shader"]["parameters"]["i"] = 1 if context.get( "scene:path", None ) else 0' )

		script["sphere"] = GafferScene.Sphere()

		script["filter"] = GafferScene.PathFilter()
		script["filter"]["paths"].setValue( IECore.StringVectorData( [ "/sphere" ] ) )

		script["assignment"] = GafferScene.ShaderAssignment()
		script["assignment"]["in"].setInput( script["sphere"]["out"] )
		script["assignment"]["filter"].setInput( script["filter"]["out"] )
		script["assignment"]["shader"].setInput( script["shader"]["out"] )

		self.assertEqual(
			script["assignment"]["out"].attributes( "/sphere" )["shader"].outputShader().parameters["i"].value, 0
		)
Пример #4
0
    def testExpressions(self):

        s = Gaffer.ScriptNode()
        s["n1"] = Gaffer.Node()
        s["n2"] = Gaffer.Node()
        s["n1"]["user"]["f"] = GafferImage.AtomicFormatPlug(
            flags=Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic)
        s["n2"]["user"]["f"] = GafferImage.AtomicFormatPlug(
            flags=Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic)

        s["e"] = Gaffer.Expression()
        s["e"].setExpression(
            'f = parent["n1"]["user"]["f"]; b = f.getDisplayWindow(); b.setMin( b.min() - imath.V2i( 10 ) ); b.setMax( b.max() + imath.V2i( 20 ) ); f.setPixelAspect( 0.5 ); f.setDisplayWindow( b ); parent["n2"]["user"]["f"] = f'
        )

        s["n1"]["user"]["f"].setValue(
            GafferImage.Format(
                imath.Box2i(imath.V2i(20, 30), imath.V2i(100, 110)), 1))

        self.assertEqual(
            s["n2"]["user"]["f"].getValue(),
            GafferImage.Format(
                imath.Box2i(imath.V2i(10, 20), imath.V2i(120, 130)), 0.5))
Пример #5
0
	def testImathContextVariable( self ) :

		s = Gaffer.ScriptNode()
		s["t"] = GafferDispatchTest.TextWriter()
		s["t"]["fileName"].setValue( self.temporaryDirectory() + "/test.txt" )

		s["e"] = Gaffer.Expression()
		s["e"].setExpression( inspect.cleandoc(
			"""
			c = context["c"]
			parent["t"]["text"] = "{0} {1} {2}".format( *c )
			"""
		) )

		s["fileName"].setValue(  self.temporaryDirectory() + "/test.gfr" )
		s.save()

		subprocess.check_call( [ "gaffer", "execute", s["fileName"].getValue(), "-context", "c", "imath.Color3f( 0, 1, 2 )" ] )

		self.assertEqual(
			open( s["t"]["fileName"].getValue() ).read(),
			"0.0 1.0 2.0"
		)
Пример #6
0
    def testCancellationDuringCompute(self):

        s = Gaffer.ScriptNode()

        s["n"] = GafferTest.AddNode()
        s["e"] = Gaffer.Expression()
        s["e"].setExpression(
            inspect.cleandoc("""
			IECore.Canceller.check( context.canceller() )
			parent['n']['op1'] = 40
			"""))

        canceller = IECore.Canceller()
        canceller.cancel()

        with Gaffer.Context(s.context(), canceller):
            with self.assertRaises(IECore.Cancelled):
                s["n"]["sum"].getValue()

        canceller = IECore.Canceller()

        with Gaffer.Context(s.context(), canceller):
            self.assertEqual(s["n"]["sum"].getValue(), 40)
    def testBackgroundDispatch(self):

        script = Gaffer.ScriptNode()

        script["writer"] = GafferDispatchTest.TextWriter()

        script["expression"] = Gaffer.Expression()
        script["expression"].setExpression(
            'parent.writer.fileName = "' + self.temporaryDirectory() +
            '/test.txt"', "OSL")

        dispatcher = GafferDispatch.LocalDispatcher(
            jobPool=GafferDispatch.LocalDispatcher.JobPool())
        dispatcher["jobsDirectory"].setValue(
            "/tmp/gafferOSLExpressionEngineTest/jobs")
        dispatcher["executeInBackground"].setValue(True)
        dispatcher.dispatch([script["writer"]])

        dispatcher.jobPool().waitForAll()
        self.assertEqual(len(dispatcher.jobPool().failedJobs()), 0)

        self.assertTrue(os.path.exists(self.temporaryDirectory() +
                                       "/test.txt"))
Пример #8
0
    def test(self):

        s = Gaffer.ScriptNode()

        s["m"] = GafferTest.MultiplyNode()
        s["m"]["op2"].setValue(1)

        s["e"] = Gaffer.Expression()
        s["e"].setExpression(
            "parent[\"m\"][\"op1\"] = int( context[\"frame\"] )")

        s["w"] = Gaffer.TimeWarp()
        s["w"].setup(Gaffer.IntPlug())
        s["w"]["in"].setInput(s["m"]["product"])
        s["w"]["offset"].setValue(2)
        s["w"]["speed"].setValue(2)

        for i in range(0, 10):
            c = Gaffer.Context()
            c.setFrame(i)
            with c:
                self.assertEqual(s["m"]["product"].getValue(), i)
                self.assertEqual(s["w"]["out"].getValue(), i * 2 + 2)
Пример #9
0
    def testDeleteExpressionText(self):

        s = Gaffer.ScriptNode()

        s["m1"] = GafferTest.MultiplyNode()
        s["m1"]["op1"].setValue(10)
        s["m1"]["op2"].setValue(20)

        s["m2"] = GafferTest.MultiplyNode()
        s["m2"]["op2"].setValue(1)

        s["e"] = Gaffer.Expression()
        s["e"]["engine"].setValue("python")

        s["e"].setExpression(
            "parent[\"m2\"][\"op1\"] = parent[\"m1\"][\"product\"] * 2")

        self.failUnless(s["m2"]["op1"].getInput().node().isSame(s["e"]))
        self.assertEqual(s["m2"]["product"].getValue(), 400)

        s["e"].setExpression("")
        self.failUnless(s["m2"]["op1"].getInput() is None)
        self.assertEqual(s["m2"]["product"].getValue(), 0)
Пример #10
0
    def testStringContextVariableComparison(self):

        s = Gaffer.ScriptNode()

        s["n"] = Gaffer.Node()
        s["n"]["user"]["i"] = Gaffer.IntPlug(flags=Gaffer.Plug.Flags.Default
                                             | Gaffer.Plug.Flags.Dynamic)

        expression = inspect.cleandoc("""
			string var = context( "str" );
			parent.n.user.i = var == "abc";
			""")

        s["e"] = Gaffer.Expression()
        s["e"].setExpression(expression, "OSL")

        with Gaffer.Context() as c:

            c["str"] = "xyz"
            self.assertEqual(s["n"]["user"]["i"].getValue(), 0)

            c["str"] = "abc"
            self.assertEqual(s["n"]["user"]["i"].getValue(), 1)
Пример #11
0
    def testSetsNeedContextEntry(self):

        script = Gaffer.ScriptNode()

        script["light"] = GafferArnold.ArnoldLight()
        script["light"].loadShader("point_light")

        script["expression"] = Gaffer.Expression()
        script["expression"].setExpression(
            """parent["light"]["name"] = context["lightName"]""")

        script["render"] = GafferArnold.ArnoldRender()
        script["render"]["in"].setInput(script["light"]["out"])
        script["render"]["mode"].setValue(
            script["render"].Mode.SceneDescriptionMode)
        script["render"]["fileName"].setValue(self.temporaryDirectory() +
                                              "/test.ass")

        for i in range(0, 100):

            with Gaffer.Context() as context:
                context["lightName"] = "light%d" % i
                script["render"]["task"].execute()
Пример #12
0
    def testSwitchWithComponentConnections(self):

        s = Gaffer.ScriptNode()

        s["n1"] = GafferSceneTest.TestShader("n1")
        s["n2"] = GafferSceneTest.TestShader("n2")
        s["n3"] = GafferSceneTest.TestShader("n3")
        s["n3"]["type"].setValue("test:surface")

        s["switch"] = Gaffer.Switch()
        s["switch"].setup(s["n3"]["parameters"]["c"])

        s["switch"]["in"][0].setInput(s["n1"]["out"])
        s["switch"]["in"][1].setInput(s["n2"]["out"])

        s["n3"]["parameters"]["c"]["r"].setInput(s["switch"]["out"]["r"])

        s["expression"] = Gaffer.Expression()
        s["expression"].setExpression(
            'parent["switch"]["index"] = context["index"]')

        with Gaffer.Context() as context:

            for i in range(0, 3):

                context["index"] = i
                effectiveIndex = i % 2

                network = s["n3"].attributes()["test:surface"]
                self.assertEqual(len(network), 2)
                self.assertEqual(network.inputConnections("n3"), [
                    network.Connection(
                        network.Parameter(
                            "n{0}".format(effectiveIndex + 1),
                            "r",
                        ), network.Parameter("n3", "c.r"))
                ])
    def testDuplicateDeserialise(self):

        s = Gaffer.ScriptNode()

        s["source"] = Gaffer.Node()
        s["source"]["p"] = Gaffer.V3fPlug(flags=Gaffer.Plug.Flags.Default
                                          | Gaffer.Plug.Flags.Dynamic)
        s["source"]["p"].setValue(imath.V3f(0.1, 0.2, 0.3))

        s["dest"] = Gaffer.Node()
        s["dest"]["p"] = Gaffer.V3fPlug(flags=Gaffer.Plug.Flags.Default
                                        | Gaffer.Plug.Flags.Dynamic)

        s["e"] = Gaffer.Expression()
        s["e"].setExpression(
            "parent.dest.p.x = parent.source.p.x + 1;\n" +
            "parent.dest.p.y = parent.source.p.y + 2;\n" +
            "parent.dest.p.z = parent.source.p.z + 3;\n",
            "OSL",
        )

        ss = s.serialise()

        s.execute(ss)
        s.execute(ss)

        self.assertEqual(s["dest"]["p"].getValue(), imath.V3f(1.1, 2.2, 3.3))
        self.assertEqual(s["dest1"]["p"].getValue(), imath.V3f(1.1, 2.2, 3.3))
        self.assertEqual(s["dest2"]["p"].getValue(), imath.V3f(1.1, 2.2, 3.3))

        # Working well so far, but we've had a bug that could be hidden by the caching.  Lets
        # try evaluating the plugs again, but flushing the cache each time

        Gaffer.ValuePlug.clearCache()
        self.assertEqual(s["dest"]["p"].getValue(), imath.V3f(1.1, 2.2, 3.3))
        self.assertEqual(s["dest1"]["p"].getValue(), imath.V3f(1.1, 2.2, 3.3))
        self.assertEqual(s["dest2"]["p"].getValue(), imath.V3f(1.1, 2.2, 3.3))
Пример #14
0
	def _createTraceSetShader( self ) :
		# It's currently pretty ugly how we need to disable the trace set when it is left empty,
		# to match the behaviour expected by GafferSceneTest.InteractiveRenderTest.
		# Would be somewhat cleaner if we had the primaryInput metadata on trace_set
		# available, so we could just put an expression on it to disable it when no trace set is given,
		# but it doesn't seem very safe to do a metadata load in the middle of the tests
		shaderBox = Gaffer.Box()

		shader = GafferArnold.ArnoldShader("shader")
		shader.loadShader( "standard_surface" )

		shader["parameters"]["base"].setValue( 1 )
		shader["parameters"]["specular_roughness"].setValue( 0 )
		shader["parameters"]["metalness"].setValue( 1 )
		shader["parameters"]["specular_IOR"].setValue( 100 )

		#return shader, Gaffer.StringPlug( "unused" )

		traceSetShader = GafferArnold.ArnoldShader("traceSetShader")
		traceSetShader.loadShader( "trace_set" )
		traceSetShader["parameters"]["passthrough"].setInput( shader["out"] )

		switchShader = GafferArnold.ArnoldShader("switchShader")
		switchShader.loadShader( "switch_shader" )
		switchShader["parameters"]["input0"].setInput( shader["out"] )
		switchShader["parameters"]["input1"].setInput( traceSetShader["out"] )

		shaderBox.addChild( shader )
		shaderBox.addChild( traceSetShader )
		shaderBox.addChild( switchShader )

		shaderBox["enableExpression"] = Gaffer.Expression()
		shaderBox["enableExpression"].setExpression( 'parent.switchShader.parameters.index = parent.traceSetShader.parameters.trace_set != ""', "OSL" )

		Gaffer.PlugAlgo.promote( switchShader["out"] )

		return shaderBox, traceSetShader["parameters"]["trace_set"]
Пример #15
0
    def testDisabling(self):

        script = Gaffer.ScriptNode()

        script["constant"] = GafferImage.Constant()

        script["expression"] = Gaffer.Expression()
        script["expression"].setExpression(
            'parent["constant"]["color"]["r"] = context["frame"]')

        script["timeWarp"] = Gaffer.TimeWarp()
        script["timeWarp"].setup(GafferImage.ImagePlug())

        script["timeWarp"]["offset"].setValue(1)
        script["timeWarp"]["in"].setInput(script["constant"]["out"])

        with script.context():

            c = script["constant"]["out"].image()
            cHash = script["constant"]["out"].imageHash()
            t = script["timeWarp"]["out"].image()
            tHash = script["timeWarp"]["out"].imageHash()

        self.assertNotEqual(c, t)
        self.assertNotEqual(cHash, tHash)

        script["timeWarp"]["enabled"].setValue(False)

        with script.context():

            c = script["constant"]["out"].image()
            cHash = script["constant"]["out"].imageHash()
            t = script["timeWarp"]["out"].image()
            tHash = script["timeWarp"]["out"].imageHash()

        self.assertEqual(c, t)
        self.assertEqual(cHash, tHash)
Пример #16
0
    def testMoreThanTenPlugs(self):

        s = Gaffer.ScriptNode()

        expression = ""
        for i in range(0, 20):

            aName = "A%d" % i
            bName = "B%d" % i

            s[aName] = Gaffer.Node()
            s[bName] = Gaffer.Node()

            s[aName]["user"]["p"] = Gaffer.IntPlug(
                defaultValue=i,
                flags=Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic)
            s[bName]["user"]["p"] = Gaffer.IntPlug(
                flags=Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic)

            expression += "parent.%s.user.p = parent.%s.user.p;\n" % (bName,
                                                                      aName)

        s["e"] = Gaffer.Expression()
        s["e"].setExpression(expression, "OSL")

        self.assertEqual(s["e"].getExpression(), (expression, "OSL"))

        for i in range(0, 20):
            self.assertEqual(s["B%d" % i]["user"]["p"].getValue(), i)

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

        self.assertEqual(s2["e"].getExpression(), (expression, "OSL"))

        for i in range(0, 20):
            self.assertEqual(s2["B%d" % i]["user"]["p"].getValue(), i)
Пример #17
0
    def __init__(self, name="_ObjectPreview"):

        Gaffer.Node.__init__(self, name)

        self["fileName"] = Gaffer.StringPlug(
            defaultValue="",
            substitutions=Gaffer.Context.Substitutions.NoSubstitutions)
        self["frameRate"] = Gaffer.FloatPlug(defaultValue=24.0)
        self["samplesPerFrame"] = Gaffer.IntPlug(defaultValue=1, minValue=1)

        # single object scenes using Reader ops behind the scenes?
        self["ObjectReader"] = Gaffer.ObjectReader()
        self["ObjectReaderExpression"] = Gaffer.Expression("Expression")
        self["ObjectReaderExpression"].setExpression('''
import IECore

fileName = parent['fileName']

try :
	sequence = IECore.FileSequence( fileName )
	calc = IECore.OversamplesCalculator( frameRate = parent["frameRate"], samplesPerFrame = parent["samplesPerFrame"] )
	if isinstance( sequence.frameList, IECore.FrameRange ) and sequence.frameList.step == 1 :
		calc.setTicksPerSecond( 24 )

	result = sequence.fileNameForFrame( calc.framesToTicks( context['frame'] ) )

except :
	result = fileName

parent['ObjectReader']['fileName'] = result
''')
        self["ObjectToScene"] = GafferScene.ObjectToScene("ObjectToScene")
        self["ObjectToScene"]["object"].setInput(self["ObjectReader"]["out"])

        self["out"] = GafferScene.ScenePlug(
            direction=Gaffer.Plug.Direction.Out)
        self["out"].setInput(self["ObjectToScene"]["out"])
Пример #18
0
    def testEnabled(self):

        s = Gaffer.ScriptNode()

        s["m"] = GafferTest.MultiplyNode()
        s["m"]["op2"].setValue(1)

        s["e"] = Gaffer.Expression()
        s["e"]["engine"].setValue("python")
        s["e"]["expression"].setValue(
            "parent[\"m\"][\"op1\"] = int( context[\"frame\"] )")

        s["w"] = Gaffer.TimeWarpComputeNode()
        s["w"]["in"] = Gaffer.IntPlug()
        s["w"]["in"].setInput(s["m"]["product"])
        s["w"]["out"] = Gaffer.IntPlug(direction=Gaffer.Plug.Direction.Out)
        s["w"]["offset"].setValue(2)

        # test that enabledPlug() and correspondingInput() are implemented

        self.assertTrue(s["w"].enabledPlug().isSame(s["w"]["enabled"]))
        self.assertTrue(s["w"].correspondingInput(s["w"]["out"]).isSame(
            s["w"]["in"]))

        # test that disabling causes no time warping

        s["w"]["enabled"].setValue(False)

        for i in range(0, 10):
            with Gaffer.Context() as c:

                c.setFrame(i)

                self.assertEqual(s["m"]["product"].getValue(),
                                 s["w"]["out"].getValue())
                self.assertEqual(s["m"]["product"].hash(),
                                 s["w"]["out"].hash())
Пример #19
0
    def __init__(self, name="Scale"):

        GafferImage.ImageProcessor.__init__(self, name)

        self["factor"] = Gaffer.FloatPlug(defaultValue=1, minValue=0)
        self["filter"] = Gaffer.StringPlug(defaultValue="sharp-gaussian")

        self["__Resize"] = GafferImage.Resize()
        self["__Resize"]["filter"].setInput(self["filter"])
        self["__Resize"]["in"].setInput(self["in"])

        self["out"].setInput(self["__Resize"]["out"])

        self["__Expression"] = Gaffer.Expression()
        self["__Expression"].setExpression(
            inspect.cleandoc("""
				format = parent["__Resize"]["in"]["format"]
				w = format.getDisplayWindow()
				parent["__Resize"]["format"]["displayWindow"]["min"]["x"] = parent["factor"] * w.min().x
				parent["__Resize"]["format"]["displayWindow"]["min"]["y"] = parent["factor"] * w.min().y
				parent["__Resize"]["format"]["displayWindow"]["max"]["x"] = parent["factor"] * w.max().x
				parent["__Resize"]["format"]["displayWindow"]["max"]["y"] = parent["factor"] * w.max().y
				parent["__Resize"]["format"]["pixelAspect"] = format.getPixelAspect()
			"""), "python")
Пример #20
0
    def testIdentifier(self):

        s = Gaffer.ScriptNode()
        s["n"] = Gaffer.Node()
        s["n"]["user"]["i"] = Gaffer.FloatPlug(flags=Gaffer.Plug.Flags.Default
                                               | Gaffer.Plug.Flags.Dynamic)
        s["n"]["user"]["o"] = Gaffer.FloatPlug(flags=Gaffer.Plug.Flags.Default
                                               | Gaffer.Plug.Flags.Dynamic)
        s["n"]["user"]["s"] = Gaffer.SplineffPlug(
            flags=Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic)

        s["e"] = Gaffer.Expression()
        s["e"].setExpression("", "OSL")

        # We should be able to set up an expression via script without needing to know
        # the convention for addressing plugs.
        s["e"].setExpression(
            "%s = %s + 1;" % (s["e"].identifier(
                s["n"]["user"]["o"]), s["e"].identifier(s["n"]["user"]["i"])),
            "OSL")
        self.assertEqual(s["n"]["user"]["o"].getValue(), 1)

        # Plug type isn't supported, so should return empty string.
        self.assertEqual(s["e"].identifier(s["n"]["user"]["s"]), "")
Пример #21
0
    def testContextParameter(self):

        s = Gaffer.ScriptNode()

        s["write"] = GafferDispatchTest.TextWriter()
        s["write"]["fileName"].setValue(self.__outputFileSeq.fileName)

        s["e"] = Gaffer.Expression()
        s["e"].setExpression(
            "parent['write']['text'] = '{} {}'.format( context.get( 'valueOne', 0 ), context.get( 'valueTwo', 0 ) )"
        )

        s["fileName"].setValue(self.__scriptFileName)
        s.save()

        self.assertFalse(
            os.path.exists(self.__outputFileSeq.fileNameForFrame(1)))
        p = subprocess.Popen(
            "gaffer execute " + self.__scriptFileName +
            " -context -valueOne 1 -valueTwo 2",
            shell=True,
            stderr=subprocess.PIPE,
            universal_newlines=True,
        )
        p.wait()

        error = "".join(p.stderr.readlines())
        self.assertEqual(error, "")
        self.assertFalse(p.returncode)
        self.assertTrue(
            os.path.exists(self.__outputFileSeq.fileNameForFrame(1)))

        with open(self.__outputFileSeq.fileNameForFrame(1)) as f:
            string = f.read()

        self.assertEqual(string, "1 2")
Пример #22
0
    def testStringVectorDataPlug(self):

        s = Gaffer.ScriptNode()

        s["n"] = Gaffer.Node()
        s["n"]["user"].addChild(
            Gaffer.StringVectorDataPlug("p",
                                        defaultValue=IECore.StringVectorData(),
                                        flags=Gaffer.Plug.Flags.Default
                                        | Gaffer.Plug.Flags.Dynamic))

        s["e"] = Gaffer.Expression()
        s["e"].setExpression(
            'import IECore; parent["n"]["user"]["p"] = IECore.StringVectorData( [ "one", "two" ] )'
        )

        self.assertEqual(s["n"]["user"]["p"].getValue(),
                         IECore.StringVectorData(["one", "two"]))

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

        self.assertEqual(s2["n"]["user"]["p"].getValue(),
                         IECore.StringVectorData(["one", "two"]))
Пример #23
0
    def testContextCompatibility(self):

        script = Gaffer.ScriptNode()

        # Network to assign the existence of "scene:path" as a primvar called "id"

        script["outInt"] = GafferOSL.OSLShader()
        script["outInt"].loadShader("ObjectProcessing/OutInt")

        script["outObject"] = GafferOSL.OSLShader()
        script["outObject"].loadShader("ObjectProcessing/OutObject")
        script["outObject"]["parameters"]["in0"].setInput(
            script["outInt"]["out"]["primitiveVariable"])

        script["expression"] = Gaffer.Expression()
        script["expression"].setExpression(
            'parent["outInt"]["parameters"]["value"] = 1 if context.get( "scene:path", None ) else 0'
        )

        # OSLObject node to apply network

        script["plane"] = GafferScene.Plane()

        script["filter"] = GafferScene.PathFilter()
        script["filter"]["paths"].setValue(IECore.StringVectorData(["/plane"]))

        script["oslObject"] = GafferOSL.OSLObject()
        script["oslObject"]["in"].setInput(script["plane"]["out"])
        script["oslObject"]["filter"].setInput(script["filter"]["out"])
        script["oslObject"]["shader"].setInput(
            script["outObject"]["out"]["out"])

        # Check that "scene:path" isn't exposed to the shader

        self.assertEqual(
            script["oslObject"]["out"].object("/plane")["id"].data[0], 0)
Пример #24
0
	def testParseFailureLeavesStateUnchanged( self ) :

		s = Gaffer.ScriptNode()
		s["n"] = Gaffer.Node()
		s["n"]["user"]["i"] = Gaffer.IntPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )

		s["e"] = Gaffer.Expression()
		s["e"].setExpression( "parent['n']['user']['i'] = context.getFrame()" )

		cs = GafferTest.CapturingSlot( s["e"].expressionChangedSignal() )

		with Gaffer.Context() as c :

			c.setFrame( 10 )
			self.assertEqual( s["n"]["user"]["i"].getValue(), 10 )
			c.setFrame( 20 )
			self.assertEqual( s["n"]["user"]["i"].getValue(), 20 )

		with Gaffer.UndoScope( s ) :

			self.assertRaisesRegexp(
				Exception,
				"SyntaxError",
				s["e"].setExpression,
				"i'm not valid python"
			)

		self.assertEqual( len( cs ), 0 )
		self.assertFalse( s.undoAvailable() )

		with Gaffer.Context() as c :

			c.setFrame( 11 )
			self.assertEqual( s["n"]["user"]["i"].getValue(), 11 )
			c.setFrame( 21 )
			self.assertEqual( s["n"]["user"]["i"].getValue(), 21 )
Пример #25
0
	def testNoDefaultExpressionForUnsupportedPlugs( self ) :

		s = Gaffer.ScriptNode()
		s["n"] = Gaffer.Node()
		s["n"]["user"].addChild(
			Gaffer.SplineffPlug(
				defaultValue = IECore.Splineff(
					IECore.CubicBasisf.linear(),
					(
						( 0, 0 ),
						( 1, 1 ),
					),
				),
				flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic
			)
		)
		s["n"]["user"].addChild( Gaffer.TransformPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) )
		s["n"]["user"].addChild( Gaffer.Transform2DPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) )
		s["n"]["user"].addChild( Gaffer.ValuePlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) )

		s["e"] = Gaffer.Expression()

		for plug in s["n"]["user"] :
			self.assertEqual( s["e"].defaultExpression( plug, "python" ), "" )
Пример #26
0
    def testPathPlugExpression(self):

        s = Gaffer.ScriptNode()

        s["f"] = GafferScene.PathFilter()

        s["e"] = Gaffer.Expression()
        s["e"]["engine"].setValue("python")
        s["e"]["expression"].setValue(
            "import IECore\n"
            "passName = context.get( 'passName', '' )\n"
            "if passName == 'foreground' :\n"
            "	paths = IECore.StringVectorData( [ '/a' ] )\n"
            "else :\n"
            "	paths = IECore.StringVectorData( [ '/b' ] )\n"
            "parent['f']['paths'] = paths")

        with Gaffer.Context() as c:
            c["scene:path"] = IECore.InternedStringVectorData(["a"])
            self.assertEqual(s["f"]["match"].getValue(),
                             GafferScene.Filter.Result.NoMatch)
            c["passName"] = "foreground"
            self.assertEqual(s["f"]["match"].getValue(),
                             GafferScene.Filter.Result.ExactMatch)
Пример #27
0
	def testSerialisation( self ) :

		s = Gaffer.ScriptNode()

		s["m1"] = GafferTest.MultiplyNode()
		s["m1"]["op1"].setValue( 10 )
		s["m1"]["op2"].setValue( 20 )

		s["m2"] = GafferTest.MultiplyNode()
		s["m2"]["op2"].setValue( 1 )

		s["e"] = Gaffer.Expression()
		s["e"]["engine"].setValue( "python" )

		s["e"]["expression"].setValue( "parent[\"m2\"][\"op1\"] = parent[\"m1\"][\"product\"] * 2" )

		self.assertEqual( s["m2"]["product"].getValue(), 400 )

		ss = s.serialise()

		s2 = Gaffer.ScriptNode()
		s2.execute( ss )

		self.assertEqual( s2["m2"]["product"].getValue(), 400 )
Пример #28
0
    def testExecute(self):

        s = Gaffer.ScriptNode()

        s["plane"] = GafferScene.Plane()
        s["render"] = GafferAppleseed.AppleseedRender()
        s["render"]["mode"].setValue(s["render"].Mode.SceneDescriptionMode)
        s["render"]["in"].setInput(s["plane"]["out"])

        s["expression"] = Gaffer.Expression()
        s["expression"].setExpression(
            "parent['render']['fileName'] = '" + self.temporaryDirectory() +
            "/test.%d.appleseed' % int( context['frame'] )")

        s["fileName"].setValue(self.__scriptFileName)
        s.save()

        subprocess.check_call(
            ["gaffer", "execute", self.__scriptFileName, "-frames", "1-3"])

        for i in range(1, 4):
            self.failUnless(
                os.path.exists(self.temporaryDirectory() +
                               "/test.%d.appleseed" % i))
Пример #29
0
def __createExpression(plug):

    node = plug.node()
    parentNode = node.ancestor(Gaffer.Node.staticTypeId())

    with Gaffer.UndoContext(node.scriptNode()):

        expressionNode = Gaffer.Expression()
        parentNode.addChild(expressionNode)

        expression = "parent['"
        expression += plug.relativeName(parentNode).replace(".", "']['")
        expression += "'] = "

        if isinstance(plug, Gaffer.StringPlug):
            expression += "''"
        elif isinstance(plug, Gaffer.IntPlug):
            expression += "1"
        elif isinstance(plug, Gaffer.FloatPlug):
            expression += "1.0"

        expressionNode["expression"].setValue(expression)

    __editExpression(plug)
Пример #30
0
	def testUndo( self ) :

		s = Gaffer.ScriptNode()

		s["n"] = Gaffer.Node()
		s["n"]["user"]["a"] = Gaffer.IntPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
		s["n"]["user"]["b"] = Gaffer.IntPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
		s["n"]["user"]["c"] = Gaffer.IntPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )

		s["e"] = Gaffer.Expression()
		s["e"]["engine"].setValue( "python" )
		s["e"]["expression"].setValue( 'parent["n"]["user"]["a"] = 1; parent["n"]["user"]["b"] = 2; parent["n"]["user"]["c"] = 3' )
		
		self.assertEqual( s["n"]["user"]["a"].getValue(), 1 )
		self.assertEqual( s["n"]["user"]["b"].getValue(), 2 )
		self.assertEqual( s["n"]["user"]["c"].getValue(), 3 )

		with Gaffer.UndoContext( s ) :

			s["e"]["expression"].setValue( 'parent["n"]["user"]["c"] = 1; parent["n"]["user"]["b"] = 2; parent["n"]["user"]["a"] = 3' )

		self.assertEqual( s["n"]["user"]["a"].getValue(), 3 )
		self.assertEqual( s["n"]["user"]["b"].getValue(), 2 )
		self.assertEqual( s["n"]["user"]["c"].getValue(), 1 )

		s.undo()

		self.assertEqual( s["n"]["user"]["a"].getValue(), 1 )
		self.assertEqual( s["n"]["user"]["b"].getValue(), 2 )
		self.assertEqual( s["n"]["user"]["c"].getValue(), 3 )

		s.redo()

		self.assertEqual( s["n"]["user"]["a"].getValue(), 3 )
		self.assertEqual( s["n"]["user"]["b"].getValue(), 2 )
		self.assertEqual( s["n"]["user"]["c"].getValue(), 1 )