Ejemplo n.º 1
0
        public void TestCompiler()
        {
            var device = GraphicsDevice.New();

            // Compile a toolkit effect from a file
            var result = new EffectCompiler().CompileFromFile("TestEffectTextureArray.fx");

            // Check that we don't have any errors
            Assert.False(result.HasErrors);

            var bytecode = result.EffectData;

            var effect = new Effect(device, bytecode);

            var tex1 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var tex2 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var tex3 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var samplerState = device.SamplerStates.PointWrap;

            effect.Parameters["testTextureArray"].SetResource(0, tex1);
            effect.Parameters["testTextureArray"].SetResource(1, tex2);
            effect.Parameters["testTextureArray"].SetResource(2, tex3);

            //effect.Parameters["World"].SetValue(Vector3.Zero);
            //effect.Parameters["Tata"].SetResource(texture);

            effect.Techniques[0].Passes[0].Apply();

            effect.Techniques[0].Passes[1].Apply();

            Console.WriteLine(effect.Parameters.Count);

            effect.Dispose();
            device.Dispose();
        }
Ejemplo n.º 2
0
        public void TestShaderCompilation()
        {
            Init();

            var generics = new string[3];

            generics[0] = "Texturing.Texture1";
            generics[1] = "TEXCOORD0";
            generics[2] = "float4(2.0,1,1,1)";

            var compilerParameters = new CompilerParameters();

            compilerParameters.Set(EffectSourceCodeKeys.Enable, true);
            compilerParameters.EffectParameters.Profile = GraphicsProfile.Level_11_0;

            var mixinSource = new ShaderMixinSource {
                Name = "TestShaderCompilationGenericClass"
            };

            mixinSource.Mixins.Add(new ShaderClassSource("GenericClass2", generics));

            var log = new CompilerResults();

            var compiler = new EffectCompiler(TestHelper.CreateDatabaseProvider().FileProvider);

            compiler.SourceDirectories.Add("shaders");

            var effectByteCode = compiler.Compile(mixinSource, compilerParameters.EffectParameters, compilerParameters);
        }
Ejemplo n.º 3
0
        public void TestCompiler()
        {
            var device = GraphicsDevice.New();

            // Compile a toolkit effect from a file
            var result = new EffectCompiler().CompileFromFile("TestEffect.fx");

            // Check that we don't have any errors
            Assert.False(result.HasErrors);

            var bytecode = result.EffectData;

            // Check that we have a single effect compiled in this archive.
            Assert.AreEqual(bytecode.Effects.Count, 1);

            // Check that the name of this effect is the file name
            Assert.AreEqual(bytecode.Effects[0].Name, "TestEffect");

            // We have 3 shaders compiled: VS, VS2, PS
            Assert.AreEqual(bytecode.Shaders.Count, 3);

            // Check that this is the profile 10.0
            Assert.AreEqual(bytecode.Shaders[0].Level, FeatureLevel.Level_10_0);

            // Create a EffectData pool from a single EffectData
            var effectGroup = EffectPool.New(device);

            //var effect = effectGroup.New<BasicEffect>();
            var effect = new Effect(device, bytecode, effectGroup);

            //Texture2D tex : register(t0);
            //Texture2D tex1 : register(t2);
            //Texture2D tex2 : register(t3);
            //Texture2D tex3 : register(t10);
            //SamplerState samp;
            var tex = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var tex1 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var tex2 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var tex3 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var samplerState = device.SamplerStates.PointWrap;

            effect.Parameters["tex"].SetResource(tex);
            effect.Parameters["tex1"].SetResource(tex1);
            effect.Parameters["tex2"].SetResource(tex2);
            effect.Parameters["tex3"].SetResource(tex3);
            effect.Parameters["worldViewProj"].SetValue(Matrix.Identity);
            effect.Parameters["samp"].SetResource(samplerState);

            //effect.Parameters["World"].SetValue(Vector3.Zero);
            //effect.Parameters["Tata"].SetResource(texture);

            effect.Techniques[0].Passes[0].Apply();

            Console.WriteLine(effect.Parameters.Count);

            effect.Dispose();
            device.Dispose();
        }
Ejemplo n.º 4
0
        protected override void Initialize()
        {
            SetupD3DCompilerPath();

            compiler         = new EffectCompiler();
            parseLogMessages = true;

            base.Initialize();
        }
Ejemplo n.º 5
0
        private bool _isRebuildingAfterReset;            // on compilation error, we try to rebuild it again with the original data

        public ShaderBuilder(ShaderData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            _data           = data;
            _effectCompiler = new EffectCompiler();
        }
Ejemplo n.º 6
0
        public void TestCompiler()
        {
            var device = GraphicsDevice.New();

            // Compile a toolkit effect from a file
            var result = new EffectCompiler().CompileFromFile("TestEffect.fx");

            // Check that we don't have any errors
            Assert.False(result.HasErrors);

            var bytecode = result.EffectData;

            // Check that the name of this effect is the file name
            Assert.AreEqual(bytecode.Description.Name, "TestEffect");

            // We have 3 shaders compiled: VS, VS2, PS
            Assert.AreEqual(bytecode.Shaders.Count, 3);

            // Check that this is the profile 10.0
            Assert.AreEqual(bytecode.Shaders[0].Level, FeatureLevel.Level_10_0);

            // Create a EffectData pool from a single EffectData
            var effectGroup = EffectPool.New(device);

            //var effect = effectGroup.New<BasicEffect>();
            var effect = new Effect(device, bytecode, effectGroup);

            //Texture2D tex : register(t0);
            //Texture2D tex1 : register(t2);
            //Texture2D tex2 : register(t3);
            //Texture2D tex3 : register(t10);
            //SamplerState samp;
            var tex          = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var tex1         = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var tex2         = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var tex3         = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm);
            var samplerState = device.SamplerStates.PointWrap;

            effect.Parameters["tex"].SetResource(tex);
            effect.Parameters["tex1"].SetResource(tex1);
            effect.Parameters["tex2"].SetResource(tex2);
            effect.Parameters["tex3"].SetResource(tex3);
            effect.Parameters["worldViewProj"].SetValue(Matrix.Identity);
            effect.Parameters["samp"].SetResource(samplerState);

            //effect.Parameters["World"].SetValue(Vector3.Zero);
            //effect.Parameters["Tata"].SetResource(texture);

            effect.Techniques[0].Passes[0].Apply();

            Console.WriteLine(effect.Parameters.Count);

            effect.Dispose();
            device.Dispose();
        }
