Esempio n. 1
0
        public ObjRenderer(Form1 F)
            : base(F.Device)
        {
            P = F;
            PortalRoomManager.Equals(null, null);
            S = new Sorter();
            string s0 = Environment.CurrentDirectory + "/resources/shaders/ambient_fast.fx";
            SB_V = ShaderBytecode.CompileFromFile(s0, "VS_STATIC", "vs_4_0", ManagedSettings.ShaderCompileFlags, EffectFlags.None);
            SB_P = ShaderBytecode.CompileFromFile(s0, "PS", "ps_4_0", ManagedSettings.ShaderCompileFlags, EffectFlags.None);
            VS = new VertexShader(F.Device.HadrwareDevice(), SB_V);
            PS = new PixelShader(F.Device.HadrwareDevice(), SB_P);
            IL = new InputLayout(Device.HadrwareDevice(), SB_V, StaticVertex.ies);
            BufferDescription desc = new BufferDescription
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = 2 * 64,
                BindFlags = BindFlags.ConstantBuffer
            };
            cBuf = new SlimDX.Direct3D11.Buffer(Device.HadrwareDevice(), desc);
            dS = new DataStream(2 * 64, true, true);

            BufferDescription desc2 = new BufferDescription
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = 64,
                BindFlags = BindFlags.ConstantBuffer
            };
            cBuf2 = new SlimDX.Direct3D11.Buffer(Device.HadrwareDevice(), desc2);
            dS2 = new DataStream(64, true, true);
        }
Esempio n. 2
0
 private void Load(string effectFile)
 {
     Device device = t.Device;
     bytecode = ShaderBytecode.CompileFromFile("01.frontend/shaders/" + effectFile, "fx_5_0", ShaderFlags.None, EffectFlags.None);
     effect = new Effect(device, bytecode);
     stride = SetLayout(device);
 }
        public override RenderableLightPrimitive GetRenderablePrimitive()
        {
            LightShader shader = new LightShader(Renderer);

            using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLight.vs"), true, false)))
            {
                shader.VertexShader = new VertexShader(Renderer.Device, bytecode);
                shader.InputLayout = new InputLayout(Renderer.Device, bytecode, new[]
                {
                    new InputElement("Position", 0, Format.R32G32B32_Float, sizeof(float) * 0, 0),
                });
            }
            using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLightShadowless.ps"), true, false)))
            {
                shader.PixelShader = new PixelShader(Renderer.Device, bytecode);
            }
            using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLightShadowless.ps"), true, false)))
            {
                shader.PixelShaderShadowless = new PixelShader(Renderer.Device, bytecode);
            }
            shader.Topology = PrimitiveTopology.TriangleList;

            ConstantBufferWrapper MatricesCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 32, ShaderType.VertexShader, 0);
            ConstantBufferWrapper LightCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 64, ShaderType.PixelShader, 0);
            ConstantBufferWrapper ShadowCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 16 * 4, ShaderType.PixelShader, 1);
            MatricesCBuffer.Semantics.Add(Semantic.WorldViewProj);
            MatricesCBuffer.Semantics.Add(Semantic.World);
            LightCBuffer.Semantics.Add(Semantic.View);
            LightCBuffer.Semantics.Add(Semantic.ViewInverse);
            LightCBuffer.Semantics.Add(Semantic.ViewProjInverse);
            LightCBuffer.Semantics.Add(Semantic.CameraPosition);
            shader.ConstantBuffers.Add(MatricesCBuffer);
            shader.ConstantBuffers.Add(LightCBuffer);
            shader.ConstantBuffers.Add(ShadowCBuffer);

            GeometricPrimitive prim = new SpherePrimitive(Renderer, 1, 16);

            DataStream str = new DataStream(prim.GeometryData.Positions, true, false);
            Buffer vertexBuffer = new Buffer(Renderer.Device, str, new BufferDescription()
            {
                SizeInBytes = (int)str.Length,
                BindFlags = BindFlags.VertexBuffer,
                StructureByteStride = 3 * sizeof(float),
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
            });
            int vertexCount = prim.GeometryData.VertexCount;

            DataStream IndicesStream = new DataStream(prim.GeometryData.Indices.ToArray(), true, true);

            int indexCount = prim.GeometryData.IndexCount;
            Buffer indexBuffer = new Buffer(Renderer.Device, IndicesStream, sizeof(ushort) * indexCount,
                ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, sizeof(ushort));

            prim.Dispose();

            return new RenderableLightPrimitive(shader, vertexBuffer, vertexCount, indexBuffer, indexCount);
        }
Esempio n. 4
0
        public virtual void Dispose()
        {
            InternalShaderByteCode.Dispose();

            if (m_shaderByteCode != null)
            {
                m_shaderByteCode.Dispose();
                m_shaderByteCode = null;
            }
        }
Esempio n. 5
0
 protected ShaderBase(string shaderSource,
                      string entryPoint,
                      ShaderVersion shaderVersion,
                      ShaderFlags shaderFlags = ShaderFlags.None,
                      EffectFlags effectFlags = EffectFlags.None)
 {
     m_shaderByteCode = ShaderBytecode.Compile(shaderSource,
                                               entryPoint,
                                               shaderVersion.ToShaderVersionString(),
                                               shaderFlags,
                                               effectFlags);
 }
Esempio n. 6
0
        protected ShaderBase(string embeddedSourceResourceName,
                             Assembly resourceAssembly,
                             string entryPoint,
                             ShaderVersion shaderVersion,
                             ShaderFlags shaderFlags = ShaderFlags.None,
                             EffectFlags effectFlags = EffectFlags.None)
        {
            string shaderSource = GetResourceString(embeddedSourceResourceName, resourceAssembly);

            m_shaderByteCode = ShaderBytecode.Compile(shaderSource,
                                                      entryPoint,
                                                      shaderVersion.ToShaderVersionString(),
                                                      shaderFlags,
                                                      effectFlags);
        }
Esempio n. 7
0
 protected Effect(Device device, string filename) {
     //Console.WriteLine("Loading effects from: " + Directory.GetCurrentDirectory());
     if (!File.Exists(filename)) {
         throw new FileNotFoundException(string.Format("Effect file {0} not present", filename));
     }
     ShaderBytecode compiledShader = null;
     try {
         compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes(filename), false, false));
         FX = new SlimDX.Direct3D11.Effect(device, compiledShader);
     } catch (Exception ex) {
         MessageBox.Show(ex.Message);
     } finally {
         Util.ReleaseCom(ref compiledShader);
     }
 }
Esempio n. 8
0
        public static ShaderBytecode PrecompileOrLoad(string fileName, string entryPoint, string profile, ShaderFlags shaderFlags, EffectFlags effectFlags)
        {
            FileInfo sourceFile = new FileInfo(fileName);

            if (!sourceFile.Exists)
                throw new FileNotFoundException();

            FileInfo compiledFile = new FileInfo(@"Precompiled\" + Path.GetFileNameWithoutExtension(sourceFile.Name) + "_" + entryPoint + "_" + profile + ".bin");

            if (compiledFile.Exists && sourceFile.LastWriteTime > compiledFile.LastWriteTime)
            {
                compiledFile.Delete();
                compiledFile.Refresh();
            }

            ShaderBytecode shaderBytecode = null;

            if (compiledFile.Exists)
            {
                byte[] compiledBytes = File.ReadAllBytes(compiledFile.FullName);
                DataStream compiledDataStream = new DataStream(compiledBytes, true, false);

                shaderBytecode = new ShaderBytecode(compiledDataStream);
            }
            else
            {
                shaderBytecode = ShaderBytecode.CompileFromFile(fileName, entryPoint, profile, shaderFlags, effectFlags);

                byte[] compiledBytes = shaderBytecode.Data.ReadRange<byte>((int)shaderBytecode.Data.Length);

                Directory.CreateDirectory(Path.GetDirectoryName(compiledFile.FullName));
                File.WriteAllBytes(compiledFile.FullName, compiledBytes);
            }

            if (shaderBytecode == null)
                throw new D3DCompilerException();

            return shaderBytecode;
        }
Esempio n. 9
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("DeferredGObject");
			E = new Effect(device, _b);

			TechStandardDeferred = E.GetTechniqueByName("StandardDeferred");
			TechStandardForward = E.GetTechniqueByName("StandardForward");
			TechAmbientShadowDeferred = E.GetTechniqueByName("AmbientShadowDeferred");
			TechTransparentDeferred = E.GetTechniqueByName("TransparentDeferred");
			TechTransparentForward = E.GetTechniqueByName("TransparentForward");
			TechTransparentMask = E.GetTechniqueByName("TransparentMask");

			for (var i = 0; i < TechStandardDeferred.Description.PassCount && InputSignaturePNTG == null; i++) {
				InputSignaturePNTG = TechStandardDeferred.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePNTG == null) throw new System.Exception("input signature (DeferredGObject, PNTG, StandardDeferred) == null");
			LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue);
			for (var i = 0; i < TechAmbientShadowDeferred.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechAmbientShadowDeferred.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (DeferredGObject, PT, AmbientShadowDeferred) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxWorld = E.GetVariableByName("gWorld").AsMatrix();
			FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix();
			FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix();
			FxDiffuseMap = E.GetVariableByName("gDiffuseMap").AsResource();
			FxNormalMap = E.GetVariableByName("gNormalMap").AsResource();
			FxMapsMap = E.GetVariableByName("gMapsMap").AsResource();
			FxDetailsMap = E.GetVariableByName("gDetailsMap").AsResource();
			FxDetailsNormalMap = E.GetVariableByName("gDetailsNormalMap").AsResource();
			FxReflectionCubemap = E.GetVariableByName("gReflectionCubemap").AsResource();
			FxEyePosW = E.GetVariableByName("gEyePosW").AsVector();
			FxAmbientDown = E.GetVariableByName("gAmbientDown").AsVector();
			FxAmbientRange = E.GetVariableByName("gAmbientRange").AsVector();
			FxLightColor = E.GetVariableByName("gLightColor").AsVector();
			FxDirectionalLightDirection = E.GetVariableByName("gDirectionalLightDirection").AsVector();
			FxMaterial = E.GetVariableByName("gMaterial");
		}
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonHullShader" /> class.
 /// </summary>
 /// <param name="graphics">The graphics interface that owns this object.</param>
 /// <param name="name">The name for this shader.</param>
 /// <param name="isDebug"><b>true</b> if debug information is included in the byte code, <b>false</b> if not.</param>
 /// <param name="byteCode">The byte code for the shader.</param>
 internal GorgonHullShader(GorgonGraphics graphics, string name, bool isDebug, ShaderBytecode byteCode)
     : base(graphics, name, isDebug, byteCode)
 {
     graphics.Log.Print($"Creating {ShaderType} '{name}' ({ID})", LoggingLevel.Verbose);
     _shader = new D3D11.HullShader(graphics.D3DDevice, byteCode)
     {
         DebugName = name + "_ID3D11HullShader"
     };
 }
Esempio n. 11
0
 protected override VertexShader CreateDeviceShader(Device device, ShaderBytecode bytecode)
 {
     return(new VertexShader(device, bytecode));
 }
Esempio n. 12
0
 protected override PixelShader CreateDeviceShader(Device device, ShaderBytecode bytecode)
 {
     return(new PixelShader(device, bytecode));
 }
Esempio n. 13
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("SimpleMaterial");
			E = new Effect(device, _b);

			TechStandard = E.GetTechniqueByName("Standard");
			TechAlpha = E.GetTechniqueByName("Alpha");
			TechReflective = E.GetTechniqueByName("Reflective");
			TechNm = E.GetTechniqueByName("Nm");
			TechNmUvMult = E.GetTechniqueByName("NmUvMult");
			TechAtNm = E.GetTechniqueByName("AtNm");
			TechMaps = E.GetTechniqueByName("Maps");
			TechDiffMaps = E.GetTechniqueByName("DiffMaps");
			TechGl = E.GetTechniqueByName("Gl");
			TechAmbientShadow = E.GetTechniqueByName("AmbientShadow");
			TechMirror = E.GetTechniqueByName("Mirror");

			for (var i = 0; i < TechAmbientShadow.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechAmbientShadow.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (SimpleMaterial, PT, AmbientShadow) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);
			for (var i = 0; i < TechStandard.Description.PassCount && InputSignaturePNTG == null; i++) {
				InputSignaturePNTG = TechStandard.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePNTG == null) throw new System.Exception("input signature (SimpleMaterial, PNTG, Standard) == null");
			LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue);

			FxWorld = E.GetVariableByName("gWorld").AsMatrix();
			FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix();
			FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix();
			FxDiffuseMap = E.GetVariableByName("gDiffuseMap").AsResource();
			FxNormalMap = E.GetVariableByName("gNormalMap").AsResource();
			FxMapsMap = E.GetVariableByName("gMapsMap").AsResource();
			FxDetailsMap = E.GetVariableByName("gDetailsMap").AsResource();
			FxDetailsNormalMap = E.GetVariableByName("gDetailsNormalMap").AsResource();
			FxEyePosW = E.GetVariableByName("gEyePosW").AsVector();
			FxMaterial = E.GetVariableByName("gMaterial");
			FxReflectiveMaterial = E.GetVariableByName("gReflectiveMaterial");
			FxMapsMaterial = E.GetVariableByName("gMapsMaterial");
			FxAlphaMaterial = E.GetVariableByName("gAlphaMaterial");
			FxNmUvMultMaterial = E.GetVariableByName("gNmUvMultMaterial");
		}
 public virtual void VertexFromString(string input)
 {
     bcVertex = ShaderBytecode.Compile(input, "VShader", "vs_4_0", ShaderFlags.Debug, EffectFlags.None);
     Vertex = new VertexShader(Device, bcVertex);
 }
Esempio n. 15
0
        public DepthAndColorShader(Device device)
        {
            shaderByteCode  = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorFloatVS.cso"));
            depthAndColorVS = new VertexShader(device, shaderByteCode);
            depthAndColorGS = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso")));
            depthAndColorPS = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso")));

            // depth stencil state
            var depthStencilStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.LessEqual,
                IsStencilEnabled = false,
            };

            depthStencilState = new DepthStencilState(device, depthStencilStateDesc);

            // rasterizer state
            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode                = CullMode.None,
                FillMode                = FillMode.Solid,
                IsDepthClipEnabled      = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled    = true,
            };

            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            // color sampler state
            var colorSamplerStateDesc = new SamplerStateDescription()
            {
                Filter   = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Border,
                AddressV = TextureAddressMode.Border,
                AddressW = TextureAddressMode.Border,
                //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f),
                BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f),
            };

            colorSamplerState = new SamplerState(device, colorSamplerStateDesc);

            //// Kinect depth image
            //var depthImageTextureDesc = new Texture2DDescription()
            //{
            //    Width = depthImageWidth,
            //    Height = depthImageHeight,
            //    MipLevels = 1,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.R16_UInt, // R32_Float
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Dynamic,
            //    BindFlags = BindFlags.ShaderResource,
            //    CpuAccessFlags = CpuAccessFlags.Write,
            //};
            //depthImageTexture = new Texture2D(device, depthImageTextureDesc);
            //depthImageTextureRV = new ShaderResourceView(device, depthImageTexture);

            // filtered depth image
            var filteredDepthImageTextureDesc = new Texture2DDescription()
            {
                Width             = Kinect2Calibration.depthImageWidth * 3,
                Height            = Kinect2Calibration.depthImageHeight * 3,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.R32G32_Float,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
            };

            filteredDepthImageTexture = new Texture2D(device, filteredDepthImageTextureDesc);
            filteredRenderTargetView  = new RenderTargetView(device, filteredDepthImageTexture);
            filteredDepthImageSRV     = new ShaderResourceView(device, filteredDepthImageTexture);

            filteredDepthImageTexture2 = new Texture2D(device, filteredDepthImageTextureDesc);
            filteredRenderTargetView2  = new RenderTargetView(device, filteredDepthImageTexture2);
            filteredDepthImageSRV2     = new ShaderResourceView(device, filteredDepthImageTexture2);



            //// Kinect color image
            //var colorImageStagingTextureDesc = new Texture2DDescription()
            //{
            //    Width = colorImageWidth,
            //    Height = colorImageHeight,
            //    MipLevels = 1,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            //    //Format = SharpDX.DXGI.Format.YUY2
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Dynamic,
            //    BindFlags = BindFlags.ShaderResource,
            //    CpuAccessFlags = CpuAccessFlags.Write
            //};
            //colorImageStagingTexture = new Texture2D(device, colorImageStagingTextureDesc);

            //var colorImageTextureDesc = new Texture2DDescription()
            //{
            //    Width = colorImageWidth,
            //    Height = colorImageHeight,
            //    MipLevels = 0,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Default,
            //    BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
            //    CpuAccessFlags = CpuAccessFlags.None,
            //    OptionFlags = ResourceOptionFlags.GenerateMipMaps
            //};
            //colorImageTexture = new Texture2D(device, colorImageTextureDesc);
            //colorImageTextureRV = new ShaderResourceView(device, colorImageTexture);

            // constant buffer
            var constantBufferDesc = new BufferDescription()
            {
                Usage               = ResourceUsage.Dynamic,
                BindFlags           = BindFlags.ConstantBuffer,
                SizeInBytes         = ConstantBuffer.size,
                CpuAccessFlags      = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags         = 0,
            };

            constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc);

            bilateralFilter = new BilateralFilter(device, Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight);

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });
        }
Esempio n. 16
0
        private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName)
        {
            try
            {
                #region Input Layout Configuration
                // Setup full paths
                vsFileName = SystemConfiguration.ShadersFilePath + vsFileName;
                psFileName = SystemConfiguration.ShadersFilePath + psFileName;

                // Compile the vertex shader code.
                var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "FontVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.EnableStrictness, EffectFlags.None);
                // Compile the pixel shader code.
                var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "FontPixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.EnableStrictness, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                var inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();
                #endregion

                #region Matrix Constant Buffer
                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                var matrixBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <MatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc);
                #endregion

                #region Sampler State
                // Create a texture sampler state description.
                var samplerDesc = new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = new Color4(0, 0, 0, 0),
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };

                // Create the texture sampler state.
                SampleState = new SamplerState(device, samplerDesc);
                #endregion

                #region Pixel Constant Buffer
                // Setup the description of the dynamic pixel constant buffer that is in the pixel shader.
                var pixelBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <PixelBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantPixelBuffer = new Buffer(device, pixelBufferDesc);
                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            };
        }
Esempio n. 17
0
        public ShaderInfo(FileChunk fileChunk)
        {
            bytecode = new ShaderBytecode(fileChunk.CompiledShader);
            this.Name = fileChunk.Name;
            this.ConstantHandles = new List<EffectHandle>();
            this.ConstantDescriptions = new List<ConstantDescription>();

            int i = 0;
            ConstantTable cTable = bytecode.ConstantTable;
            if (cTable != null)
            {
                EffectHandle handle = bytecode.ConstantTable.GetConstant(null, 0);
                while (handle != null)
                {
                    ConstantHandles.Add(handle);
                    var desc = bytecode.ConstantTable.GetConstantDescription(handle);
                    ConstantDescriptions.Add(desc);
                    i++;
                    handle = bytecode.ConstantTable.GetConstant(null, i);
                }
            }
        }
Esempio n. 18
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("PpOutline");
			E = new Effect(device, _b);

			TechOutline = E.GetTechniqueByName("Outline");

			for (var i = 0; i < TechOutline.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechOutline.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (PpOutline, PT, Outline) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxInputMap = E.GetVariableByName("gInputMap").AsResource();
			FxDepthMap = E.GetVariableByName("gDepthMap").AsResource();
			FxScreenSize = E.GetVariableByName("gScreenSize").AsVector();
		}