Ejemplo n.º 7
0
        protected override void InitializeCore()
        {
            base.InitializeCore();

            // Setup our own effect compiler
            using var fileProvider = new InMemoryFileProvider(EffectSystem.FileProvider);
            fileProvider.Register("shaders/WebRendererShader.sdsl", GetShaderSource());
            using var compiler = new EffectCompiler(fileProvider);
            compiler.SourceDirectories.Add("shaders");

            // Switch effect compiler
            var currentCompiler = EffectSystem.Compiler;

            EffectSystem.Compiler = compiler;
            try
            {
                shader = ToLoadAndUnload(new ImageEffectShader("WebRendererShader"));
                // The incoming texture uses premultiplied alpha
                shader.BlendState = BlendStates.AlphaBlend;
                shader.EffectInstance.UpdateEffect(GraphicsDevice);
            }
            finally
            {
                EffectSystem.Compiler = currentCompiler;
            }

            string GetShaderSource()
            {
                return(@"
shader WebRendererShader : ImageEffectShader
{
stage override float4 Shading()
{
    float2 samplePosition = float2(streams.TexCoord.x, 1 - streams.TexCoord.y);
    float4 color = Texture0.Sample(PointSampler, samplePosition);

    // The render pipeline expects a linear color space
    return float4(ToLinear(color.r), ToLinear(color.g), ToLinear(color.b), color.a);
}

// There're faster approximations, see http://chilliant.blogspot.com/2012/08/srgb-approximations-for-hlsl.html
float ToLinear(float C_srgb)
{
    if (C_srgb <= 0.04045)
        return C_srgb / 12.92;
    else
        return pow((C_srgb + 0.055) / 1.055, 2.4);
}
};
");
            }
        }
Ejemplo n.º 8
0
        private void Init()
        {
            // Create and mount database file system
            var objDatabase          = ObjectDatabase.CreateDefaultDatabase();
            var databaseFileProvider = new DatabaseFileProvider(objDatabase);

            Compiler = new EffectCompiler(databaseFileProvider);
            Compiler.SourceDirectories.Add("shaders");
            MixinParameters = new CompilerParameters();
            MixinParameters.EffectParameters.Platform = GraphicsPlatform.Direct3D11;
            MixinParameters.EffectParameters.Profile  = GraphicsProfile.Level_11_0;
            ResultLogger = new LoggerResult();
        }
Ejemplo n.º 9
0
        public void Init()
        {
            // Create and mount database file system
            var objDatabase          = new ObjectDatabase("/data/db", "index", "/local/db");
            var databaseFileProvider = new DatabaseFileProvider(objDatabase);

            AssetManager.GetFileProvider = () => databaseFileProvider;

            Compiler = new EffectCompiler();
            Compiler.SourceDirectories.Add("shaders");
            MixinParameters = new ShaderMixinParameters();
            MixinParameters.Add(CompilerParameters.GraphicsPlatformKey, GraphicsPlatform.Direct3D11);
            MixinParameters.Add(CompilerParameters.GraphicsProfileKey, GraphicsProfile.Level_11_0);
            ResultLogger = new LoggerResult();
        }
Ejemplo n.º 10
0
        public static void Main()
        {
            using (var profile = Profiler.Begin(GameProfilingKeys.ObjectDatabaseInitialize))
            {
                // Create and mount database file system
                var objDatabase          = new ObjectDatabase("/data/db");
                var assetIndexMap        = AssetIndexMap.Load();
                var databaseFileProvider = new DatabaseFileProvider(assetIndexMap, objDatabase);
                AssetManager.GetFileProvider = () => databaseFileProvider;
            }

            compiler = new EffectCompiler();
            compiler.SourceDirectories.Add("shaders");
            var shaderMixinSource = new ShaderMixinSource();

            shaderMixinSource.Mixins.Add(new ShaderClassSource("ShaderBase"));
            shaderMixinSource.Mixins.Add(new ShaderClassSource("TransformationWVP"));
            shaderMixinSource.Mixins.Add(new ShaderClassSource("ShadingBase"));

            var shaderMixinSource2 = new ShaderMixinSource();

            shaderMixinSource2.Mixins.Add(new ShaderClassSource("ShaderBase"));
            shaderMixinSource2.Mixins.Add(new ShaderClassSource("TransformationWVP"));
            shaderMixinSource2.Mixins.Add(new ShaderClassSource("ShadingBase"));
            shaderMixinSource2.Mixins.Add(new ShaderClassSource("ShadingOverlay"));

            var allThreads = new List <Thread>();

            for (int i = 0; i < NumThreads; ++i)
            {
                CompilerThread compilerThread;
                if (i % 2 == 0)
                {
                    compilerThread = new CompilerThread(compiler, shaderMixinSource);
                }
                else
                {
                    compilerThread = new CompilerThread(compiler, shaderMixinSource2);
                }
                allThreads.Add(new Thread(compilerThread.Compile));
            }

            foreach (var thread in allThreads)
            {
                thread.Start();
            }
        }
Ejemplo n.º 11
0
        public void TestMixinAndComposeKeys()
        {
            var compiler = new EffectCompiler(TestHelper.CreateDatabaseProvider().FileProvider)
            {
                UseFileSystem = true
            };
            var currentPath = Core.PlatformFolders.ApplicationBinaryDirectory;

            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\Stride.Graphics\Shaders"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\Stride.Shaders.Tests\GameAssets\Mixins"));

            var compilerParameters = new CompilerParameters {
                EffectParameters = { Platform = GraphicsPlatform.Direct3D11 }
            };

            var subCompute1Key = TestABC.TestParameters.UseComputeColor2.ComposeWith("SubCompute1");
            var subCompute2Key = TestABC.TestParameters.UseComputeColor2.ComposeWith("SubCompute2");
            var subComputesKey = TestABC.TestParameters.UseComputeColorRedirect.ComposeWith("SubComputes[0]");

            compilerParameters.Set(subCompute1Key, true);
            compilerParameters.Set(subComputesKey, true);

            var results = compiler.Compile(new ShaderMixinGeneratorSource("test_mixin_compose_keys"), compilerParameters);

            Assert.False(results.HasErrors);

            var mainBytecode = results.Bytecode.WaitForResult();

            Assert.False(mainBytecode.CompilationLog.HasErrors);

            Assert.NotNull(mainBytecode.Bytecode.Reflection.ConstantBuffers);
            Assert.Single(mainBytecode.Bytecode.Reflection.ConstantBuffers);
            var cbuffer = mainBytecode.Bytecode.Reflection.ConstantBuffers[0];

            Assert.NotNull(cbuffer.Members);
            Assert.Equal(2, cbuffer.Members.Length);


            // Check that ComputeColor2.Color is correctly composed for variables
            var computeColorSubCompute2 = ComputeColor2Keys.Color.ComposeWith("SubCompute1");
            var computeColorSubComputes = ComputeColor2Keys.Color.ComposeWith("ColorRedirect.SubComputes[0]");

            var members = cbuffer.Members.Select(member => member.KeyInfo.KeyName).ToList();

            Assert.Contains(computeColorSubCompute2.Name, members);
            Assert.Contains(computeColorSubComputes.Name, members);
        }
Ejemplo n.º 12
0
        public void TestSimple()
        {
            VirtualFileSystem.RemountFileSystem("/shaders", "../../../../shaders");
            VirtualFileSystem.RemountFileSystem("/compiler", "Compiler");


            var compiler = new EffectCompiler();

            compiler.SourceDirectories.Add("shaders");
            compiler.SourceDirectories.Add("compiler");

            var compilerParameters = new CompilerParameters {
                Platform = GraphicsPlatform.Direct3D11
            };

            var results = compiler.Compile(new ShaderMixinGeneratorSource("SimpleEffect"), compilerParameters, null, null);
        }
Ejemplo n.º 13
0
        protected override void LoadContent()
        {
            // Importer for many models
            var importer = new AssimpImporter();

            // Load a specific model
            //string fileName = System.IO.Path.GetFullPath(Content.RootDirectory + "/tower.3ds");
            //Scene scene = importer.ImportFile(fileName, PostProcessSteps.MakeLeftHanded);
            //m_model = new Model(scene, GraphicsDevice, Content);

            // Load shader
            EffectCompilerFlags compilerFlags = EffectCompilerFlags.None;
            EffectCompiler      compiler      = new EffectCompiler();

#if DEBUG
            compilerFlags |= EffectCompilerFlags.Debug;
#endif
            var simpleShaderCompileResult = compiler.CompileFromFile(Content.RootDirectory + "/pointlight.fx", compilerFlags);
            if (simpleShaderCompileResult.HasErrors)
            {
                System.Console.WriteLine(simpleShaderCompileResult.Logger.Messages);
                System.Diagnostics.Debugger.Break();
            }
            m_simpleEffect = new SharpDX.Toolkit.Graphics.Effect(GraphicsDevice, simpleShaderCompileResult.EffectData);
            m_simpleEffect.Parameters["diffuseSampler"].SetResource(m_linearSamplerState);
            base.LoadContent();

            map = new Map(@"Content\map.PNG", new Size2(20, 20));
            map.LoadContent(GraphicsDevice, Content);

            player     = new Player(new Vector3(0.0f, 10.0f, 0.0f), GraphicsDevice);
            player.Map = map;

            spritebatch = new SpriteBatch(GraphicsDevice, 2048);



            compass       = Content.Load <Texture2D>("compass.png");
            torch         = Content.Load <Texture2D>("torchPlaceholder.png");
            compassNeedle = Content.Load <Texture2D>("needle.png");
            particle      = Content.Load <Texture2D>("particle.png");

            gameOver = Content.Load <Texture2D>("gameover.png");

            emitter.position = new Vector2(width - torch.Width / 3, height - torch.Height / 3);
        }
        public static void Main3()
        {
            // Create and mount database file system
            var objDatabase          = ObjectDatabase.CreateDefaultDatabase();
            var assetIndexMap        = ContentIndexMap.Load(VirtualFileSystem.ApplicationDatabaseIndexPath);
            var databaseFileProvider = new DatabaseFileProvider(assetIndexMap, objDatabase);

            ContentManager.GetFileProvider = () => databaseFileProvider;

            compiler = new EffectCompiler();
            compiler.SourceDirectories.Add("shaders");
            var shaderMixinSource = new ShaderMixinSource();

            shaderMixinSource.Mixins.Add(new ShaderClassSource("ShaderBase"));
            shaderMixinSource.Mixins.Add(new ShaderClassSource("TransformationWVP"));
            shaderMixinSource.Mixins.Add(new ShaderClassSource("ShadingBase"));

            var shaderMixinSource2 = new ShaderMixinSource();

            shaderMixinSource2.Mixins.Add(new ShaderClassSource("ShaderBase"));
            shaderMixinSource2.Mixins.Add(new ShaderClassSource("TransformationWVP"));
            shaderMixinSource2.Mixins.Add(new ShaderClassSource("ShadingBase"));
            shaderMixinSource2.Mixins.Add(new ShaderClassSource("ShadingOverlay"));

            var allThreads = new List <Thread>();

            for (int i = 0; i < NumThreads; ++i)
            {
                CompilerThread compilerThread;
                if (i % 2 == 0)
                {
                    compilerThread = new CompilerThread(compiler, shaderMixinSource);
                }
                else
                {
                    compilerThread = new CompilerThread(compiler, shaderMixinSource2);
                }
                allThreads.Add(new Thread(compilerThread.Compile));
            }

            foreach (var thread in allThreads)
            {
                thread.Start();
            }
        }
Ejemplo n.º 15
0
        public void TestMixinAndComposeKeys()
        {
            var compiler = new EffectCompiler {
                UseFileSystem = true
            };

            compiler.SourceDirectories.Add(@"..\..\sources\engine\SiliconStudio.Paradox.Graphics\Shaders");
            compiler.SourceDirectories.Add(@"..\..\sources\engine\SiliconStudio.Paradox.Shaders.Tests\GameAssets\Mixins");

            var compilerParameters = new CompilerParameters {
                Platform = GraphicsPlatform.Direct3D11
            };

            var subCompute1Key = TestABC.TestParameters.UseComputeColor2.ComposeWith("SubCompute1");
            var subCompute2Key = TestABC.TestParameters.UseComputeColor2.ComposeWith("SubCompute2");
            var subComputesKey = TestABC.TestParameters.UseComputeColorRedirect.ComposeWith("SubComputes[0]");

            compilerParameters.Set(subCompute1Key, true);
            compilerParameters.Set(subComputesKey, true);

            var results = compiler.Compile(new ShaderMixinGeneratorSource("test_mixin_compose_keys"), compilerParameters);

            Assert.IsFalse(results.HasErrors);

            var mainBytecode = results.Bytecode.WaitForResult();

            Assert.IsFalse(mainBytecode.CompilationLog.HasErrors);

            Assert.NotNull(mainBytecode.Bytecode.Reflection.ConstantBuffers);
            Assert.AreEqual(1, mainBytecode.Bytecode.Reflection.ConstantBuffers.Count);
            var cbuffer = mainBytecode.Bytecode.Reflection.ConstantBuffers[0];

            Assert.NotNull(cbuffer.Members);
            Assert.AreEqual(2, cbuffer.Members.Length);


            // Check that ComputeColor2.Color is correctly composed for variables
            var computeColorSubCompute2 = ComputeColor2Keys.Color.ComposeWith("SubCompute1");
            var computeColorSubComputes = ComputeColor2Keys.Color.ComposeWith("ColorRedirect.SubComputes[0]");

            var members = cbuffer.Members.Select(member => member.Param.KeyName).ToList();

            Assert.IsTrue(members.Contains(computeColorSubCompute2.Name));
            Assert.IsTrue(members.Contains(computeColorSubComputes.Name));
        }
Ejemplo n.º 16
0
        public void TestGlslESCompiler()
        {
            VirtualFileSystem.RemountFileSystem("/shaders", "../../../../shaders");
            VirtualFileSystem.RemountFileSystem("/baseShaders", "../../../../engine/Stride.Graphics/Shaders");
            VirtualFileSystem.RemountFileSystem("/compiler", "Compiler");

            var compiler = new EffectCompiler(TestHelper.CreateDatabaseProvider().FileProvider);

            compiler.SourceDirectories.Add("shaders");
            compiler.SourceDirectories.Add("compiler");
            compiler.SourceDirectories.Add("baseShaders");

            var compilerParameters = new CompilerParameters {
                EffectParameters = { Platform = GraphicsPlatform.OpenGLES }
            };

            var results = compiler.Compile(new ShaderMixinGeneratorSource("ToGlslEffect"), compilerParameters);
        }
Ejemplo n.º 17
0
        public void TestGlslESCompiler()
        {
            VirtualFileSystem.RemountFileSystem("/shaders", "../../../../shaders");
            VirtualFileSystem.RemountFileSystem("/baseShaders", "../../../../engine/SiliconStudio.Paradox.Graphics/Shaders");
            VirtualFileSystem.RemountFileSystem("/compiler", "Compiler");

            var compiler = new EffectCompiler();

            compiler.SourceDirectories.Add("shaders");
            compiler.SourceDirectories.Add("compiler");
            compiler.SourceDirectories.Add("baseShaders");

            var compilerParameters = new CompilerParameters {
                Platform = GraphicsPlatform.OpenGLES
            };

            var results = compiler.Compile(new ShaderMixinGeneratorSource("ToGlslEffect"), compilerParameters);
        }
Ejemplo n.º 18
0
        //  DepthStencilState _depthStencilDrawWhereNothing;

        public Background(GraphicsDevice graphicsDevice)
        {
            /*       var depthStencilStateDesc = SharpDX.Direct3D11.DepthStencilStateDescription.Default();
             *     depthStencilStateDesc.IsDepthEnabled = false;
             *     depthStencilStateDesc.DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.Zero;
             *     _noDepthState = DepthStencilState.New(graphicsDevice, "NoZBuffer", depthStencilStateDesc);*/

            EffectCompilerFlags compilerFlags = EffectCompilerFlags.None;

#if DEBUG
            compilerFlags |= EffectCompilerFlags.Debug;
#endif
            var shaderCompileResult = EffectCompiler.CompileFromFile("Content/sky.fx", compilerFlags);
            if (shaderCompileResult.HasErrors)
            {
                System.Console.WriteLine(shaderCompileResult.Logger.Messages);
                System.Diagnostics.Debugger.Break();
            }
            _effect = new SharpDX.Toolkit.Graphics.Effect(graphicsDevice, shaderCompileResult.EffectData);
        }