Esempio n. 19
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("PpSmaa");
			E = new Effect(device, _b);

			TechSmaa = E.GetTechniqueByName("Smaa");
			TechSmaaB = E.GetTechniqueByName("SmaaB");
			TechSmaaN = E.GetTechniqueByName("SmaaN");

			for (var i = 0; i < TechSmaa.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechSmaa.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (PpSmaa, PT, Smaa) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxInputMap = E.GetVariableByName("gInputMap").AsResource();
			FxEdgesMap = E.GetVariableByName("gEdgesMap").AsResource();
			FxBlendMap = E.GetVariableByName("gBlendMap").AsResource();
			FxAreaTexMap = E.GetVariableByName("gAreaTexMap").AsResource();
			FxSearchTexMap = E.GetVariableByName("gSearchTexMap").AsResource();
			FxSizeMultipler = E.GetVariableByName("gSizeMultipler").AsScalar();
			FxScreenSizeSpec = E.GetVariableByName("gScreenSizeSpec").AsVector();
		}
Esempio n. 20
0
        /// <summary>
        /// Converts the hlsl code into glsl and stores the result as plain text
        /// </summary>
        /// <param name="shaderSource">the hlsl shader</param>
        /// <param name="entryPoint">the entrypoint function name</param>
        /// <param name="stage">the shader pipeline stage</param>
        /// <param name="effectParameters"></param>
        /// <param name="reflection">the reflection gathered from the hlsl analysis</param>
        /// <param name="sourceFilename">the name of the source file</param>
        /// <returns></returns>
        public ShaderBytecodeResult Compile(string shaderSource, string entryPoint, ShaderStage stage, EffectCompilerParameters effectParameters, EffectReflection reflection, string sourceFilename = null)
        {
            var shaderBytecodeResult = new ShaderBytecodeResult();
            byte[] rawData;

            GlslShaderPlatform shaderPlatform;
            int shaderVersion;

            switch (effectParameters.Platform)
            {
                case GraphicsPlatform.OpenGL:
                    shaderPlatform = GlslShaderPlatform.OpenGL;
                    shaderVersion = 420;
                    break;
                case GraphicsPlatform.OpenGLES:
                    shaderPlatform = GlslShaderPlatform.OpenGLES;
                    shaderVersion = effectParameters.Profile >= GraphicsProfile.Level_10_0 ? 300 : 100;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("effectParameters.Platform");
            }

            var shader = Compile(shaderSource, entryPoint, stage, shaderPlatform, shaderVersion, shaderBytecodeResult, reflection, sourceFilename);

            if (shader == null)
                return shaderBytecodeResult;

            if (effectParameters.Platform == GraphicsPlatform.OpenGLES)
            {
                // store both ES 2 and ES 3 on OpenGL ES platforms
                var shaderBytecodes = new ShaderLevelBytecode();
                if (effectParameters.Profile >= GraphicsProfile.Level_10_0)
                {
                    shaderBytecodes.DataES3 = shader;
                    shaderBytecodes.DataES2 = null;
                }
                else
                {
                    shaderBytecodes.DataES2 = shader;
                    shaderBytecodes.DataES3 = Compile(shaderSource, entryPoint, stage, GlslShaderPlatform.OpenGLES, 300, shaderBytecodeResult, reflection, sourceFilename);
                }
                using (var stream = new MemoryStream())
                {
                    BinarySerialization.Write(stream, shaderBytecodes);
#if !SILICONSTUDIO_RUNTIME_CORECLR
                    rawData = stream.GetBuffer();
#else
// FIXME: Manu: The call to "ToArray()" might be slower than "GetBuffer()"
                    rawData = stream.ToArray();
#endif
                }
            }
            else
            {
                // store string on OpenGL platforms
                rawData = Encoding.ASCII.GetBytes(shader);
            }
            
            var bytecodeId = ObjectId.FromBytes(rawData);
            var bytecode = new ShaderBytecode(bytecodeId, rawData);
            bytecode.Stage = stage;

            shaderBytecodeResult.Bytecode = bytecode;
            
            return shaderBytecodeResult;
        }
Esempio n. 21
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("SpecialUv");
			E = new Effect(device, _b);

			TechMain = E.GetTechniqueByName("Main");

			for (var i = 0; i < TechMain.Description.PassCount && InputSignaturePNTG == null; i++) {
				InputSignaturePNTG = TechMain.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePNTG == null) throw new System.Exception("input signature (SpecialUv, PNTG, Main) == null");
			LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue);

			FxOffset = E.GetVariableByName("gOffset").AsVector();
		}
Esempio n. 22
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("SpecialTrackMap");
			E = new Effect(device, _b);

			TechMain = E.GetTechniqueByName("Main");
			TechPp = E.GetTechniqueByName("Pp");
			TechFinal = E.GetTechniqueByName("Final");
			TechFinalCheckers = E.GetTechniqueByName("FinalCheckers");
			TechPpHorizontalBlur = E.GetTechniqueByName("PpHorizontalBlur");
			TechPpVerticalBlur = E.GetTechniqueByName("PpVerticalBlur");

			for (var i = 0; i < TechMain.Description.PassCount && InputSignaturePNTG == null; i++) {
				InputSignaturePNTG = TechMain.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePNTG == null) throw new System.Exception("input signature (SpecialTrackMap, PNTG, Main) == null");
			LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue);
			for (var i = 0; i < TechPp.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechPp.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (SpecialTrackMap, PT, Pp) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix();
			FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix();
			FxInputMap = E.GetVariableByName("gInputMap").AsResource();
			FxScreenSize = E.GetVariableByName("gScreenSize").AsVector();
		}
Esempio n. 23
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("SpecialShadow");
			E = new Effect(device, _b);

			TechHorizontalShadowBlur = E.GetTechniqueByName("HorizontalShadowBlur");
			TechVerticalShadowBlur = E.GetTechniqueByName("VerticalShadowBlur");
			TechAmbientShadow = E.GetTechniqueByName("AmbientShadow");
			TechResult = E.GetTechniqueByName("Result");

			for (var i = 0; i < TechHorizontalShadowBlur.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechHorizontalShadowBlur.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (SpecialShadow, PT, HorizontalShadowBlur) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxShadowViewProj = E.GetVariableByName("gShadowViewProj").AsMatrix();
			FxInputMap = E.GetVariableByName("gInputMap").AsResource();
			FxDepthMap = E.GetVariableByName("gDepthMap").AsResource();
			FxMultipler = E.GetVariableByName("gMultipler").AsScalar();
			FxCount = E.GetVariableByName("gCount").AsScalar();
			FxPadding = E.GetVariableByName("gPadding").AsScalar();
			FxSize = E.GetVariableByName("gSize").AsVector();
			FxShadowSize = E.GetVariableByName("gShadowSize").AsVector();
		}
Esempio n. 24
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                _width  = Form.ClientSize.Width;
                _height = Form.ClientSize.Height;

                if (_swapChain == null)
                {
                    return;
                }

                renderView.Dispose();
                depthView.Dispose();
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            _width     = 1024;
            _height    = 768;
            _nearPlane = 1.0f;

            ambient = new Color4(Color.Gray.ToArgb());

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 10 device.");
                return;
            }


            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
            ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags);

            effect = new Effect(_device, shaderByteCode);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);

            shadowGenPass  = technique.GetPassByIndex(0);
            gBufferGenPass = technique.GetPassByIndex(1);
            debugDrawPass  = technique.GetPassByName("debug");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes    = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage          = ResourceUsage.Dynamic,
                BindFlags      = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags    = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");

            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription desc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias            = 0,
                DepthBiasClamp       = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled   = true,
            };

            _device.Rasterizer.State = new RasterizerState(_device, desc);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            depthStencilState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx

            shaderByteCode = LoadShader("grender.fx", shaderFlags);

            effect2            = new Effect(_device, shaderByteCode);
            technique          = effect2.GetTechniqueByIndex(0);
            gBufferRenderPass  = technique.GetPassByIndex(0);
            gBufferOverlayPass = technique.GetPassByIndex(1);

            Buffer quad = DemoFramework.SharpDX.MeshFactory.CreateScreenQuad(_device);

            quadBinding = new VertexBufferBinding(quad, 20, 0);
            Matrix quadProjection = Matrix.OrthoLH(1, 1, 0.1f, 1.0f);

            effect2.GetVariableByName("ViewProjection").AsMatrix().SetMatrix(quadProjection);

            InputElement[] elements = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0),
            };
            quadBufferLayout = new InputLayout(_device, gBufferRenderPass.Description.Signature, elements);


            info         = new InfoText(_device);
            _meshFactory = new MeshFactory(this);
            MeshFactory  = _meshFactory;

            CreateBuffers();
            LibraryManager.LibraryStarted();
        }