Ejemplo n.º 19
0
        public void RunTest()
        {
            // TODO: extend test with possible/impossible reduction cases
            var materialUrl    = "materials/testEffect.pdxmat";
            var materialAsset  = AssetSerializer.Load <MaterialAsset>(materialUrl);
            var material       = materialAsset.Material;
            var graphicsDevice = GraphicsDevice.New(DeviceCreationFlags.None, GraphicsProfile.Level_11_0);
            var solver         = new MaterialTextureLayerFlattener(material, graphicsDevice);

            solver.PrepareForFlattening();
            var compiler = new EffectCompiler();

            compiler.SourceDirectories.Add("shaders");
            solver.Run(compiler);

            // diffuse was reduced
            Assert.AreEqual("diffuse", solver.Material.ColorNodes[MaterialParameters.AlbedoDiffuse]);
            var node = solver.Material.Nodes["diffuse"];

            Assert.NotNull(node);
            var textureNode = solver.Material.Nodes["diffuse"] as MaterialTextureNode;

            Assert.NotNull(textureNode);
            Assert.IsTrue(textureNode.TextureName.StartsWith("__reduced_textures__"));

            // specular was reduced
            Assert.AreEqual("specular", solver.Material.ColorNodes[MaterialParameters.AlbedoSpecular]);
            node = solver.Material.Nodes["specular"];
            Assert.NotNull(node);
            textureNode = solver.Material.Nodes["specular"] as MaterialTextureNode;
            Assert.NotNull(textureNode);
            Assert.IsTrue(textureNode.TextureName.StartsWith("__reduced_textures__"));

            // normalMap wasn't reduced
            Assert.AreEqual("normalMap", solver.Material.ColorNodes[MaterialParameters.NormalMap]);
            node = solver.Material.Nodes["normalMap"];
            Assert.IsFalse(solver.Material.Nodes["normalMap"] is MaterialTextureNode);

            graphicsDevice.Dispose();
        }
Ejemplo n.º 20
0
        private static Effect LoadEffect(string name)
        {
            EffectCompilerResult result = EffectCompiler.CompileFromFile(_path + "\\Editor\\" + name + ".fx");

            if (result.HasErrors)
            {
                string errors = "";

                foreach (SharpDX.Toolkit.Diagnostics.LogMessage err in result.Logger.Messages)
                {
                    errors += err + Environment.NewLine;
                }

                LogManager.GetCurrentClassLogger().Log(LogLevel.Error, "Could not compile effect '" + name + ".fx'");
                MessageBox.Show("Could not compile effect '" + name + ".fx'" + Environment.NewLine + errors, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }

            Effect effect = new Effect(GraphicsDevice, result.EffectData);

            return(effect);
        }
Ejemplo n.º 21
0
        public void TestShaderCompilation()
        {
            var generics = new string[3];

            generics[0] = "Texturing.Texture1";
            generics[1] = "TEXCOORD0";
            generics[2] = "float4(2.0,1,1,1)";

            var mixinSource = new ShaderMixinSource();

            mixinSource.Mixins.Add(new ShaderClassSource("GenericClass2", generics));

            var compilerParameters = new ShaderMixinParameters();

            compilerParameters.Set(EffectSourceCodeKeys.Enable, true);
            compilerParameters.Set(CompilerParameters.GraphicsProfileKey, GraphicsProfile.Level_11_0);

            var log = new CompilerResults();

            var compiler = new EffectCompiler();

            compiler.SourceDirectories.Add("shaders");
            var effectByteCode = compiler.Compile(mixinSource, "TestShaderCompilationGenericClass", compilerParameters, null, null, log);
        }
Ejemplo n.º 22
0
        public void TestMatrix()
        {
            var device = GraphicsDevice.New();

            // Compile a toolkit effect from a file
            var result = new EffectCompiler().CompileFromFile("TestEffectValueArray.fx");

            // Check that we don't have any errors
            Assert.False(result.HasErrors);

            var bytecode = result.EffectData;

            var effect = new Effect(device, bytecode);


            var matrices = new Matrix[4];

            for (int i = 0; i < matrices.Length; i++)
            {
                matrices[i] = new Matrix();
                for (int j = 0; j < 16; j++)
                {
                    matrices[i][j] = (j + i * 16);
                }
            }

            effect.Parameters["Matrices4x4"].SetValue(matrices);
            effect.Parameters["Matrices4x3"].SetValue(matrices);
            effect.Parameters["Matrices3x3"].SetValue(matrices);
            effect.Parameters["Matrices3x4"].SetValue(matrices);

            var locals4x4 = effect.Parameters["Matrices4x4"].GetMatrixArray(4);
            var locals4x3 = effect.Parameters["Matrices4x3"].GetMatrixArray(4);
            var locals3x3 = effect.Parameters["Matrices3x3"].GetMatrixArray(4);
            var locals3x4 = effect.Parameters["Matrices3x4"].GetMatrixArray(4);

            Assert.That(CompareMatrixArray(matrices, locals4x4, 4, 4), Is.True);
            Assert.That(CompareMatrixArray(matrices, locals4x3, 4, 3), Is.True);
            Assert.That(CompareMatrixArray(matrices, locals3x3, 3, 3), Is.True);
            Assert.That(CompareMatrixArray(matrices, locals3x4, 3, 4), Is.True);

            var local4x4 = effect.Parameters["Matrices4x4"].GetMatrix(3);
            var local4x3 = effect.Parameters["Matrices4x3"].GetMatrix(3);
            var local3x3 = effect.Parameters["Matrices3x3"].GetMatrix(3);
            var local3x4 = effect.Parameters["Matrices3x4"].GetMatrix(3);

            Assert.That(CompareMatrix(ref local4x4, ref matrices[3], 4, 4));
            Assert.That(CompareMatrix(ref local4x3, ref matrices[3], 4, 3));
            Assert.That(CompareMatrix(ref local3x3, ref matrices[3], 3, 3));
            Assert.That(CompareMatrix(ref local3x4, ref matrices[3], 3, 4));

            var buffer = Buffer.Structured.New <Matrix>(device, 4, true);

            effect.Parameters["MatrixOut"].SetResource(buffer);

            effect.CurrentTechnique = effect.Techniques["TestMatrices"];

            effect.CurrentTechnique.Passes[0].Apply();
            device.Dispatch(4, 1, 1);
            var compute4x4 = Transpose(buffer.GetData <Matrix>());

            Assert.That(CompareMatrixArray(matrices, compute4x4, 4, 4), Is.True);

            effect.CurrentTechnique.Passes[1].Apply();
            device.Dispatch(4, 1, 1);
            var compute4x3 = Transpose(buffer.GetData <Matrix>());

            Assert.That(CompareMatrixArray(matrices, compute4x3, 4, 3), Is.True);

            effect.CurrentTechnique.Passes[2].Apply();
            device.Dispatch(4, 1, 1);
            var compute3x3 = Transpose(buffer.GetData <Matrix>());

            Assert.That(CompareMatrixArray(matrices, compute3x3, 3, 3), Is.True);

            effect.CurrentTechnique.Passes[3].Apply();
            device.Dispatch(4, 1, 1);
            var compute3x4 = Transpose(buffer.GetData <Matrix>());

            Assert.That(CompareMatrixArray(matrices, compute3x4, 3, 4), Is.True);

            effect.Dispose();
            device.Dispose();
        }
Ejemplo n.º 23
0
        /// <inheritdoc/>
        protected override async void HandleClient(SimpleSocket clientSocket, string url)
        {
            string[] urlSegments;
            string   urlParameters;

            RouterHelper.ParseUrl(url, out urlSegments, out urlParameters);
            var parameters = RouterHelper.ParseQueryString(urlParameters);
            var mode       = parameters["mode"];

            // We accept everything
            await AcceptConnection(clientSocket);

            var socketMessageLayer = new SocketMessageLayer(clientSocket, true);

            Guid?packageId = null;

            {
                Guid packageIdParsed;
                if (Guid.TryParse(parameters["packageid"], out packageIdParsed))
                {
                    packageId = packageIdParsed;
                }
            }

            if (mode == "gamestudio")
            {
                Console.WriteLine(@"GameStudio mode started!");

                if (!packageId.HasValue)
                {
                    return;
                }

                lock (gameStudioPerPackageId)
                {
                    gameStudioPerPackageId[packageId.Value] = socketMessageLayer;
                }
            }
            else
            {
                // Create an effect compiler per connection
                var effectCompiler = new EffectCompiler();

                Console.WriteLine(@"Client connected");

                // TODO: This should come from an "init" packet
                effectCompiler.SourceDirectories.Add(EffectCompilerBase.DefaultSourceShaderFolder);

                // Make a VFS that will access remotely the DatabaseFileProvider
                // TODO: Is that how we really want to do that in the future?
                var networkVFS = new NetworkVirtualFileProvider(socketMessageLayer, "/asset");
                VirtualFileSystem.RegisterProvider(networkVFS);
                effectCompiler.FileProvider = networkVFS;

                socketMessageLayer.AddPacketHandler <RemoteEffectCompilerEffectRequest>(packet => ShaderCompilerRequestHandler(socketMessageLayer, effectCompiler, packet));

                socketMessageLayer.AddPacketHandler <RemoteEffectCompilerEffectRequested>(packet =>
                {
                    if (!packageId.HasValue)
                    {
                        return;
                    }

                    SocketMessageLayer gameStudio;
                    lock (gameStudioPerPackageId)
                    {
                        if (!gameStudioPerPackageId.TryGetValue(packageId.Value, out gameStudio))
                        {
                            return;
                        }
                    }

                    // Forward to game studio
                    gameStudio.Send(packet);
                });
            }

            Task.Run(() => socketMessageLayer.MessageLoop());
        }
Ejemplo n.º 24
0
        private static async Task ShaderCompilerRequestHandler(SocketMessageLayer socketMessageLayer, EffectCompiler effectCompiler, RemoteEffectCompilerEffectRequest remoteEffectCompilerEffectRequest)
        {
            // Yield so that this socket can continue its message loop to answer to shader file request
            // TODO: maybe not necessary anymore with RouterServiceServer?
            await Task.Yield();

            Console.WriteLine($"Compiling shader: {remoteEffectCompilerEffectRequest.MixinTree.Name}");

            // A shader has been requested, compile it (asynchronously)!
            var precompiledEffectShaderPass = await effectCompiler.Compile(remoteEffectCompilerEffectRequest.MixinTree, remoteEffectCompilerEffectRequest.EffectParameters, null).AwaitResult();

            // Send compiled shader
            await socketMessageLayer.Send(new RemoteEffectCompilerEffectAnswer { StreamId = remoteEffectCompilerEffectRequest.StreamId, EffectBytecode = precompiledEffectShaderPass.Bytecode });
        }
 public CompilerThread(EffectCompiler compiler, ShaderMixinSource source)
 {
     effectCompiler = compiler;
     mixinSource    = source;
 }
Ejemplo n.º 26
0
        private async void ShaderCompilerRequestHandler(SocketContext clientSocketContext, EffectLogStore recordedEffectCompile, EffectCompiler effectCompiler, ShaderCompilerRequest shaderCompilerRequest)
        {
            // Wait for a client to be connected
            await clientConnectedTCS.Task;

            // Yield so that this socket can continue its message loop to answer to shader file request.
            await Task.Yield();

            Console.WriteLine("Compiling shader");

            // A shader has been requested, compile it (asynchronously)!
            var precompiledEffectShaderPass = await effectCompiler.Compile(shaderCompilerRequest.MixinTree, null).AwaitResult();

            // Record compilation to asset file (only if parent)
            recordedEffectCompile[new EffectCompileRequest(shaderCompilerRequest.MixinTree.Name, shaderCompilerRequest.MixinTree.UsedParameters)] = true;

            // Send compiled shader
            clientSocketContext.Send(new ShaderCompilerAnswer {
                StreamId = shaderCompilerRequest.StreamId, EffectBytecode = precompiledEffectShaderPass.Bytecode
            });
        }
Ejemplo n.º 27
0
        private static async Task ShaderCompilerRequestHandler(SocketMessageLayer socketMessageLayer, EffectLogStore recordedEffectCompile, EffectCompiler effectCompiler, RemoteEffectCompilerEffectRequest remoteEffectCompilerEffectRequest)
        {
            // Yield so that this socket can continue its message loop to answer to shader file request
            // TODO: maybe not necessary anymore with RouterServiceServer?
            await Task.Yield();

            Console.WriteLine("Compiling shader");

            // Restore MixinTree.UsedParameters (since it is DataMemberIgnore)
            remoteEffectCompilerEffectRequest.MixinTree.UsedParameters = remoteEffectCompilerEffectRequest.UsedParameters;

            // A shader has been requested, compile it (asynchronously)!
            var precompiledEffectShaderPass = await effectCompiler.Compile(remoteEffectCompilerEffectRequest.MixinTree, null).AwaitResult();

            // Record compilation to asset file (only if parent)
            recordedEffectCompile[new EffectCompileRequest(remoteEffectCompilerEffectRequest.MixinTree.Name, remoteEffectCompilerEffectRequest.MixinTree.UsedParameters)] = true;

            // Send compiled shader
            socketMessageLayer.Send(new RemoteEffectCompilerEffectAnswer {
                StreamId = remoteEffectCompilerEffectRequest.StreamId, EffectBytecode = precompiledEffectShaderPass.Bytecode
            });
        }
Ejemplo n.º 28
0
        public void TestMaterial()
        {
            var compiler = new EffectCompiler {
                UseFileSystem = true
            };
            var currentPath = Core.PlatformFolders.ApplicationBinaryDirectory;

            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Graphics\Shaders"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Shaders"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Core"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Lights"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Shadows"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Materials\Shaders"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Materials\ComputeColors\Shaders"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Skinning"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Shading"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Transformation"));
            compiler.SourceDirectories.Add(Path.Combine(currentPath, @"..\..\sources\engine\SiliconStudio.Xenko.Engine\Rendering\Utils"));
            var compilerParameters = new CompilerParameters {
                EffectParameters = { Platform = GraphicsPlatform.OpenGL }
            };

            var layers = new MaterialBlendLayers();

            layers.Add(new MaterialBlendLayer
            {
                BlendMap = new ComputeFloat(0.5f),
                Material = AttachedReferenceManager.CreateProxyObject <Material>(AssetId.Empty, "fake")
            });

            var materialAsset = new MaterialAsset
            {
                Attributes = new MaterialAttributes()
                {
                    Diffuse = new MaterialDiffuseMapFeature()
                    {
                        DiffuseMap = new ComputeColor(Color4.White)
                    },
                    DiffuseModel = new MaterialDiffuseLambertModelFeature()
                },
                Layers = layers
            };

            var fakeAsset = new MaterialAsset
            {
                Attributes = new MaterialAttributes()
                {
                    Diffuse = new MaterialDiffuseMapFeature()
                    {
                        DiffuseMap = new ComputeColor(Color.Blue)
                    },
                }
            };

            var context = new MaterialGeneratorContext {
                FindAsset = reference => fakeAsset
            };
            var result = MaterialGenerator.Generate(new MaterialDescriptor {
                Attributes = materialAsset.Attributes, Layers = materialAsset.Layers
            }, context, "TestMaterial");

            compilerParameters.Set(MaterialKeys.PixelStageSurfaceShaders, result.Material.Parameters.Get(MaterialKeys.PixelStageSurfaceShaders));
            var directionalLightGroup = new ShaderClassSource("LightDirectionalGroup", 1);

            compilerParameters.Set(LightingKeys.DirectLightGroups, new ShaderSourceCollection {
                directionalLightGroup
            });
            //compilerParameters.Set(LightingKeys.CastShadows, false);
            //compilerParameters.Set(MaterialParameters.HasSkinningPosition, true);
            //compilerParameters.Set(MaterialParameters.HasSkinningNormal, true);
            compilerParameters.Set(MaterialKeys.HasNormalMap, true);

            var results = compiler.Compile(new ShaderMixinGeneratorSource("XenkoEffectBase"), compilerParameters);

            Assert.IsFalse(results.HasErrors);
        }