Esempio n. 25
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            RenderForm form = new RenderForm("Kinect RGB Joint sample");

            RenderDevice  device    = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            RenderContext context   = new RenderContext(device);
            DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle);

            //VertexShader vertexShader = ShaderCompiler.CompileFromFile<VertexShader>(device, "ColorJointView.fx", "VS");
            SharpDX.D3DCompiler.ShaderSignature signature;
            VertexShader vertexShader = ShaderCompiler.CompileFromFile(device, "ColorJointView.fx", "VS_Color", out signature);
            PixelShader  pixelShader  = ShaderCompiler.CompileFromFile <PixelShader>(device, "ColorJointView.fx", "PS_Color");

            DX11IndexedGeometry circle = device.Primitives.Segment(new Segment()
            {
                Resolution = 32
            });
            DX11InstancedIndexedDrawer drawer = new DX11InstancedIndexedDrawer();

            circle.AssignDrawer(drawer);

            InputLayout layout;
            var         bc = new ShaderBytecode(signature);

            circle.ValidateLayout(bc, out layout);

            KinectSensor sensor = KinectSensor.GetDefault();

            sensor.Open();

            Color4[] statusColor = new Color4[]
            {
                Color.Red,
                Color.Yellow,
                Color.Green
            };

            //Note cbuffer should have a minimum size of 16 bytes, so we create verctor4 instead of vector2
            SharpDX.Vector4 jointSize = new SharpDX.Vector4(0.04f, 0.07f, 0.0f, 1.0f);
            ConstantBuffer <SharpDX.Vector4> cbSize = new ConstantBuffer <SharpDX.Vector4>(device);

            cbSize.Update(context, ref jointSize);

            DX11StructuredBuffer colorTableBuffer = DX11StructuredBuffer.CreateImmutable <Color4>(device, statusColor);

            bool doQuit      = false;
            bool doUpload    = false;
            bool uploadImage = false;


            KinectBody[]            bodyFrame      = null;
            BodyColorPositionBuffer positionBuffer = new BodyColorPositionBuffer(device);
            BodyJointStatusBuffer   statusBuffer   = new BodyJointStatusBuffer(device);

            KinectSensorBodyFrameProvider provider = new KinectSensorBodyFrameProvider(sensor);

            provider.FrameReceived += (sender, args) => { bodyFrame = args.FrameData; doUpload = true; };

            ColorRGBAFrameData                 rgbFrame      = null;
            DynamicColorRGBATexture            colorTexture  = new DynamicColorRGBATexture(device);
            KinectSensorColorRGBAFrameProvider colorProvider = new KinectSensorColorRGBAFrameProvider(sensor);

            colorProvider.FrameReceived += (sender, args) => { rgbFrame = args.FrameData; uploadImage = true; };


            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape)
                                                {
                                                    doQuit = true;
                                                }
            };

            RenderLoop.Run(form, () =>
            {
                if (doQuit)
                {
                    form.Dispose();
                    return;
                }

                if (doUpload)
                {
                    var tracked    = bodyFrame.TrackedOnly();
                    var colorSpace = tracked.Select(kb => new ColorSpaceKinectJoints(kb, sensor.CoordinateMapper));

                    positionBuffer.Copy(context, colorSpace);
                    statusBuffer.Copy(context, tracked);
                    drawer.InstanceCount = colorSpace.Count() * Microsoft.Kinect.Body.JointCount;
                }

                if (uploadImage)
                {
                    colorTexture.Copy(context, rgbFrame);
                }

                context.RenderTargetStack.Push(swapChain);
                context.Context.ClearRenderTargetView(swapChain.RenderView, SharpDX.Color.Black);

                device.Primitives.ApplyFullTri(context, colorTexture.ShaderView);
                device.Primitives.FullScreenTriangle.Draw(context);

                circle.Bind(context, layout);

                context.Context.PixelShader.Set(pixelShader);
                context.Context.VertexShader.Set(vertexShader);
                context.Context.VertexShader.SetShaderResource(0, positionBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(1, statusBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(2, colorTableBuffer.ShaderView);
                context.Context.VertexShader.SetConstantBuffer(0, cbSize.Buffer);

                circle.Draw(context);

                context.RenderTargetStack.Pop();
                swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);
            });

            swapChain.Dispose();
            context.Dispose();
            device.Dispose();

            colorProvider.Dispose();
            colorTexture.Dispose();

            positionBuffer.Dispose();
            statusBuffer.Dispose();
            colorTableBuffer.Dispose();

            cbSize.Dispose();

            provider.Dispose();
            circle.Dispose();
            layout.Dispose();



            pixelShader.Dispose();
            vertexShader.Dispose();


            sensor.Close();
        }
Esempio n. 26
0
 protected virtual void Dispose(bool disposeManaged)
 {
     if (bytecode != null)
     {
         bytecode.Dispose();
         bytecode = null;
     }
 }
Esempio n. 27
0
        private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                // Compile the Vertex Shader & Pixel Shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ShadowVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "ShadowPixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the Vertex & Pixel Shaders from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "NORMAL",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout. Kin dof like a Vertex Declaration.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Create a wrap texture sampler state description.
                SamplerStateDescription samplerDesc = new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Clamp,
                    AddressV           = TextureAddressMode.Clamp,
                    AddressW           = TextureAddressMode.Clamp,
                    MipLodBias         = 0,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = new Color4(0, 0, 0, 0), // Black Border.
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };

                // Create the texture sampler state.
                SamplerStateClamp = new SamplerState(device, samplerDesc);

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                BufferDescription matrixBufferDescription = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic, // ResourceUsage.Default
                    SizeInBytes         = Utilities.SizeOf <DMatrixBufferType>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write, // CpuAccessFlags.None
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription);

                // Setup the description of the light dynamic constant bufffer that is in the pixel shader.
                // Note that ByteWidth alwalys needs to be a multiple of the 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail.
                BufferDescription light2BufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DLightBufferType2>(), // Must be divisable by 16 bytes, so this is equated to 32.
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantLightBuffer2 = new SharpDX.Direct3D11.Buffer(device, light2BufferDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
        /// <summary>
        /// 提供PixelShader接口对渲染进一步处理
        /// </summary>
        /// <param name="shaderbytes">编译出来的ps文件的bytes</param>
        public void SetPixelShader(byte[] shaderbytes)
        {
            this.SafeRelease(this.pixelShader);
            this.SafeRelease(this.pixelShaderConstantTable);
            this.SafeRelease(this.pixelShaderCode);

            this.pixelShaderCode = new ShaderBytecode(shaderbytes);
            this.pixelShader = new PixelShader(this.device, this.pixelShaderCode);
            this.pixelShaderConstantTable = this.pixelShaderCode.ConstantTable;
        }
Esempio n. 29
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("PpBlur");
			E = new Effect(device, _b);

			TechGaussianBlur = E.GetTechniqueByName("GaussianBlur");
			TechReflectionGaussianBlur = E.GetTechniqueByName("ReflectionGaussianBlur");

			for (var i = 0; i < TechGaussianBlur.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechGaussianBlur.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (PpBlur, PT, GaussianBlur) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxInputMap = E.GetVariableByName("gInputMap").AsResource();
			FxMapsMap = E.GetVariableByName("gMapsMap").AsResource();
			FxSampleWeights = E.GetVariableByName("gSampleWeights").AsScalar();
			FxPower = E.GetVariableByName("gPower").AsScalar();
			FxSampleOffsets = E.GetVariableByName("gSampleOffsets").AsVector();
		}
        /// <summary>
        /// 提供VertexShader接口对渲染进行进一步
        /// </summary>
        /// <param name="shader">编译出来的shader文件的bytes</param>
        public void SetVertexShader(byte[] shaderbytes)
        {
            this.SafeRelease(this.vertexShader);
            this.SafeRelease(this.vertexConstantTable);
            this.SafeRelease(this.vertexShaderCode);

            this.vertexShaderCode = new ShaderBytecode(shaderbytes);
            this.vertexShader = new VertexShader(this.device, this.vertexShaderCode);
            this.vertexConstantTable = this.vertexShaderCode.ConstantTable;
        }
Esempio n. 31
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("PpBasic");
			E = new Effect(device, _b);

			TechCopy = E.GetTechniqueByName("Copy");
			TechCopyNoAlpha = E.GetTechniqueByName("CopyNoAlpha");
			TechOverlay = E.GetTechniqueByName("Overlay");
			TechShadow = E.GetTechniqueByName("Shadow");
			TechDepth = E.GetTechniqueByName("Depth");
			TechFxaa = E.GetTechniqueByName("Fxaa");

			for (var i = 0; i < TechCopy.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechCopy.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (PpBasic, PT, Copy) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxInputMap = E.GetVariableByName("gInputMap").AsResource();
			FxOverlayMap = E.GetVariableByName("gOverlayMap").AsResource();
			FxDepthMap = E.GetVariableByName("gDepthMap").AsResource();
			FxSizeMultipler = E.GetVariableByName("gSizeMultipler").AsScalar();
			FxScreenSize = E.GetVariableByName("gScreenSize").AsVector();
		}
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref pixelShader);
            RemoveAndDispose(ref pointSamplerState);
            //RemoveAndDispose(ref indexBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            // Get a reference to the Device1 instance and immediate context
            var device  = DeviceManager.Direct3DDevice;
            var context = DeviceManager.Direct3DContext;

#if DEBUG
            var shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
#endif
            // Use our HLSL file include handler to resolve #include directives in the HLSL source
            //var includeHandler = new HLSLFileIncludeHandler(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "Shaders"));

            // Compile and create the vertex shader
            using (var vertexShaderBytecode = ToDispose(ShaderBytecode.Compile(shaderCode, "VSMain", "vs_4_0", shaderFlags, EffectFlags.None, null, null)))
            {
                vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode));


                //// Layout from VertexShader input signature
                //vertexLayout = ToDispose(new InputLayout(device,
                //    ShaderSignature.GetInputSignature(vertexShaderBytecode),
                ////ShaderSignature.GetInputSignature(vertexShaderBytecode),
                //new[]
                //{
                //    // "SV_Position" = vertex coordinate
                //    new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                //}));

                //// Create vertex buffer
                //vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new Vector3[] {
                //    /*  Position: float x 3 */
                //    new Vector3(-1.0f, -1.0f, -1.0f),
                //    new Vector3(-1.0f, 1.0f, -1.0f),
                //    new Vector3(1.0f, -1.0f, -1.0f),
                //    new Vector3(1.0f, 1.0f, -1.0f),
                //}));
                //vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vector3>(), 0);
                // Triangle strip:
                // v1   v3
                // |\   |
                // | \ B|
                // | A\ |
                // |   \|
                // v0   v2
            }

            // Compile and create the pixel shader
            using (var bytecode = ToDispose(ShaderBytecode.Compile(shaderCode, "PSMain", "ps_5_0", shaderFlags, EffectFlags.None, null, null)))
                pixelShader = ToDispose(new PixelShader(device, bytecode));

            linearSampleState = ToDispose(new SamplerState(device, new SamplerStateDescription
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                ComparisonFunction = Comparison.Never,
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            }));

            pointSamplerState = ToDispose(new SamplerState(device, new SamplerStateDescription
            {
                Filter             = Filter.MinMagMipPoint,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                ComparisonFunction = Comparison.Never,
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            }));

            context.Rasterizer.State = ToDispose(new RasterizerState(device, new RasterizerStateDescription
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid
            }));

            //// Configure the depth buffer to discard pixels that are
            //// further than the current pixel.
            //context.OutputMerger.SetDepthStencilState(ToDispose(new DepthStencilState(device,
            //    new DepthStencilStateDescription()
            //    {
            //        IsDepthEnabled = false, // enable depth?
            //        DepthComparison = Comparison.Less,
            //        DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All,
            //        IsStencilEnabled = false,// enable stencil?
            //        StencilReadMask = 0xff, // 0xff (no mask)
            //        StencilWriteMask = 0xff,// 0xff (no mask)
            //        // Configure FrontFace depth/stencil operations
            //        FrontFace = new DepthStencilOperationDescription()
            //        {
            //            Comparison = Comparison.Always,
            //            PassOperation = StencilOperation.Keep,
            //            FailOperation = StencilOperation.Keep,
            //            DepthFailOperation = StencilOperation.Increment
            //        },
            //        // Configure BackFace depth/stencil operations
            //        BackFace = new DepthStencilOperationDescription()
            //        {
            //            Comparison = Comparison.Always,
            //            PassOperation = StencilOperation.Keep,
            //            FailOperation = StencilOperation.Keep,
            //            DepthFailOperation = StencilOperation.Decrement
            //        },
            //    })));
        }