Ejemplo n.º 29
0
        public void TestMatrix()
        {
            var device = GraphicsDevice.New();

            // Compile a toolkit effect from a file
            var result = new EffectCompiler().CompileFromFile("TestEffectValueArray.fx");

            // Check that we don't have any errors
            Assert.False(result.HasErrors);

            var bytecode = result.EffectData;

            var effect = new Effect(device, bytecode);

            
            var matrices = new Matrix[4];
            for (int i = 0; i < matrices.Length; i++)
            {
                matrices[i] = new Matrix();
                for (int j = 0; j < 16; j++)
                {
                    matrices[i][j] = (j + i * 16);
                }
            }

            effect.Parameters["Matrices4x4"].SetValue(matrices);
            effect.Parameters["Matrices4x3"].SetValue(matrices);
            effect.Parameters["Matrices3x3"].SetValue(matrices);
            effect.Parameters["Matrices3x4"].SetValue(matrices);

            var locals4x4 = effect.Parameters["Matrices4x4"].GetMatrixArray(4);
            var locals4x3 = effect.Parameters["Matrices4x3"].GetMatrixArray(4);
            var locals3x3 = effect.Parameters["Matrices3x3"].GetMatrixArray(4);
            var locals3x4 = effect.Parameters["Matrices3x4"].GetMatrixArray(4);

            Assert.That(CompareMatrixArray(matrices, locals4x4, 4, 4), Is.True);
            Assert.That(CompareMatrixArray(matrices, locals4x3, 4, 3), Is.True);
            Assert.That(CompareMatrixArray(matrices, locals3x3, 3, 3), Is.True);
            Assert.That(CompareMatrixArray(matrices, locals3x4, 3, 4), Is.True);

            var local4x4 = effect.Parameters["Matrices4x4"].GetMatrix(3);
            var local4x3 = effect.Parameters["Matrices4x3"].GetMatrix(3);
            var local3x3 = effect.Parameters["Matrices3x3"].GetMatrix(3);
            var local3x4 = effect.Parameters["Matrices3x4"].GetMatrix(3);

            Assert.That(CompareMatrix(ref local4x4, ref matrices[3], 4, 4));
            Assert.That(CompareMatrix(ref local4x3, ref matrices[3], 4, 3));
            Assert.That(CompareMatrix(ref local3x3, ref matrices[3], 3, 3));
            Assert.That(CompareMatrix(ref local3x4, ref matrices[3], 3, 4));

            var buffer = Buffer.Structured.New<Matrix>(device, 4, true);
            effect.Parameters["MatrixOut"].SetResource(buffer);

            effect.CurrentTechnique = effect.Techniques["TestMatrices"];

            effect.CurrentTechnique.Passes[0].Apply();
            device.Dispatch(4, 1, 1);
            var compute4x4 = Transpose(buffer.GetData<Matrix>());
            Assert.That(CompareMatrixArray(matrices, compute4x4, 4, 4), Is.True);

            effect.CurrentTechnique.Passes[1].Apply();
            device.Dispatch(4, 1, 1);
            var compute4x3 = Transpose(buffer.GetData<Matrix>());
            Assert.That(CompareMatrixArray(matrices, compute4x3, 4, 3), Is.True);

            effect.CurrentTechnique.Passes[2].Apply();
            device.Dispatch(4, 1, 1);
            var compute3x3 = Transpose(buffer.GetData<Matrix>());
            Assert.That(CompareMatrixArray(matrices, compute3x3, 3, 3), Is.True);

            effect.CurrentTechnique.Passes[3].Apply();
            device.Dispatch(4, 1, 1);
            var compute3x4 = Transpose(buffer.GetData<Matrix>());
            Assert.That(CompareMatrixArray(matrices, compute3x4, 3, 4), Is.True);

            effect.Dispose();
            device.Dispose();
        }
Ejemplo n.º 30
0
        public void TestFloats()
        {
            var device = GraphicsDevice.New();

            // Compile a toolkit effect from a file
            var result = new EffectCompiler().CompileFromFile("TestEffectValueArray.fx");

            // Check that we don't have any errors
            Assert.False(result.HasErrors);

            var bytecode = result.EffectData;

            var effect = new Effect(device, bytecode);

            // Test for floats
            // When uploading a float[16], each float in the array will be aligned to the closest float4
            // So it is actually as using a float4[16] array. The toolkit is managing this to avoid a
            // user to have to remap to a float4. For efficiency, It is recommended to directly use float4
            // whenever possible.
            var floats = new float[16];

            for (int i = 0; i < floats.Length; i++)
            {
                floats[i] = i;
            }
            effect.Parameters["Floats"].SetValue(floats);
            var localFloats = effect.Parameters["Floats"].GetValueArray <float>(floats.Length);

            Assert.That(Utilities.Compare(floats, localFloats), Is.True);

            var buffer = Buffer.Structured.New <float>(device, floats.Length, true);

            effect.Parameters["FloatsOut"].SetResource(buffer);

            effect.CurrentTechnique = effect.Techniques["TestFloats"];

            effect.CurrentTechnique.Passes[0].Apply();
            device.Dispatch(floats.Length, 1, 1);
            var computeFloats = buffer.GetData <float>();

            Assert.That(Utilities.Compare(floats, computeFloats), Is.True);

            // Test with float2 array
            var floats2 = new Vector2[8];

            for (int i = 0; i < floats2.Length; i++)
            {
                floats2[i] = new Vector2(i * 2, i * 2 + 1);
            }
            effect.Parameters["Floats2"].SetValue(floats2);

            var localFloats2 = effect.Parameters["Floats2"].GetValueArray <Vector2>(floats2.Length);

            Assert.That(Utilities.Compare(floats2, localFloats2), Is.True);

            var bufferFloats2 = Buffer.Structured.New <Vector2>(device, floats2.Length, true);

            effect.Parameters["Floats2Out"].SetResource(bufferFloats2);

            effect.CurrentTechnique.Passes[1].Apply();
            device.Dispatch(floats2.Length, 1, 1);
            var computeFloats2 = buffer.GetData <Vector2>();

            Assert.That(Utilities.Compare(floats2, computeFloats2), Is.True);

            // Test with float4 array
            var floats4 = new Vector4[4];

            for (int i = 0; i < floats4.Length; i++)
            {
                floats4[i] = new Vector4(i * 4, i * 4 + 1, i * 4 + 2, i * 4 + 3);
            }
            effect.Parameters["Floats4"].SetValue(floats4);

            var localFloats4 = effect.Parameters["Floats4"].GetValueArray <Vector4>(floats4.Length);

            Assert.That(Utilities.Compare(floats4, localFloats4), Is.True);

            var bufferFloats4 = Buffer.Structured.New <Vector2>(device, floats4.Length, true);

            effect.Parameters["Floats4Out"].SetResource(bufferFloats4);

            effect.CurrentTechnique.Passes[2].Apply();
            device.Dispatch(floats4.Length, 1, 1);
            var computeFloats4 = buffer.GetData <Vector4>();

            Assert.That(Utilities.Compare(floats4, computeFloats4), Is.True);

            effect.Dispose();
            device.Dispose();
        }
Ejemplo n.º 31
0
        public void TestMatrix()
        {
            // Compile a toolkit effect from a file
            var device = GraphicsDevice.New(DeviceCreationFlags.Debug);
            var result = new EffectCompiler().CompileFromFile("TestEffect.fx");

            var effect = new Effect(device, result.EffectData);

            var worldViewProj = effect.Parameters["worldViewProj"];
            var worlViewProjRowMajor = effect.Parameters["worlViewProjRowMajor"];
            var worldViewProj3x3 = effect.Parameters["worldViewProj3x3"];
            var matrix4x3 = effect.Parameters["matrix4x3"];
            var matrix3x4RowMajor = effect.Parameters["matrix3x4RowMajor"];


            var constantBuffer = effect.ConstantBuffers["$Globals"];
            var sourceMatrix = Matrix.RotationX(0.5f);

            // Test column_major float4x4 (the matrix is transposed automatically by the effect)
            worldViewProj.SetValue(sourceMatrix);
            var destMatrix = worldViewProj.GetMatrix();
            Assert.AreEqual(sourceMatrix, destMatrix);

            var destMatrix2 = constantBuffer.GetMatrix(worldViewProj.Offset);
            destMatrix2.Transpose();
            Assert.AreEqual(sourceMatrix, destMatrix2);

            // Test row_major float4x4 (the matrix is transferred as is)
            worlViewProjRowMajor.SetValue(sourceMatrix);
            destMatrix = worlViewProjRowMajor.GetMatrix();
            Assert.AreEqual(sourceMatrix, destMatrix);

            destMatrix2 = constantBuffer.GetMatrix(worlViewProjRowMajor.Offset);
            Assert.AreEqual(sourceMatrix, destMatrix2);

            // Test column_major float3x3 (the matrix is transposed automatically by the effect and only the 3x3 is transferred)
            var sourceMatrix3x3 = sourceMatrix;
            sourceMatrix3x3.Row4 = Vector4.Zero;
            sourceMatrix3x3.Column4 = Vector4.Zero;

            worldViewProj3x3.SetValue(sourceMatrix3x3);
            destMatrix = worldViewProj3x3.GetMatrix();
            Assert.AreEqual(sourceMatrix3x3, destMatrix);

            var destMatrixFloats = constantBuffer.GetRange<float>(worldViewProj3x3.Offset, 3 * 3);
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Assert.AreEqual(destMatrixFloats[j + i*3], sourceMatrix3x3[j, i]);
                }
            }

            effect.Dispose();
            device.Dispose();
        }
Ejemplo n.º 32
0
        public VoxelRenderer(GraphicsDevice graphicsDevice, ContentManager contentManager)
        {
            _cubeVertexBuffer = Buffer.Vertex.New(
                graphicsDevice,
                new[]
            {
                // 3D coordinates              UV Texture coordinates
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(0.0f, 1.0f)
                },                                                                                                                                     // Front
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(1.0f, 0.0f)
                },                                                                                                                                    // BACK
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, -1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(0.0f, 1.0f)
                },                                                                                                                                    // Top
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, 1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, -1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, -1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(1.0f, 0.0f)
                },                                                                                                                                     // Bottom
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, 1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, 1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, 1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(0.0f, 1.0f)
                },                                                                                                                                     // Left
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, 1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, 1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, 1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, -1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, -1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(1.0f, 0.0f)
                },                                                                                                                                    // Right
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, 1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, -1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, -1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(0.0f, 1.0f)
                }
            }, SharpDX.Direct3D11.ResourceUsage.Immutable);

            // Create an input layout from the vertices
            _vertexInputLayout = VertexInputLayout.New(
                VertexBufferLayout.New(0, new VertexElement[] { new VertexElement("POSITION_CUBE", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0),
                                                                new VertexElement("NORMAL", 0, SharpDX.DXGI.Format.R32G32B32_Float, sizeof(float) * 3),
                                                                new VertexElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, sizeof(float) * 6) }, 0),
                VertexBufferLayout.New(1, new VertexElement[] { new VertexElement("POSITION_INSTANCE", SharpDX.DXGI.Format.R32_SInt) }, 1));

            // Create instance buffer for every VoxelInfo
            _voxelTypeRenderingData = new VoxelTypeInstanceData[TypeInformation.GetNumTypes() - 1];
            for (int i = 0; i < _voxelTypeRenderingData.Length; ++i)
            {
                _voxelTypeRenderingData[i] = new VoxelTypeInstanceData(graphicsDevice, (VoxelType)(i + 1));
            }
            LoadTextures(contentManager);


            // load shader
            EffectCompilerFlags compilerFlags = EffectCompilerFlags.None;

#if DEBUG
            compilerFlags |= EffectCompilerFlags.Debug;
#endif
            var voxelShaderCompileResult = EffectCompiler.CompileFromFile("Content/voxel.fx", compilerFlags);
            if (voxelShaderCompileResult.HasErrors)
            {
                System.Console.WriteLine(voxelShaderCompileResult.Logger.Messages);
                System.Diagnostics.Debugger.Break();
            }
            _voxelEffect = new SharpDX.Toolkit.Graphics.Effect(graphicsDevice, voxelShaderCompileResult.EffectData);

            // setup states
            var rasterizerStateDesc = SharpDX.Direct3D11.RasterizerStateDescription.Default();
            rasterizerStateDesc.CullMode = SharpDX.Direct3D11.CullMode.Back;
            _backfaceCullingState        = RasterizerState.New(graphicsDevice, "CullModeBack", rasterizerStateDesc);
            rasterizerStateDesc.CullMode = SharpDX.Direct3D11.CullMode.None;
            _noneCullingState            = RasterizerState.New(graphicsDevice, "CullModeNone", rasterizerStateDesc);

            var depthStencilStateDesc = SharpDX.Direct3D11.DepthStencilStateDescription.Default();
            depthStencilStateDesc.IsDepthEnabled = true;
            _depthStencilStateState = DepthStencilState.New(graphicsDevice, "NormalZBufferUse", depthStencilStateDesc);

            var samplerStateDesc = SharpDX.Direct3D11.SamplerStateDescription.Default();
            samplerStateDesc.AddressV = SharpDX.Direct3D11.TextureAddressMode.Mirror;
            samplerStateDesc.AddressU = SharpDX.Direct3D11.TextureAddressMode.Mirror;
            samplerStateDesc.Filter   = SharpDX.Direct3D11.Filter.MinMagMipPoint;
            _pointSamplerState        = SamplerState.New(graphicsDevice, "PointSampler", samplerStateDesc);
            _voxelEffect.Parameters["PointSampler"].SetResource(_pointSamplerState);

            var blendStateDesc = SharpDX.Direct3D11.BlendStateDescription.Default();
            _blendStateOpaque = BlendState.New(graphicsDevice, "Opaque", blendStateDesc);
            blendStateDesc.RenderTarget[0].IsBlendEnabled   = true;
            blendStateDesc.RenderTarget[0].SourceBlend      = SharpDX.Direct3D11.BlendOption.SourceAlpha;
            blendStateDesc.RenderTarget[0].DestinationBlend = SharpDX.Direct3D11.BlendOption.InverseSourceAlpha;
            blendStateDesc.RenderTarget[0].BlendOperation   = SharpDX.Direct3D11.BlendOperation.Add;
            _blendStateTransparent = BlendState.New(graphicsDevice, "AlphaBlend", blendStateDesc);

            // vertexbuffer for a single instance
            _singleInstanceBuffer = Buffer.Vertex.New <Int32>(graphicsDevice, 1, SharpDX.Direct3D11.ResourceUsage.Dynamic);
        }