Esempio n. 33
0
 public D3DFragmentShader(Device device, ShaderBytecode bytecode)
     : base(device, ShaderStages.Fragment, bytecode)
 {
 }
Esempio n. 34
0
        internal static byte[] Compile(string source, ShaderMacro[] macros, MyShadersDefines.Profiles profile, string sourceDescriptor, bool optimize, bool invalidateCache, out bool wasCached, out string compileLog)
        {
            ProfilerShort.Begin("MyShaders.Compile");
            string function    = MyShadersDefines.ProfileEntryPoint(profile);
            string profileName = MyShadersDefines.ProfileToString(profile);

            wasCached  = false;
            compileLog = null;

            ProfilerShort.Begin("MyShaders.Preprocess");
            string preprocessedSource = PreprocessShader(source, macros);

            var key = MyShaderCache.CalculateKey(preprocessedSource, function, profileName);

            if (!invalidateCache)
            {
                var cached = MyShaderCache.TryFetch(key);
                if (cached != null)
                {
                    wasCached = true;
                    ProfilerShort.End();
                    ProfilerShort.End();
                    return(cached);
                }
            }
            ProfilerShort.End();

            try
            {
                string            descriptor        = sourceDescriptor + " " + profile + " " + macros.GetString();
                CompilationResult compilationResult = ShaderBytecode.Compile(preprocessedSource, function, profileName, optimize ? ShaderFlags.OptimizationLevel3 : 0, 0, null, null, descriptor);

                if (DUMP_CODE)
                {
                    var disassembly = compilationResult.Bytecode.Disassemble(DisassemblyFlags.EnableColorCode |
                                                                             DisassemblyFlags.EnableInstructionNumbering);
                    string asmPath;
                    if (MyRender11.DebugMode)
                    {
                        asmPath = Path.GetFileName(descriptor + "__DEBUG.html");
                    }
                    else
                    {
                        asmPath = Path.GetFileName(descriptor + "__O3.html");
                    }

                    using (var writer = new StreamWriter(Path.Combine(MyFileSystem.ContentPath, "ShaderOutput", asmPath)))
                    {
                        writer.Write(disassembly);
                    }
                }

                if (compilationResult.Message != null)
                {
                    compileLog = ExtendedErrorMessage(source, compilationResult.Message) + DumpShaderSource(key, preprocessedSource);
                }

                if (compilationResult.Bytecode.Data.Length > 0)
                {
                    MyShaderCache.Store(key.ToString(), compilationResult.Bytecode.Data);
                }

                return(compilationResult.Bytecode.Data);
            }
            catch (CompilationException e)
            {
                Debug.WriteLine(preprocessedSource);
                compileLog = ExtendedErrorMessage(source, e.Message) + DumpShaderSource(key, preprocessedSource);
            }
            finally
            {
                ProfilerShort.End();
            }
            return(null);
        }
Esempio n. 35
0
 public D3DVertexShader(Device device, ShaderBytecode bytecode)
     : base(device, ShaderStages.Vertex, bytecode)
 {
 }
Esempio n. 36
0
 public DX11ShaderInstance(DX11RenderContext context, ShaderBytecode bytecode)
 {
     this.context          = context;
     this.effect           = new Effect(context.Device, bytecode);
     this.currenttechnique = this.effect.GetTechniqueByIndex(0);
 }
Esempio n. 37
0
        private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = SystemConfiguration.ShadersFilePath + vsFileName;
                psFileName = SystemConfiguration.ShadersFilePath + psFileName;

                // Compile the vertex shader code.
                var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                // Compile the pixel shader code.
                var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                var inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = ShaderUtilities.Vector4Alignment,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                var matrixBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <Matrix>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            };
        }
Esempio n. 38
0
        // Handler for DeviceManager.OnInitialize
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // First release all ressources
            RemoveAndDispose(ref texture2D);
            RemoveAndDispose(ref vsByteCode);
            RemoveAndDispose(ref vsShader);
            RemoveAndDispose(ref psByteCode);
            RemoveAndDispose(ref psShader);
            RemoveAndDispose(ref vsLayout);
            RemoveAndDispose(ref depthStencilState);
            RemoveAndDispose(ref mvpBuffer);

            ShaderFlags flag = ShaderFlags.None;

#if DEBUG
            flag = ShaderFlags.Debug;
#endif
            var device  = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            // Compile and create vs shader
            vsByteCode = ToDispose(ShaderBytecode.CompileFromFile("Shaders/Simple.hlsl", "VSMain", "vs_5_0", flag));
            vsShader   = ToDispose(new VertexShader(device, vsByteCode));

            // Compile and create ps shader
            psByteCode = ToDispose(ShaderBytecode.CompileFromFile("Shaders/Simple.hlsl", "PSMain", "ps_5_0", flag));
            psShader   = ToDispose(new PixelShader(device, psByteCode));

            // Compile and create the depth vertex and pixel shaders
            // These shaders are for checking what the depth buffer should look like
            //depthVertexShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Depth.hlsl", "VSMain", "vs_5_0", flag));
            //depthVertexShader = ToDispose(new VertexShader(device, depthVertexShaderBytecode));
            //depthPixelShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Depth.hlsl", "PSMain", "ps_5_0", flag));
            //depthPixelShader = ToDispose(new PixelShader(device, depthPixelShaderBytecode));

            // Initialize vertex layout to match vs input structure
            // Input structure definition
            var input = new[]
            {
                // Position
                new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0),
                // Color
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
            };
            vsLayout = ToDispose(new InputLayout(device, vsByteCode.GetPart(ShaderBytecodePart.InputSignatureBlob), input));

            // Create the constant buffer to store the MVP matrix

            mvpBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create depth stencil state for OM

            depthStencilState = ToDispose(new DepthStencilState(device, new DepthStencilStateDescription
            {
                IsDepthEnabled   = true,
                DepthComparison  = Comparison.Less,
                DepthWriteMask   = DepthWriteMask.All,
                IsStencilEnabled = false,
                StencilReadMask  = 0xff, // no mask
                StencilWriteMask = 0xff,
                // Face culling
                FrontFace = new DepthStencilOperationDescription {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    FailOperation      = StencilOperation.Keep
                },

                BackFace = new DepthStencilOperationDescription
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    FailOperation      = StencilOperation.Keep
                },
            }));

            // Tell IA what vertices will look like
            context.InputAssembler.InputLayout = vsLayout;

            // Bind buffers to vs
            context.VertexShader.SetConstantBuffer(0, mvpBuffer);

            // Set vs to run
            context.VertexShader.Set(vsShader);

            // Set pixel shader to run
            context.PixelShader.Set(psShader);

            // Set depth stencil to OM
            context.OutputMerger.DepthStencilState = depthStencilState;

            InitializeMatricies();
        }
Esempio n. 39
0
        protected override void Initialize(DemoConfiguration demoConfiguration)
        {
            base.Initialize(demoConfiguration);

            var config = File.ReadAllLines("config.txt").Select(l => l.Split('=')).ToDictionary(k => k[0], v => string.Join("=", v.Skip(1)));

            Instruments.localBaro = int.Parse(config["localBaro"]);
            instruments.UpdateBaro();
            comPort              = config["comPort"];
            baudRate             = int.Parse(config["baudRate"]);
            Instruments.mbOffset = float.Parse(config["mbOffset"]);

            // Zero, Zero
            _form.Top = _form.Left = 0;

            adhrs = xPlaneMode ? (IADHRS) new ADHRSXPlane(comPort, baudRate) : (IADHRS) new ADHRS(comPort, baudRate);
            Task.Run(DataAquasition); // set it free!

            // Initialize a TextFormat
            Stock.TextFormatCenter = new TextFormat(FactoryDWrite, "Calibri", 64)
            {
                TextAlignment      = TextAlignment.Center,
                ParagraphAlignment = ParagraphAlignment.Center
            };
            Stock.TextFormatLeft = new TextFormat(FactoryDWrite, "Calibri", 64)
            {
                TextAlignment      = TextAlignment.Leading,
                ParagraphAlignment = ParagraphAlignment.Center
            };
            Stock.TextFormatRight = new TextFormat(FactoryDWrite, "Calibri", 64)
            {
                TextAlignment      = TextAlignment.Trailing,
                ParagraphAlignment = ParagraphAlignment.Center
            };
            Stock.TextFormatRightSmall = new TextFormat(FactoryDWrite, "Calibri", 48)
            {
                TextAlignment      = TextAlignment.Trailing,
                ParagraphAlignment = ParagraphAlignment.Center
            };

            RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;

            Stock.ClientRectangle = new RectangleF(0, 0, demoConfiguration.Width, demoConfiguration.Height);

            baroColorBrush       = new SolidColorBrush(RenderTarget2D, Color.DarkGray);
            instrumentColorBrush = new SolidColorBrush(RenderTarget2D, Color.LightGray);
            errorBrush           = new SolidColorBrush(RenderTarget2D, Color.Red);


            // Initialize Chevrons

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("BackFlip.fx", "VS", "vs_4_0");
            var vertexShader         = new VertexShader(Device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("BackFlip.fx", "PS", "ps_4_0");
            var pixelShader         = new PixelShader(Device, pixelShaderByteCode);

            var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
            // Layout from VertexShader input signature
            var layout = new InputLayout(Device, signature, new[]
            {
                new SharpDX.Direct3D11.InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new SharpDX.Direct3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });



            // Instantiate Vertex buiffer from vertex data
            var verticesChevron = SharpDX.Direct3D11.Buffer.Create(Device, BindFlags.VertexBuffer, attitudeIndicator.Chevrons());

            //var verticesTarget = SharpDX.Direct3D11.Buffer.Create(Device, BindFlags.VertexBuffer, attitudeIndicator.TargetBar(instruments.alpha));

            //var verticesDoF = SharpDX.Direct3D11.Buffer.Create(Device, BindFlags.VertexBuffer, attitudeIndicator.DirectionOfFlight(instruments.pitch));

            // Create Constant Buffer
            contantBuffer = new SharpDX.Direct3D11.Buffer(Device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            context = Device.ImmediateContext;

            // Prepare All the stages
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(verticesChevron, Utilities.SizeOf <Vector4>() * 2, 0));
            context.VertexShader.SetConstantBuffer(0, contantBuffer);
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            // Prepare matrices
            view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);

            proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, demoConfiguration.Width / (float)demoConfiguration.Height, 0.1f, 100.0f);

            varioBeeper.Start();
        }
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref vertexShaderBytecode);
            RemoveAndDispose(ref pixelShader);
            RemoveAndDispose(ref pixelShaderBytecode);

            RemoveAndDispose(ref depthVertexShader);
            RemoveAndDispose(ref depthVertexShaderBytecode);
            RemoveAndDispose(ref depthPixelShader);
            RemoveAndDispose(ref depthPixelShaderBytecode);

            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref worldViewProjectionBuffer);
            RemoveAndDispose(ref depthStencilState);

            // Get a reference to the Device1 instance and immediate context
            var device  = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            ShaderFlags shaderFlags = ShaderFlags.None;

#if DEBUG
            shaderFlags = ShaderFlags.Debug;
#endif

            // Compile and create the vertex shader
            vertexShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Simple.hlsl", "VSMain", "vs_5_0", shaderFlags));
            vertexShader         = ToDispose(new VertexShader(device, vertexShaderBytecode));

            // Compile and create the pixel shader
            pixelShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Simple.hlsl", "PSMain", "ps_5_0", shaderFlags));
            pixelShader         = ToDispose(new PixelShader(device, pixelShaderBytecode));

            // Compile and create the depth vertex and pixel shaders
            // These shaders are for checking what the depth buffer should look like
            depthVertexShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Depth.hlsl", "VSMain", "vs_5_0", shaderFlags));
            depthVertexShader         = ToDispose(new VertexShader(device, depthVertexShaderBytecode));
            depthPixelShaderBytecode  = ToDispose(ShaderBytecode.CompileFromFile("Depth.hlsl", "PSMain", "ps_5_0", shaderFlags));
            depthPixelShader          = ToDispose(new PixelShader(device, depthPixelShaderBytecode));

            // Layout from VertexShader input signature
            vertexLayout = ToDispose(new InputLayout(device,
                                                     vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                                                     //ShaderSignature.GetInputSignature(vertexShaderBytecode),
                                                     new[]
            {
                // input semantic SV_Position = vertex coordinate in object space
                new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0),
                // input semantic COLOR = vertex color
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            }));

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            worldViewProjectionBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                                                                new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,   // enable depth?
                DepthComparison  = Comparison.Less,
                DepthWriteMask   = SharpDX.Direct3D11.DepthWriteMask.All,
                IsStencilEnabled = false,   // enable stencil?
                StencilReadMask  = 0xff,    // 0xff (no mask)
                StencilWriteMask = 0xff,    // 0xff (no mask)
                // Configure FrontFace depth/stencil operations
                FrontFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment
                },
                // Configure BackFace depth/stencil operations
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement
                },
            }));

            // Tell the IA what the vertices will look like
            // in this case two 4-component 32bit floats
            // (32 bytes in total)
            context.InputAssembler.InputLayout = vertexLayout;

            // Set our constant buffer (to store worldViewProjection)
            context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

            // Set the vertex shader to run
            context.VertexShader.Set(vertexShader);

            // Set the pixel shader to run
            context.PixelShader.Set(pixelShader);

            // Set our depth stencil state
            context.OutputMerger.DepthStencilState = depthStencilState;
        }
Esempio n. 41
0
        private bool InitializeShader(Device device, IntPtr hwnd, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                // Compile the Vertex & Pixel Shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "SkyDomeVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "SkyDomePixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the Vertex & Pixel Shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                // Create the vertex input layout description.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                BufferDescription matrixBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDesc);

                // Setup the description of the gradient constant buffer that is in the pixel shader.
                BufferDescription gradientBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DGradientBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
                ConstantGradientBuffer = new SharpDX.Direct3D11.Buffer(device, gradientBufferDesc);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonGeometryShader" /> class.
 /// </summary>
 /// <param name="graphics">The graphics interface that owns this object.</param>
 /// <param name="name">The name for this shader.</param>
 /// <param name="isDebug"><b>true</b> if debug information is included in the byte code, <b>false</b> if not.</param>
 /// <param name="byteCode">The byte code for the shader.</param>
 /// <param name="soShader">The stream out shader.</param>
 private GorgonGeometryShader(GorgonGraphics graphics, string name, bool isDebug, ShaderBytecode byteCode, D3D11.GeometryShader soShader)
     : base(graphics, name, isDebug, byteCode)
 {
     graphics.Log.Print($"Creating {ShaderType} '{name}' ({ID})", LoggingLevel.Verbose);
     _shader = soShader;
 }
Esempio n. 43
0
 /// <summary>
 /// Creates a new <see cref="CachedShader"/> instance with the specified parameters
 /// </summary>
 /// <param name="loader">The <see cref="ShaderLoader"/> instance with the shader metadata</param>
 /// <param name="bytecode">The compiled shader bytecode</param>
 public CachedShader(ShaderLoader <T> loader, ShaderBytecode bytecode)
 {
     Loader   = loader;
     Bytecode = bytecode;
 }
Esempio n. 44
0
        /// <summary>
        /// Converts the hlsl code into glsl and stores the result as plain text
        /// </summary>
        /// <param name="shaderSource">the hlsl shader</param>
        /// <param name="entryPoint">the entrypoint function name</param>
        /// <param name="stage">the shader pipeline stage</param>
        /// <param name="effectParameters"></param>
        /// <param name="reflection">the reflection gathered from the hlsl analysis</param>
        /// <param name="sourceFilename">the name of the source file</param>
        /// <returns></returns>
        public ShaderBytecodeResult Compile(string shaderSource, string entryPoint, ShaderStage stage, EffectCompilerParameters effectParameters, EffectReflection reflection, string sourceFilename = null)
        {
            var shaderBytecodeResult = new ShaderBytecodeResult();

            byte[] rawData;

            var inputAttributeNames = new Dictionary <int, string>();
            var resourceBindings    = new Dictionary <string, int>();

            GlslShaderPlatform shaderPlatform;
            int shaderVersion;

            switch (effectParameters.Platform)
            {
            case GraphicsPlatform.OpenGL:
                shaderPlatform = GlslShaderPlatform.OpenGL;
                shaderVersion  = 420;
                break;

            case GraphicsPlatform.OpenGLES:
                shaderPlatform = GlslShaderPlatform.OpenGLES;
                shaderVersion  = effectParameters.Profile >= GraphicsProfile.Level_10_0 ? 300 : 100;
                break;

            case GraphicsPlatform.Vulkan:
                shaderPlatform = GlslShaderPlatform.Vulkan;
                shaderVersion  = 450;
                break;

            default:
                throw new ArgumentOutOfRangeException("effectParameters.Platform");
            }

            var shader = Compile(shaderSource, entryPoint, stage, shaderPlatform, shaderVersion, shaderBytecodeResult, reflection, inputAttributeNames, resourceBindings, sourceFilename);

            if (shader == null)
            {
                return(shaderBytecodeResult);
            }

            if (effectParameters.Platform == GraphicsPlatform.OpenGLES)
            {
                // store both ES 2 and ES 3 on OpenGL ES platforms
                var shaderBytecodes = new ShaderLevelBytecode();
                if (effectParameters.Profile >= GraphicsProfile.Level_10_0)
                {
                    shaderBytecodes.DataES3 = shader;
                    shaderBytecodes.DataES2 = null;
                }
                else
                {
                    shaderBytecodes.DataES2 = shader;
                    shaderBytecodes.DataES3 = Compile(shaderSource, entryPoint, stage, GlslShaderPlatform.OpenGLES, 300, shaderBytecodeResult, reflection, inputAttributeNames, resourceBindings, sourceFilename);
                }
                using (var stream = new MemoryStream())
                {
                    BinarySerialization.Write(stream, shaderBytecodes);
#if !SILICONSTUDIO_RUNTIME_CORECLR
                    rawData = stream.GetBuffer();
#else
// FIXME: Manu: The call to "ToArray()" might be slower than "GetBuffer()"
                    rawData = stream.ToArray();
#endif
                }
            }
            else if (effectParameters.Platform == GraphicsPlatform.Vulkan)
            {
                string inputFileExtension;
                switch (stage)
                {
                case ShaderStage.Vertex: inputFileExtension = ".vert"; break;

                case ShaderStage.Pixel: inputFileExtension = ".frag"; break;

                case ShaderStage.Geometry: inputFileExtension = ".geom"; break;

                case ShaderStage.Domain: inputFileExtension = ".tese"; break;

                case ShaderStage.Hull: inputFileExtension = ".tesc"; break;

                case ShaderStage.Compute: inputFileExtension = ".comp"; break;

                default:
                    shaderBytecodeResult.Error("Unknown shader profile");
                    return(shaderBytecodeResult);
                }

                var inputFileName  = Path.ChangeExtension(Path.GetTempFileName(), inputFileExtension);
                var outputFileName = Path.ChangeExtension(inputFileName, ".spv");

                // Write shader source to disk
                File.WriteAllBytes(inputFileName, Encoding.ASCII.GetBytes(shader));

                // Run shader compiler
                var process = new Process
                {
                    StartInfo =
                    {
                        FileName  = "glslangValidator.exe",
                        Arguments = $"-V -s -o {outputFileName} {inputFileName}",
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        UseShellExecute        = false,
                        CreateNoWindow         = true
                    }
                };
                process.Start();
                process.WaitForExit();

                if (!File.Exists(outputFileName))
                {
                    shaderBytecodeResult.Error("Failed to generate SPIR-V from GLSL");
                    return(shaderBytecodeResult);
                }

                // Read compiled shader
                var shaderBytecodes = new ShaderInputBytecode
                {
                    InputAttributeNames = inputAttributeNames,
                    ResourceBindings    = resourceBindings,
                    Data = File.ReadAllBytes(outputFileName),
                };

                using (var stream = new MemoryStream())
                {
                    BinarySerialization.Write(stream, shaderBytecodes);
                    rawData = stream.ToArray();
                }

                // Cleanup temp files
                File.Delete(inputFileName);
                File.Delete(outputFileName);
            }
            else
            {
                // store string on OpenGL platforms
                rawData = Encoding.ASCII.GetBytes(shader);
            }

            var bytecodeId = ObjectId.FromBytes(rawData);
            var bytecode   = new ShaderBytecode(bytecodeId, rawData);
            bytecode.Stage = stage;

            shaderBytecodeResult.Bytecode = bytecode;

            return(shaderBytecodeResult);
        }
        private void LoadAssets()
        {
            // Create an empty root signature.
            var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout);

            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

#if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
#endif

#if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
#endif

            // Define the vertex input layout.
            var inputElementDescs = new []
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout        = new InputLayoutDescription(inputElementDescs),
                RootSignature      = rootSignature,
                VertexShader       = vertexShader,
                PixelShader        = pixelShader,
                RasterizerState    = RasterizerStateDescription.Default(),
                BlendState         = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState  = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false, IsStencilEnabled = false
                },
                SampleMask            = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount     = 1,
                Flags             = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput      = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            var triangleVertices = new []
            {
                new Vertex()
                {
                    Position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), Color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f)
                },
                new Vertex()
                {
                    Position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), Color = new Vector4(0.0f, 1.0f, 0.0f, 1.0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), Color = new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
                },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes  = Utilities.SizeOf <Vertex>();
            vertexBufferView.SizeInBytes    = vertexBufferSize;

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create synchronization objects.
            fence      = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);
        }