Ejemplo n.º 33
0
        public void TestFloats()
        {
            var device = GraphicsDevice.New();

            // Compile a toolkit effect from a file
            var result = new EffectCompiler().CompileFromFile("TestEffectValueArray.fx");

            // Check that we don't have any errors
            Assert.False(result.HasErrors);

            var bytecode = result.EffectData;

            var effect = new Effect(device, bytecode);

            // Test for floats
            // When uploading a float[16], each float in the array will be aligned to the closest float4
            // So it is actually as using a float4[16] array. The toolkit is managing this to avoid a 
            // user to have to remap to a float4. For efficiency, It is recommended to directly use float4
            // whenever possible.
            var floats = new float[16];
            for (int i = 0; i < floats.Length; i++)
            {
                floats[i] = i;
            }
            effect.Parameters["Floats"].SetValue(floats);
            var localFloats = effect.Parameters["Floats"].GetValueArray<float>(floats.Length);
            Assert.That(Utilities.Compare(floats, localFloats), Is.True);

            var buffer = Buffer.Structured.New<float>(device, floats.Length, true);
            effect.Parameters["FloatsOut"].SetResource(buffer);

            effect.CurrentTechnique = effect.Techniques["TestFloats"];

            effect.CurrentTechnique.Passes[0].Apply();
            device.Dispatch(floats.Length, 1, 1);
            var computeFloats = buffer.GetData<float>();
            Assert.That(Utilities.Compare(floats, computeFloats), Is.True);

            // Test with float2 array
            var floats2 = new Vector2[8];
            for (int i = 0; i < floats2.Length; i++)
            {
                floats2[i] = new Vector2(i * 2, i * 2 + 1);
            }
            effect.Parameters["Floats2"].SetValue(floats2);

            var localFloats2 = effect.Parameters["Floats2"].GetValueArray<Vector2>(floats2.Length);
            Assert.That(Utilities.Compare(floats2, localFloats2), Is.True);

            var bufferFloats2 = Buffer.Structured.New<Vector2>(device, floats2.Length, true);
            effect.Parameters["Floats2Out"].SetResource(bufferFloats2);

            effect.CurrentTechnique.Passes[1].Apply();
            device.Dispatch(floats2.Length, 1, 1);
            var computeFloats2 = buffer.GetData<Vector2>();
            Assert.That(Utilities.Compare(floats2, computeFloats2), Is.True);

            // Test with float4 array
            var floats4 = new Vector4[4];
            for (int i = 0; i < floats4.Length; i++)
            {
                floats4[i] = new Vector4(i * 4, i * 4 + 1, i * 4 + 2, i * 4 + 3);
            }
            effect.Parameters["Floats4"].SetValue(floats4);

            var localFloats4 = effect.Parameters["Floats4"].GetValueArray<Vector4>(floats4.Length);
            Assert.That(Utilities.Compare(floats4, localFloats4), Is.True);

            var bufferFloats4 = Buffer.Structured.New<Vector2>(device, floats4.Length, true);
            effect.Parameters["Floats4Out"].SetResource(bufferFloats4);

            effect.CurrentTechnique.Passes[2].Apply();
            device.Dispatch(floats4.Length, 1, 1);
            var computeFloats4 = buffer.GetData<Vector4>();
            Assert.That(Utilities.Compare(floats4, computeFloats4), Is.True);

            effect.Dispose();
            device.Dispose();
        }
Ejemplo n.º 34
0
        public void TestMaterial()
        {
            var compiler = new EffectCompiler {
                UseFileSystem = true
            };

            compiler.SourceDirectories.Add(@"..\..\sources\engine\SiliconStudio.Paradox.Graphics\Shaders");
            compiler.SourceDirectories.Add(@"..\..\sources\engine\SiliconStudio.Paradox.Engine\Shaders");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\Core");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\Lights");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\Materials");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\Shadows");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\ComputeColor");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\Skinning");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\Shading");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\Transformation");
            compiler.SourceDirectories.Add(@"..\..\sources\shaders\Utils");
            var compilerParameters = new CompilerParameters {
                Platform = GraphicsPlatform.Direct3D11
            };

            var layers = new MaterialBlendLayers();

            layers.Add(new MaterialBlendLayer
            {
                BlendMap = new ComputeFloat(0.5f),
                Material = AttachedReferenceManager.CreateSerializableVersion <Material>(Guid.Empty, "fake")
            });

            var materialAsset = new MaterialAsset
            {
                Attributes = new MaterialAttributes()
                {
                    Diffuse = new MaterialDiffuseMapFeature()
                    {
                        DiffuseMap = new ComputeColor(Color4.White)
                    },
                    DiffuseModel = new MaterialDiffuseLambertModelFeature()
                },
                Layers = layers
            };

            var fakeAsset = new MaterialAsset
            {
                Attributes = new MaterialAttributes()
                {
                    Diffuse = new MaterialDiffuseMapFeature()
                    {
                        DiffuseMap = new ComputeColor(Color.Blue)
                    },
                }
            };

            var context = new MaterialGeneratorContext {
                FindAsset = reference => fakeAsset
            };
            var result = MaterialGenerator.Generate(new MaterialDescriptor {
                Attributes = materialAsset.Attributes, Layers = materialAsset.Layers
            }, context, "TestMaterial");

            compilerParameters.Set(MaterialKeys.PixelStageSurfaceShaders, result.Material.Parameters.Get(MaterialKeys.PixelStageSurfaceShaders));
            var directionalLightGroup = new ShaderClassSource("LightDirectionalGroup", 1);

            compilerParameters.Set(LightingKeys.DirectLightGroups, new List <ShaderSource> {
                directionalLightGroup
            });
            //compilerParameters.Set(LightingKeys.CastShadows, false);
            //compilerParameters.Set(MaterialParameters.HasSkinningPosition, true);
            //compilerParameters.Set(MaterialParameters.HasSkinningNormal, true);
            compilerParameters.Set(MaterialKeys.HasNormalMap, true);

            var results = compiler.Compile(new ShaderMixinGeneratorSource("ParadoxEffectBase"), compilerParameters);

            Assert.IsFalse(results.HasErrors);
        }
Ejemplo n.º 35
0
        private void CompileMicrocode()
	    {
            ConstantTable constantTable = null;
            string errors = null;
            var defines = buildDefines(preprocessorDefines);

            var compileFlags = ShaderFlags.None;
            var parseFlags = ShaderFlags.None;

            parseFlags |= columnMajorMatrices ? ShaderFlags.PackMatrixColumnMajor : ShaderFlags.PackMatrixRowMajor;

#if DEBUG
            compileFlags |= ShaderFlags.Debug;
            parseFlags |= ShaderFlags.Debug;
#endif
            switch (optimizationLevel)
            {
                case OptimizationLevel.Default:
                    compileFlags |= ShaderFlags.OptimizationLevel1;
                    parseFlags |= ShaderFlags.OptimizationLevel1;
                    break;
                case OptimizationLevel.None:
                    compileFlags |= ShaderFlags.SkipOptimization;
                    parseFlags |= ShaderFlags.SkipOptimization;
                    break;
                case OptimizationLevel.LevelZero:
                    compileFlags |= ShaderFlags.OptimizationLevel0;
                    parseFlags |= ShaderFlags.OptimizationLevel0;
                    break;
                case OptimizationLevel.LevelOne:
                    compileFlags |= ShaderFlags.OptimizationLevel1;
                    parseFlags |= ShaderFlags.OptimizationLevel1;
                    break;
                case OptimizationLevel.LevelTwo:
                    compileFlags |= ShaderFlags.OptimizationLevel2;
                    parseFlags |= ShaderFlags.OptimizationLevel2;
                    break;
                case OptimizationLevel.LevelThree:
                    compileFlags |= ShaderFlags.OptimizationLevel3;
                    parseFlags |= ShaderFlags.OptimizationLevel3;
                    break;
            }

            // compile the high level shader to low level microcode
            // note, we need to pack matrices in row-major format for HLSL
            var effectCompiler = new EffectCompiler(Source, defines.ToArray(), includeHandler, parseFlags);
	       

            try
            {
                microcode = effectCompiler.CompileShader(new EffectHandle(entry),
                                                          target,
                                                          compileFlags,
                                                          out errors,
                                                          out constantTable);
            }
            catch (Direct3D9Exception ex)
            {
                throw new AxiomException("HLSL: Unable to compile high level shader {0}:\n{1}", ex, Name);
            }
            finally
            {
                // check for errors
                if ( !String.IsNullOrEmpty( errors ) )
                {
                    if ( microcode != null )
                    {
                        if ( LogManager.Instance != null )
                        {
                            LogManager.Instance.Write( "HLSL: Warnings while compiling high level shader {0}:\n{1}",
                                                       Name, errors );
                        }
                    }
                    else
                    {
                        throw new AxiomException( "HLSL: Unable to compile high level shader {0}:\n{1}", Name, errors );
                    }
                }


                // Get contents of the constant table
                var desc = constantTable.Description;
                CreateParameterMappingStructures( true );


                // Iterate over the constants
                for ( var i = 0; i < desc.Constants; ++i )
                {
                    // Recursively descend through the structure levels
                    ProcessParamElement( constantTable, null, "", i );
                }

                constantTable.Dispose();

                /*
                if ( GpuProgramManager.Instance.SaveMicrocodesToCache )
                {
                    AddMicrocodeToCache();
                }*/

                effectCompiler.Dispose();
            }

	    }