Esempio n. 46
0
        bool InitializeShader(Device device, string vsFileName, string psFileName)
        {
            try {
                var compileVertexShaderResult = ShaderBytecode.CompileFromFile(vsFileName, "FontVertexShader", "vs_5_0", ShaderFlags.EnableStrictness);
                vertexShader = new VertexShader(device, compileVertexShaderResult.Bytecode);

                var compilePixelShaderResult = ShaderBytecode.CompileFromFile(psFileName, "FontPixelShader", "ps_5_0", ShaderFlags.EnableStrictness);
                pixelShader = new PixelShader(device, compilePixelShaderResult.Bytecode);

                var inputElements = new[] {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0)
                };

                inputLayout = new InputLayout(device, compileVertexShaderResult.Bytecode, inputElements);

                compileVertexShaderResult.Dispose();
                compilePixelShaderResult.Dispose();

                var matrixBufferDescription = new BufferDescription {
                    Usage               = ResourceUsage.Default,
                    SizeInBytes         = Utilities.SizeOf <ConstantBufferType>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.None,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                constantBuffer = Buffer.Create(device, new[] { new ConstantBufferType() }, matrixBufferDescription);

                var samplerStateDescription = new SamplerStateDescription {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0.0f,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        =
                    {
                        A = 0,
                        R = 0,
                        G = 0,
                        B = 0
                    },
                    MinimumLod = 0,
                    MaximumLod = float.MaxValue
                };

                samplerState = new SamplerState(device, samplerStateDescription);

                var pixelBufferDescription = new BufferDescription {
                    Usage               = ResourceUsage.Default,
                    SizeInBytes         = Utilities.SizeOf <PixelBufferType>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.None,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                pixelBuffer = Buffer.Create(device, new[] { new PixelBufferType() }, pixelBufferDescription);
            } catch { return(false); }
            return(true);
        }
Esempio n. 47
0
        public bool Initialize()
        {
            //Debug.Assert(!_initialized);
            if (_initialized)
            {
                return(false);
            }

            #region Shaders
            string SpriteFX = @"Texture2D SpriteTex;
SamplerState samLinear {
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = WRAP;
    AddressV = WRAP;
};
struct VertexIn {
    float3 PosNdc : POSITION;
    float2 Tex    : TEXCOORD;
    float4 Color  : COLOR;
};
struct VertexOut {
    float4 PosNdc : SV_POSITION;
    float2 Tex    : TEXCOORD;
    float4 Color  : COLOR;
};
VertexOut VS(VertexIn vin) {
    VertexOut vout;
    vout.PosNdc = float4(vin.PosNdc, 1.0f);
    vout.Tex    = vin.Tex;
    vout.Color  = vin.Color;
    return vout;
};
float4 PS(VertexOut pin) : SV_Target {
    return pin.Color*SpriteTex.Sample(samLinear, pin.Tex);
};
technique11 SpriteTech {
    pass P0 {
        SetVertexShader( CompileShader( vs_5_0, VS() ) );
        SetHullShader( NULL );
        SetDomainShader( NULL );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_5_0, PS() ) );
    }
};";
            #endregion

            _compiledFX = ToDispose(ShaderBytecode.Compile(SpriteFX, "SpriteTech", "fx_5_0"));
            {
                if (_compiledFX.HasErrors)
                {
                    return(false);
                }

                _effect = ToDispose(new Effect(_device, _compiledFX));
                {
                    _spriteTech = ToDispose(_effect.GetTechniqueByName("SpriteTech"));
                    _spriteMap  = ToDispose(_effect.GetVariableByName("SpriteTex").AsShaderResource());

                    using (var pass = _spriteTech.GetPassByIndex(0))
                    {
                        InputElement[] layoutDesc =
                        {
                            new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float,     0, 0, InputClassification.PerVertexData, 0),
                            new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float,       12, 0, InputClassification.PerVertexData, 0),
                            new InputElement("COLOR",    0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0)
                        };

                        _inputLayout = ToDispose(new InputLayout(_device, pass.Description.Signature, layoutDesc));
                    }
                    // Create Vertex Buffer
                    BufferDescription vbd = new BufferDescription
                    {
                        SizeInBytes         = 2048 * Marshal.SizeOf(typeof(SpriteVertex)),
                        Usage               = ResourceUsage.Dynamic,
                        BindFlags           = BindFlags.VertexBuffer,
                        CpuAccessFlags      = CpuAccessFlags.Write,
                        OptionFlags         = ResourceOptionFlags.None,
                        StructureByteStride = 0
                    };

                    _VB = ToDispose(new SharpDX.Direct3D11.Buffer(_device, vbd));

                    // Create and initialise Index Buffer

                    short[] indices = new short[3072];

                    for (ushort i = 0; i < 512; ++i)
                    {
                        indices[i * 6]     = (short)(i * 4);
                        indices[i * 6 + 1] = (short)(i * 4 + 1);
                        indices[i * 6 + 2] = (short)(i * 4 + 2);
                        indices[i * 6 + 3] = (short)(i * 4);
                        indices[i * 6 + 4] = (short)(i * 4 + 2);
                        indices[i * 6 + 5] = (short)(i * 4 + 3);
                    }

                    _indexBuffer = ToDispose(new SafeHGlobal(indices.Length * Marshal.SizeOf(indices[0])));
                    Marshal.Copy(indices, 0, _indexBuffer.DangerousGetHandle(), indices.Length);

                    BufferDescription ibd = new BufferDescription
                    {
                        SizeInBytes         = 3072 * Marshal.SizeOf(typeof(short)),
                        Usage               = ResourceUsage.Immutable,
                        BindFlags           = BindFlags.IndexBuffer,
                        CpuAccessFlags      = CpuAccessFlags.None,
                        OptionFlags         = ResourceOptionFlags.None,
                        StructureByteStride = 0
                    };

                    _IB = ToDispose(new SharpDX.Direct3D11.Buffer(_device, _indexBuffer.DangerousGetHandle(), ibd));

                    BlendStateDescription transparentDesc = new BlendStateDescription()
                    {
                        AlphaToCoverageEnable  = false,
                        IndependentBlendEnable = false,
                    };
                    transparentDesc.RenderTarget[0].IsBlendEnabled        = true;
                    transparentDesc.RenderTarget[0].SourceBlend           = BlendOption.SourceAlpha;
                    transparentDesc.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
                    transparentDesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
                    transparentDesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
                    transparentDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
                    transparentDesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
                    transparentDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

                    _transparentBS = ToDispose(new BlendState(_device, transparentDesc));
                }
            }

            _initialized = true;

            return(true);
        }
Esempio n. 48
0
        private void BuildFX() {
            ShaderBytecode compiledShader = null;
            try {
                compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes("fx/color.fxo"), false, false));
                _fx = new Effect(Device, compiledShader);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return;
            } finally {
                Util.ReleaseCom(ref compiledShader);
            }

            _tech = _fx.GetTechniqueByName("ColorTech");
            _fxWVP = _fx.GetVariableByName("gWorldViewProj").AsMatrix();
        }
        private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFileName, string psFileName)
        {
            try
            {
                //vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                //psFileName = DSystemConfiguration.ShaderFilePath + psFileName;


                /*var vsFileNameByteArray = SCCoreSystems.Properties.Resources.Color1;
                 * var psFileNameByteArray = SCCoreSystems.Properties.Resources.Color;
                 * //var gsFileNameByteArray = SCCoreSystems.Properties.Resources.HLSL;
                 *
                 * ShaderBytecode vertexShaderByteCode = ShaderBytecode.Compile(vsFileNameByteArray, "ColorVertexShader", "vs_5_0", ShaderFlags.None, EffectFlags.None);
                 * ShaderBytecode pixelShaderByteCode = ShaderBytecode.Compile(psFileNameByteArray, "ColorPixelShader", "ps_5_0", ShaderFlags.None, EffectFlags.None);
                 */

                vsFileName = "../../../sc_instance_shader/" + "Color.vs";
                psFileName = "../../../sc_instance_shader/" + "Color.ps";

                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);



                // Compile the vertex shader code.
                //ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                // Compile the pixel shader code.
                //ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                BufferDescription matrixBufDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(), // was Matrix
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufDesc);

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(" DObjectColorShaderCLASS ERROR ### " + ex.ToString());
                return(false);
            }
        }
Esempio n. 50
0
 public DX11ShaderInstance(DX11RenderContext context, ShaderBytecode bytecode)
 {
     this.context = context;
     this.effect = new Effect(context.Device, bytecode);
     this.currenttechnique = this.effect.GetTechniqueByIndex(0);
 }
Esempio n. 51
0
        /// <summary>
        /// Converts the hlsl code into glsl and stores the result as plain text
        /// </summary>
        /// <param name="shaderSource">the hlsl shader</param>
        /// <param name="entryPoint">the entrypoint function name</param>
        /// <param name="stage">the shader pipeline stage</param>
        /// <param name="compilerParameters"></param>
        /// <param name="reflection">the reflection gathered from the hlsl analysis</param>
        /// <param name="sourceFilename">the name of the source file</param>
        /// <returns></returns>
        public ShaderBytecodeResult Compile(string shaderSource, string entryPoint, ShaderStage stage, ShaderMixinParameters compilerParameters, EffectReflection reflection, string sourceFilename = null)
        {
            var isOpenGLES = compilerParameters.Get(CompilerParameters.GraphicsPlatformKey) == GraphicsPlatform.OpenGLES;
            var isOpenGLES3 = compilerParameters.Get(CompilerParameters.GraphicsProfileKey) >= GraphicsProfile.Level_10_0;
            var shaderBytecodeResult = new ShaderBytecodeResult();
            byte[] rawData;

            var shader = Compile(shaderSource, entryPoint, stage, isOpenGLES, isOpenGLES3, shaderBytecodeResult, sourceFilename);

            if (shader == null)
                return shaderBytecodeResult;

            if (isOpenGLES)
            {
                // store both ES 2 and ES 3 on OpenGL ES platforms
                var shaderBytecodes = new ShaderLevelBytecode();
                if (isOpenGLES3)
                {
                    shaderBytecodes.DataES3 = shader;
                    shaderBytecodes.DataES2 = null;
                }
                else
                {
                    shaderBytecodes.DataES2 = shader;
                    shaderBytecodes.DataES3 = Compile(shaderSource, entryPoint, stage, true, true, shaderBytecodeResult, sourceFilename);
                }
                using (var stream = new MemoryStream())
                {
                    BinarySerialization.Write(stream, shaderBytecodes);
#if !SILICONSTUDIO_RUNTIME_CORECLR
                    rawData = stream.GetBuffer();
#else
// FIXME: Manu: The call to "ToArray()" might be slower than "GetBuffer()"
                    rawData = stream.ToArray();
#endif
                }
            }
            else
            {
                // store string on OpenGL platforms
                rawData = Encoding.ASCII.GetBytes(shader);
            }
            
            var bytecodeId = ObjectId.FromBytes(rawData);
            var bytecode = new ShaderBytecode(bytecodeId, rawData);
            bytecode.Stage = stage;

            shaderBytecodeResult.Bytecode = bytecode;
            
            return shaderBytecodeResult;
        }
Esempio n. 52
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("PpHdr");
			E = new Effect(device, _b);

			TechDownsampling = E.GetTechniqueByName("Downsampling");
			TechAdaptation = E.GetTechniqueByName("Adaptation");
			TechTonemap = E.GetTechniqueByName("Tonemap");
			TechCopy = E.GetTechniqueByName("Copy");
			TechCombine = E.GetTechniqueByName("Combine");
			TechBloom = E.GetTechniqueByName("Bloom");

			for (var i = 0; i < TechDownsampling.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechDownsampling.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (PpHdr, PT, Downsampling) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxInputMap = E.GetVariableByName("gInputMap").AsResource();
			FxBrightnessMap = E.GetVariableByName("gBrightnessMap").AsResource();
			FxBloomMap = E.GetVariableByName("gBloomMap").AsResource();
			FxPixel = E.GetVariableByName("gPixel").AsVector();
			FxCropImage = E.GetVariableByName("gCropImage").AsVector();
		}
 public virtual void Dispose()
 {
     if (Vertex != null)
     {
         Vertex.Dispose();
         Vertex = null;
         bcVertex.Dispose();
         bcVertex = null;
     }
     if (Pixel != null)
     {
         Pixel.Dispose();
         Pixel = null;
         bcPixel.Dispose();
         bcPixel = null;
     }
     if (Effect != null)
     {
         Effect.Dispose();
         Effect = null;
         bcEffect.Dispose();
         bcEffect = null;
     }
     if (Geo != null)
     {
         Geo.Dispose();
         Geo = null;
         bcGeo.Dispose();
         bcGeo = null;
     }
 }
Esempio n. 54
0
 public D3DGeometryShader(Device device, ShaderBytecode bytecode)
     : base(device, ShaderStages.Geometry, bytecode)
 {
 }
Esempio n. 55
0
 public D3DTessellationControlShader(Device device, ShaderBytecode bytecode)
     : base(device, ShaderStages.TessellationControl, bytecode)
 {
 }
Esempio n. 56
0
 protected override GeometryShader CreateDeviceShader(Device device, ShaderBytecode bytecode)
 {
     return(new GeometryShader(device, bytecode));
 }
Esempio n. 57
0
        public void Load()
        {
            byte[] effectBuffer = null;
            ShaderSignature inputSignature;
            try
            {
                using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("OpenSAGE.Shaders.Compiled.Simple.fxo"))
                {
                    effectBuffer = new byte[stream.Length];
                    stream.Read(effectBuffer, 0, effectBuffer.Length);
                }
                using (DataStream stream = new DataStream(effectBuffer, true, true))
                {
                    using (ShaderBytecode byteCode = new ShaderBytecode(stream))
                    {
                        _effect = new Effect(_device, byteCode);
                    }
                }
            }
            catch
            {
                using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("OpenSAGE.Shaders.Simple.fx"))
                {
                    effectBuffer = new byte[stream.Length];
                    stream.Read(effectBuffer, 0, effectBuffer.Length);
                }
                using (ShaderBytecode byteCode = ShaderBytecode.Compile(effectBuffer, "fx_5_0"))
                {
                    _effect = new Effect(_device, byteCode);
                }
            }
            _defaultTechnique = _effect.GetTechniqueByName("Default");
            EffectPass pass = _defaultTechnique.GetPassByIndex(0);
            inputSignature = pass.Description.Signature;

            byte[] vertices = new byte[0x70];
            int position = 0;
            BufferWriter.WriteVector3(vertices, ref position, new Math.Vector3(0.0f, 0.5f, 0.5f));
            BufferWriter.WriteLinearColorRGBA(vertices, ref position, new Math.LinearColor(1.0f, 0.0f, 0.0f));
            BufferWriter.WriteVector3(vertices, ref position, new Math.Vector3(0.5f, -0.5f, 0.5f));
            BufferWriter.WriteLinearColorRGBA(vertices, ref position, new Math.LinearColor(0.0f, 1.0f, 0.0f));
            BufferWriter.WriteVector3(vertices, ref position, new Math.Vector3(-0.5f, -0.5f, 0.5f));
            BufferWriter.WriteLinearColorRGBA(vertices, ref position, new Math.LinearColor(0.0f, 0.0f, 1.0f));
            BufferWriter.WriteVector3(vertices, ref position, new Math.Vector3(-0.5f, 0.5f, 0.5f));
            BufferWriter.WriteLinearColorRGBA(vertices, position, new Math.LinearColor(1.0f, 1.0f, 1.0f, 0.0f));
            DataStream vertexStream = new DataStream(vertices, true, true);
            _vertexBuffer = new D3D11Buffer(_device, vertexStream, 0x70,
                ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            byte[] indices = new byte[12];
            position = 0;
            BufferWriter.WriteUInt16(indices, ref position, 0);
            BufferWriter.WriteUInt16(indices, ref position, 1);
            BufferWriter.WriteUInt16(indices, ref position, 2);
            BufferWriter.WriteUInt16(indices, ref position, 3);
            BufferWriter.WriteUInt16(indices, ref position, 0);
            BufferWriter.WriteUInt16(indices, ref position, 2);
            DataStream indexStream = new DataStream(indices, true, true);
            _indexBuffer = new D3D11Buffer(_device, indexStream, 12,
                ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            InputElement[] inElements = new[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
                };
            _inLayout = new InputLayout(_device, inputSignature, inElements);
            _deviceContext.InputAssembler.InputLayout = _inLayout;
            _deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            _deviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_vertexBuffer, 28, 0));
            _deviceContext.InputAssembler.SetIndexBuffer(_indexBuffer, Format.R16_UInt, 0);
            _defaultTechnique.GetPassByIndex(0).Apply(_deviceContext);
        }
Esempio n. 58
0
 public D3DTessellationEvaluationShader(Device device, ShaderBytecode bytecode)
     : base(device, ShaderStages.TessellationEvaluation, bytecode)
 {
 }
Esempio n. 59
0
        private void BuildFX() {
            ShaderBytecode compiledShader = null;
            try {
                compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes("fx/Lighting.fxo"), false, false));
                _fx = new Effect(Device, compiledShader);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return;
            } finally {
                Util.ReleaseCom(ref compiledShader);
            }

            _tech = _fx.GetTechniqueByName("LightTech");
            _fxWVP = _fx.GetVariableByName("gWorldViewProj").AsMatrix();
            _fxWorld = _fx.GetVariableByName("gWorld").AsMatrix();
            _fxWIT = _fx.GetVariableByName("gWorldInvTranspose").AsMatrix();
            _fxEyePosW = _fx.GetVariableByName("gEyePosW").AsVector();
            _fxDirLight = _fx.GetVariableByName("gDirLight");
            _fxPointLight = _fx.GetVariableByName("gPointLight");
            _fxSpotLight = _fx.GetVariableByName("gSpotLight");
            _fxMaterial = _fx.GetVariableByName("gMaterial");
        }
Esempio n. 60
0
 protected override DomainShader CreateDeviceShader(Device device, ShaderBytecode bytecode)
 {
     return(new DomainShader(device, bytecode));
 }