Example #1
0
        /// <summary>
        /// Function to reset the shader states.
        /// </summary>
        internal void Reset()
        {
            VertexShader.Reset();
            PixelShader.Reset();

            if (GeometryShader != null)
            {
                GeometryShader.Reset();
            }

            if (ComputeShader != null)
            {
                ComputeShader.Reset();
            }

            if (HullShader != null)
            {
                HullShader.Reset();
            }

            if (DomainShader != null)
            {
                DomainShader.Reset();
            }
        }
Example #2
0
            /// <summary>
            /// Sets the shader.
            /// </summary>
            /// <param name="shader">The shader.</param>
            public void SetShader(ShaderBase shader)
            {
                switch (shader.ShaderType)
                {
                case ShaderStage.Vertex:
                    RemoveAndDispose(ref vertexShader);
                    vertexShader = shader as VertexShader ?? VertexShader.NullVertexShader;
                    break;

                case ShaderStage.Pixel:
                    RemoveAndDispose(ref pixelShader);
                    pixelShader = shader as PixelShader ?? PixelShader.NullPixelShader;
                    break;

                case ShaderStage.Compute:
                    RemoveAndDispose(ref computeShader);
                    computeShader = shader as ComputeShader ?? ComputeShader.NullComputeShader;
                    break;

                case ShaderStage.Hull:
                    RemoveAndDispose(ref hullShader);
                    hullShader = shader as HullShader ?? HullShader.NullHullShader;
                    break;

                case ShaderStage.Domain:
                    RemoveAndDispose(ref domainShader);
                    domainShader = shader as DomainShader ?? DomainShader.NullDomainShader;
                    break;

                case ShaderStage.Geometry:
                    RemoveAndDispose(ref geometryShader);
                    geometryShader = shader as GeometryShader ?? GeometryShader.NullGeometryShader;
                    break;
                }
            }
Example #3
0
        /// <summary>
        /// Release Elements
        /// </summary>
        public void Dispose()
        {
            if (VertexShader != null)
            {
                VertexShader.Dispose();
            }

            if (PixelShader != null)
            {
                PixelShader.Dispose();
            }

            if (GeometryShader != null)
            {
                GeometryShader.Dispose();
            }

            if (DomainShader != null)
            {
                DomainShader.Dispose();
            }

            if (HullShader != null)
            {
                HullShader.Dispose();
            }

            if (Layout != null)
            {
                Layout.Dispose();
            }
        }
Example #4
0
        public D3D11Shader(Device device, ShaderDescription description)
        {
            switch (description.Stage)
            {
            case ShaderStages.Vertex:
                DeviceShader = new VertexShader(device, description.ShaderBytes);
                break;

            case ShaderStages.Geometry:
                DeviceShader = new GeometryShader(device, description.ShaderBytes);
                break;

            case ShaderStages.TessellationControl:
                DeviceShader = new HullShader(device, description.ShaderBytes);
                break;

            case ShaderStages.TessellationEvaluation:
                DeviceShader = new DomainShader(device, description.ShaderBytes);
                break;

            case ShaderStages.Fragment:
                DeviceShader = new PixelShader(device, description.ShaderBytes);
                break;

            default:
                throw Illegal.Value <ShaderStages>();
            }

            Bytecode = description.ShaderBytes;
        }
Example #5
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="passDescription"></param>
            /// <param name="manager"></param>
            public ShaderPass(ShaderPassDescription passDescription, IEffectsManager manager)
            {
                Name           = passDescription.Name;
                effectsManager = manager;
                if (passDescription.ShaderList != null)
                {
                    foreach (var shader in passDescription.ShaderList)
                    {
                        var s = manager.ShaderManager.RegisterShader(shader);
                        switch (shader.ShaderType)
                        {
                        case ShaderStage.Vertex:
                            vertexShader = s as VertexShader;
                            break;

                        case ShaderStage.Domain:
                            domainShader = s as DomainShader;
                            break;

                        case ShaderStage.Hull:
                            hullShader = s as HullShader;
                            break;

                        case ShaderStage.Geometry:
                            geometryShader = s as GeometryShader;
                            break;

                        case ShaderStage.Pixel:
                            pixelShader = s as PixelShader;
                            break;

                        case ShaderStage.Compute:
                            computeShader = s as ComputeShader;
                            break;
                        }
                    }
                }

                blendState = passDescription.BlendStateDescription != null?
                             manager.StateManager.Register((BlendStateDescription)passDescription.BlendStateDescription) : BlendStateProxy.Empty;

                depthStencilState = passDescription.DepthStencilStateDescription != null?
                                    manager.StateManager.Register((DepthStencilStateDescription)passDescription.DepthStencilStateDescription) : DepthStencilStateProxy.Empty;

                rasterState = passDescription.RasterStateDescription != null?
                              manager.StateManager.Register((RasterizerStateDescription)passDescription.RasterStateDescription) : RasterizerStateProxy.Empty;

                BlendFactor = passDescription.BlendFactor;

                StencilRef = passDescription.StencilRef;

                SampleMask = passDescription.SampleMask;

                Topology = passDescription.Topology;
                if (passDescription.InputLayoutDescription != null)
                {
                    layout = manager.ShaderManager.RegisterInputLayout(passDescription.InputLayoutDescription);
                }
            }
Example #6
0
        public IDomainShader LoadDomainShaderFromFile(string relativePath, string entryPoint = null)
        {
            var bytecode = CompileShaderBytecodeFromFileOrThrow($"{BasePath}\\{relativePath}.hlsl", entryPoint ?? "DS", "ds_5_0");
            var shader   = new DomainShader(_device, bytecode);

            return(new DomainShaderBox {
                Shader = shader
            });
        }
 public ShaderPipelineState(DX11RenderContext renderContext)
 {
     var context = renderContext.CurrentDeviceContext;
     this.VertexShader = context.VertexShader.Get();
     this.HullShader = context.HullShader.Get();
     this.DomainShader = context.DomainShader.Get();
     this.GeometryShader = context.GeometryShader.Get();
     this.PixelShader = context.PixelShader.Get();
 }
Example #8
0
        public ShaderPipelineState(DX11RenderContext renderContext)
        {
            var context = renderContext.CurrentDeviceContext;

            this.VertexShader   = context.VertexShader.Get();
            this.HullShader     = context.HullShader.Get();
            this.DomainShader   = context.DomainShader.Get();
            this.GeometryShader = context.GeometryShader.Get();
            this.PixelShader    = context.PixelShader.Get();
        }
Example #9
0
        private void ResetManagedState()
        {
            _numVertexBindings = 0;
            Util.ClearArray(_vertexBindings);
            _vertexStrides = null;
            Util.ClearArray(_vertexOffsets);

            _framebuffer = null;

            Util.ClearArray(_viewports);
            Util.ClearArray(_scissors);
            _viewportsChanged    = false;
            _scissorRectsChanged = false;

            _ib = null;
            _graphicsPipeline  = null;
            _blendState        = null;
            _depthStencilState = null;
            _rasterizerState   = null;
            _primitiveTopology = SharpDX.Direct3D.PrimitiveTopology.Undefined;
            _inputLayout       = null;
            _vertexShader      = null;
            _geometryShader    = null;
            _hullShader        = null;
            _domainShader      = null;
            _pixelShader       = null;
            Util.ClearArray(_graphicsResourceSets);

            Util.ClearArray(_vertexBoundUniformBuffers);
            Util.ClearArray(_vertexBoundTextureViews);
            Util.ClearArray(_vertexBoundSamplers);

            Util.ClearArray(_fragmentBoundUniformBuffers);
            Util.ClearArray(_fragmentBoundTextureViews);
            Util.ClearArray(_fragmentBoundSamplers);

            _computePipeline = null;
            Util.ClearArray(_computeResourceSets);

            foreach (KeyValuePair <Texture, List <BoundTextureInfo> > kvp in _boundSRVs)
            {
                List <BoundTextureInfo> list = kvp.Value;
                list.Clear();
                PoolBoundTextureList(list);
            }
            _boundSRVs.Clear();

            foreach (KeyValuePair <Texture, List <BoundTextureInfo> > kvp in _boundUAVs)
            {
                List <BoundTextureInfo> list = kvp.Value;
                list.Clear();
                PoolBoundTextureList(list);
            }
            _boundUAVs.Clear();
        }
Example #10
0
 public void SetShader(DomainShader shader, bool bindConstantBuffer = true)
 {
     deviceContext.DomainShader.Set(shader.Shader);
     if (bindConstantBuffer)
     {
         foreach (var buff in shader.ConstantBufferMapping.Mappings)
         {
             deviceContext.DomainShader.SetConstantBuffer(buff.Key, buff.Value.Buffer);
         }
     }
 }
            private void OnBindMaterialTextures(DeviceContextProxy context, DomainShader shader)
            {
                if (shader.IsNULL)
                {
                    return;
                }
                int idx = shader.ShaderStageIndex;

                shader.BindTexture(context, texDisplaceSlot, TextureResources[DisplaceMapIdx]);
                shader.BindSampler(context, samplerDisplaceSlot, SamplerResources[DisplaceSamplerIdx]);
            }
Example #12
0
        public Shader(InputLayout inputLayout, VertexShader vertexShader, HullShader hullShader,
                      DomainShader domainShader,
                      GeometryShader geometryShader, PixelShader pixelShader)
        {
            InputLayout    = inputLayout;
            VertexShader   = vertexShader;
            HullShader     = hullShader;
            DomainShader   = domainShader;
            GeometryShader = geometryShader;
            PixelShader    = pixelShader;

            shaderResourceViews = new Dictionary <int, ShaderResourceView>();
        }
Example #13
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="device">Device</param>
        /// <param name="filename">Path of shader file</param>
        /// <param name="description">Description structure</param>
        /// <param name="elements">Input Layout Elements</param>
        public SharpShader(SharpDevice device, string filename, SharpShaderDescription description, InputElement[] elements)
        {
            Device = device;
            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(filename, description.VertexShaderFunction, "vs_5_0");

            VertexShader = new VertexShader(Device.Device, vertexShaderByteCode);

            //create pixel shader
            if (!string.IsNullOrEmpty(description.PixelShaderFunction))
            {
                var pixelShaderByteCode = ShaderBytecode.CompileFromFile(filename, description.PixelShaderFunction, "ps_5_0");
                PixelShader = new PixelShader(Device.Device, pixelShaderByteCode);
            }

            if (!string.IsNullOrEmpty(description.GeometryShaderFunction))
            {
                var geometryShaderByteCode = ShaderBytecode.CompileFromFile(filename, description.GeometryShaderFunction, "gs_5_0");

                if (description.GeometrySO == null)
                {
                    GeometryShader = new GeometryShader(Device.Device, geometryShaderByteCode);
                }
                else
                {
                    int[] size = new int[] { description.GeometrySO.Select(e => e.ComponentCount * 4).Sum() };

                    GeometryShader = new GeometryShader(Device.Device, geometryShaderByteCode, description.GeometrySO, size, -1);
                }
            }

            if (!string.IsNullOrEmpty(description.DomainShaderFunction))
            {
                var domainShaderByteCode = ShaderBytecode.CompileFromFile(filename, description.DomainShaderFunction, "ds_5_0");
                DomainShader = new DomainShader(Device.Device, domainShaderByteCode);
            }

            if (!string.IsNullOrEmpty(description.HullShaderFunction))
            {
                var hullShaderByteCode = ShaderBytecode.CompileFromFile(filename, description.HullShaderFunction, "hs_5_0");
                HullShader = new HullShader(Device.Device, hullShaderByteCode);
            }

            var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode);

            // Layout from VertexShader input signature
            Layout = new InputLayout(Device.Device, signature, elements);
        }
Example #14
0
 public void SetShader(DomainShader shader, bool bindConstantBuffer = true)
 {
     deviceContext.DomainShader.Set(shader.Shader);
     if (bindConstantBuffer)
     {
         foreach (var buff in shader.ConstantBufferMapping.Mappings)
         {
             int idx = CBCheckDomainShaderStartIdx + buff.Key;
             if (ConstantBufferCheck[idx] != buff.Value)
             {
                 ConstantBufferCheck[idx] = buff.Value;
                 deviceContext.DomainShader.SetConstantBuffer(buff.Key, buff.Value.Buffer);
             }
         }
     }
 }
Example #15
0
        public D3D11Shader(Device device, ShaderDescription description)
            : base(description.Stage)
        {
            if (description.ShaderBytes.Length > 4 &&
                description.ShaderBytes[0] == 0x44 &&
                description.ShaderBytes[1] == 0x58 &&
                description.ShaderBytes[2] == 0x42 &&
                description.ShaderBytes[3] == 0x43)
            {
                Bytecode = Util.ShallowClone(description.ShaderBytes);
            }
            else
            {
                Bytecode = CompileCode(description);
            }

            switch (description.Stage)
            {
            case ShaderStages.Vertex:
                DeviceShader = new VertexShader(device, Bytecode);
                break;

            case ShaderStages.Geometry:
                DeviceShader = new GeometryShader(device, Bytecode);
                break;

            case ShaderStages.TessellationControl:
                DeviceShader = new HullShader(device, Bytecode);
                break;

            case ShaderStages.TessellationEvaluation:
                DeviceShader = new DomainShader(device, Bytecode);
                break;

            case ShaderStages.Fragment:
                DeviceShader = new PixelShader(device, Bytecode);
                break;

            case ShaderStages.Compute:
                DeviceShader = new ComputeShader(device, Bytecode);
                break;

            default:
                throw Illegal.Value <ShaderStages>();
            }
        }
Example #16
0
        public Tesselation(Device dv, int tFactor)
        {
            this.tFactor = tFactor;
            this.World   = Matrix.Identity;
            _dv          = dv;
            _tri         = new Tri(dv);
            _quad        = new Quad(dv);

            _cb = new Buffer(dv, Utilities.SizeOf <TesConst>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

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

            _drawer = new Drawer("Shaders\\Tes.hlsl", inputElements, dv.ImmediateContext);
            var m = _dv.ImmediateContext.LoadTextureFromFile("Textures\\grass.jpg");

            _viewModel.Textures        = new[] { m };
            _viewModel.ConstantBuffers = new[] { _cb };

            ShaderFlags shaderFlags = ShaderFlags.None;

#if DEBUG
            shaderFlags = ShaderFlags.Debug;
#endif
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\Tes.hlsl", "HS", "hs_5_0", shaderFlags))
            {
                _HShader = new HullShader(_dv, pixelShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\Tes.hlsl", "DS", "ds_5_0", shaderFlags))
            {
                _DShader = new DomainShader(_dv, pixelShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\Tes.hlsl", "GS", "gs_5_0", shaderFlags))
            {
                _GShader = new GeometryShader(_dv, pixelShaderByteCode);
            }

            var r = RasterizerStateDescription.Default();
            r.CullMode = CullMode.None;
            r.FillMode = FillMode.Wireframe;
            _drawer.RasterizerDescription = r;
        }
Example #17
0
        public override object ProcessStream(Stream assetStream)
        {
            var graphics = (GraphicsDevice)m_services.GetService(typeof(GraphicsDevice));
            var device   = graphics.Device;

            assetStream.Position = 0;
            var buffer = new byte[assetStream.Length];

            for (int totalBytesCopied = 0; totalBytesCopied < assetStream.Length;)
            {
                totalBytesCopied += assetStream.Read(buffer, totalBytesCopied, Convert.ToInt32(assetStream.Length) - totalBytesCopied);
            }

            var vShader = new DomainShader(device, buffer);

            vShader.Tag = buffer;

            return(vShader);
        }
        /// <summary>
        /// Конструктор класса
        /// </summary>
        /// <param name="dC">Контекст Директ икс 11</param>
        /// <param name="shadersFile">Путь к файлу в которм описанный шейдеры. Назвалине функций шейредов должно быть VS, PS, GS, HS и DS соответственно.</param>
        ///<param name="inputElements">Входные элементы для Вертексного шейдера</param>
        /// <param name="hasGeom">Используеться ли Геометри шейдер GS</param>
        /// <param name="hasTes">Использовать ли Хулл HS и Домейн DS шейдеры необходимые для тесселяции</param>
        public Shader(DeviceContext dC, string shadersFile, SharpDX.Direct3D11.InputElement[] inputElements, bool hasGeom = false, bool hasTes = false)
        {
            _dx11DeviceContext = dC;
            ShaderFlags shaderFlags = ShaderFlags.None;

#if DEBUG
            shaderFlags = ShaderFlags.Debug;
#endif

            using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "VS", "vs_5_0", shaderFlags))
            {
                //Синатура храянящая сведения о том какие входные переменные есть у шейдера
                _inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
                _vertexShader   = new VertexShader(_dx11DeviceContext.Device, vertexShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "PS", "ps_5_0", shaderFlags))
            {
                _pixelShader = new PixelShader(_dx11DeviceContext.Device, pixelShaderByteCode);
            }

            if (hasTes)
            {
                using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "HS", "hs_5_0", shaderFlags))
                {
                    _HShader = new HullShader(_dx11DeviceContext.Device, pixelShaderByteCode);
                }
                using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "DS", "ds_5_0", shaderFlags))
                {
                    _DShader = new DomainShader(_dx11DeviceContext.Device, pixelShaderByteCode);
                }
            }

            if (hasGeom)
            {
                using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "GS", "gs_5_0", shaderFlags))
                {
                    _GShader = new GeometryShader(_dx11DeviceContext.Device, pixelShaderByteCode);
                }
            }

            _inputLayout = new InputLayout(_dx11DeviceContext.Device, _inputSignature, inputElements);
        }
Example #19
0
        /// <summary>
        /// Function clean up any resources within this interface.
        /// </summary>
        internal void CleanUp()
        {
            if (PixelShader != null)
            {
                PixelShader.CleanUp();
            }

            if (VertexShader != null)
            {
                VertexShader.CleanUp();
            }

            if (GeometryShader != null)
            {
                GeometryShader.CleanUp();
            }

            if (ComputeShader != null)
            {
                ComputeShader.CleanUp();
            }

            if (HullShader != null)
            {
                HullShader.CleanUp();
            }

            if (DomainShader != null)
            {
                DomainShader.CleanUp();
            }

            ComputeShader  = null;
            GeometryShader = null;
            PixelShader    = null;
            VertexShader   = null;
        }
Example #20
0
        private Shader(GraphicsDevice device, ShaderStage shaderStage, byte[] shaderBytecode)
            : base(device)
        {
            this.stage = shaderStage;

            switch (shaderStage)
            {
            case ShaderStage.Vertex:
                NativeDeviceChild    = new VertexShader(device.NativeDevice, shaderBytecode);
                NativeInputSignature = shaderBytecode;
                break;

            case ShaderStage.Hull:
                NativeDeviceChild = new HullShader(device.NativeDevice, shaderBytecode);
                break;

            case ShaderStage.Domain:
                NativeDeviceChild = new DomainShader(device.NativeDevice, shaderBytecode);
                break;

            case ShaderStage.Geometry:
                NativeDeviceChild = new GeometryShader(device.NativeDevice, shaderBytecode);
                break;

            case ShaderStage.Pixel:
                NativeDeviceChild = new PixelShader(device.NativeDevice, shaderBytecode);
                break;

            case ShaderStage.Compute:
                NativeDeviceChild = new ComputeShader(device.NativeDevice, shaderBytecode);
                break;

            default:
                throw new ArgumentOutOfRangeException("shaderStage");
            }
        }
Example #21
0
        private void ResetManagedState()
        {
            _numVertexBindings = 0;
            Util.ClearArray(_vertexBindings);
            _vertexStrides = null;
            Util.ClearArray(_vertexOffsets);

            _fb = null;

            Util.ClearArray(_viewports);
            Util.ClearArray(_scissors);
            _viewportsChanged    = false;
            _scissorRectsChanged = false;

            _ib                = null;
            _pipeline          = null;
            _blendState        = null;
            _depthStencilState = null;
            _rasterizerState   = null;
            _primitiveTopology = SharpDX.Direct3D.PrimitiveTopology.Undefined;
            _inputLayout       = null;
            _vertexShader      = null;
            _geometryShader    = null;
            _hullShader        = null;
            _domainShader      = null;
            _pixelShader       = null;
            Util.ClearArray(_resourceSets);

            Util.ClearArray(_vertexBoundUniformBuffers);
            Util.ClearArray(_vertexBoundTextureViews);
            Util.ClearArray(_vertexBoundSamplers);

            Util.ClearArray(_fragmentBoundUniformBuffers);
            Util.ClearArray(_fragmentBoundTextureViews);
            Util.ClearArray(_fragmentBoundSamplers);
        }
 private void ShuddownShader()
 {
     // Release the tessellation constant buffer.
     ConstantTessellationBuffer?.Dispose();
     ConstantTessellationBuffer = null;
     // Release the matrix constant buffer.
     ConstantMatrixBuffer?.Dispose();
     ConstantMatrixBuffer = null;
     // Release the layout.
     Layout?.Dispose();
     Layout = null;
     // Release the Vertex shader.
     VertexShader?.Dispose();
     VertexShader = null;
     // Release the Hull shader.
     PixelShader?.Dispose();
     PixelShader = null;
     // Release the Domain shader.
     HullShader?.Dispose();
     HullShader = null;
     // Release the Pixel shader.
     DomainShader?.Dispose();
     DomainShader = null;
 }
Example #23
0
        public DomainShader GetDomainShader( string bytecode )
        {
            DomainShader	shader;

            if (!dsDictionary.TryGetValue( bytecode, out shader ) ) {
                shader = new DomainShader( device, bytecode );
                dsDictionary.Add( bytecode, shader );
            }

            return shader;
        }
Example #24
0
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);

            RemoveAndDispose(ref pixelShader);
            RemoveAndDispose(ref depthPixelShader);
            RemoveAndDispose(ref lambertShader);
            RemoveAndDispose(ref blinnPhongShader);
            RemoveAndDispose(ref phongShader);

            RemoveAndDispose(ref tessellateVertexShader);
            RemoveAndDispose(ref tessellateTriIntegerShader);
            RemoveAndDispose(ref tessellateTriPow2Shader);
            RemoveAndDispose(ref tessellateTriFractionalEvenShader);
            RemoveAndDispose(ref tessellateTriFractionalOddShader);
            RemoveAndDispose(ref tessellateTriDomainShader);

            RemoveAndDispose(ref tessellateQuadIntegerShader);
            RemoveAndDispose(ref tessellateQuadPow2Shader);
            RemoveAndDispose(ref tessellateQuadFractionalEvenShader);
            RemoveAndDispose(ref tessellateQuadFractionalOddShader);
            RemoveAndDispose(ref tessellateQuadDomainShader);

            RemoveAndDispose(ref tessellateBezierIntegerShader);
            RemoveAndDispose(ref tessellateBezierPow2Shader);
            RemoveAndDispose(ref tessellateBezierFractionalEvenShader);
            RemoveAndDispose(ref tessellateBezierFractionalOddShader);
            RemoveAndDispose(ref tessellateBezierDomainShader);

            RemoveAndDispose(ref tessellateParametricIntegerShader);
            RemoveAndDispose(ref tessellateParametricPow2Shader);
            RemoveAndDispose(ref tessellateParametricFractionalEvenShader);
            RemoveAndDispose(ref tessellateParametricFractionalOddShader);
            RemoveAndDispose(ref tessellateParametricDomainShader);

            RemoveAndDispose(ref debugNormals);

            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref perObjectBuffer);
            RemoveAndDispose(ref perFrameBuffer);
            RemoveAndDispose(ref perMaterialBuffer);
            RemoveAndDispose(ref perArmatureBuffer);

            RemoveAndDispose(ref depthStencilState);

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


            // Compile and create the vertex shader and input layout
            using (var vertexShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
                using (var vertexTessBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSPassThruTessellate", "vs_5_0"))
                {
                    vertexShader           = ToDispose(new VertexShader(device, vertexShaderBytecode));
                    tessellateVertexShader = ToDispose(new VertexShader(device, vertexTessBytecode));

                    // Layout from VertexShader input signature
                    vertexLayout = ToDispose(new InputLayout(device,
                                                             vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                                                             new[]
                    {
                        // "SV_Position" = vertex coordinate in object space
                        new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                        // "NORMAL" = the vertex normal
                        new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                        // "COLOR"
                        new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0),
                        // "UV"
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0),
                        // "BLENDINDICES"
                        new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0),
                        // "BLENDWEIGHT"
                        new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0),
                    }));
                }

            // Compile and create the pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0"))
                pixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the depth vertex and pixel shaders
            // This shader is for checking what the depth buffer would look like
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DepthPS.hlsl", "PSMain", "ps_5_0"))
                depthPixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DiffusePS.hlsl", "PSMain", "ps_5_0"))
                lambertShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\BlinnPhongPS.hlsl", "PSMain", "ps_5_0"))
                blinnPhongShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\PhongPS.hlsl", "PSMain", "ps_5_0"))
                phongShader = ToDispose(new PixelShader(device, bytecode));

            #region Tessellation Shaders

            using (var integer = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesInteger", "hs_5_0", null))
                using (var pow2 = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesPow2", "hs_5_0", null))
                    using (var fracEven = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesFractionalEven", "hs_5_0", null))
                        using (var fracOdd = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesFractionalOdd", "hs_5_0", null))
                            using (var domain = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "DS_Triangles", "ds_5_0", null))
                            {
                                tessellateTriIntegerShader        = ToDispose(new HullShader(device, integer));
                                tessellateTriPow2Shader           = ToDispose(new HullShader(device, pow2));
                                tessellateTriFractionalEvenShader = ToDispose(new HullShader(device, fracEven));
                                tessellateTriFractionalOddShader  = ToDispose(new HullShader(device, fracOdd));
                                tessellateTriDomainShader         = ToDispose(new DomainShader(device, domain));
                            }
            using (var quadIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateQuad.hlsl", "HS_QuadsInteger", "hs_5_0", null))
                using (var quadPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateQuad.hlsl", "HS_QuadsPow2", "hs_5_0", null))
                    using (var quadFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateQuad.hlsl", "HS_QuadsFractionalEven", "hs_5_0", null))
                        using (var quadFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateQuad.hlsl", "HS_QuadsFractionalOdd", "hs_5_0", null))
                            using (var quadDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateQuad.hlsl", "DS_Quads", "ds_5_0", null))
                            {
                                tessellateQuadIntegerShader        = ToDispose(new HullShader(device, quadIntegerBytecode));
                                tessellateQuadPow2Shader           = ToDispose(new HullShader(device, quadPow2Bytecode));
                                tessellateQuadFractionalEvenShader = ToDispose(new HullShader(device, quadFractionalEvenBytecode));
                                tessellateQuadFractionalOddShader  = ToDispose(new HullShader(device, quadFractionalOddBytecode));
                                tessellateQuadDomainShader         = ToDispose(new DomainShader(device, quadDomainShaderBytecode));
                            }
            using (var bezierIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateBezier.hlsl", "HS_BezierInteger", "hs_5_0", null))
                using (var bezierPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateBezier.hlsl", "HS_BezierPow2", "hs_5_0", null))
                    using (var bezierFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateBezier.hlsl", "HS_BezierFractionalEven", "hs_5_0", null))
                        using (var bezierFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateBezier.hlsl", "HS_BezierFractionalOdd", "hs_5_0", null))
                            using (var bezierDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateBezier.hlsl", "DS_Bezier", "ds_5_0", null))
                            {
                                tessellateBezierIntegerShader        = ToDispose(new HullShader(device, bezierIntegerBytecode));
                                tessellateBezierPow2Shader           = ToDispose(new HullShader(device, bezierPow2Bytecode));
                                tessellateBezierFractionalEvenShader = ToDispose(new HullShader(device, bezierFractionalEvenBytecode));
                                tessellateBezierFractionalOddShader  = ToDispose(new HullShader(device, bezierFractionalOddBytecode));
                                tessellateBezierDomainShader         = ToDispose(new DomainShader(device, bezierDomainShaderBytecode));
                            }

            using (var parametricIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateParametric.hlsl", "HS_ParametricInteger", "hs_5_0", null))
                using (var parametricPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateParametric.hlsl", "HS_ParametricPow2", "hs_5_0", null))
                    using (var parametricFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateParametric.hlsl", "HS_ParametricFractionalEven", "hs_5_0", null))
                        using (var parametricFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateParametric.hlsl", "HS_ParametricFractionalOdd", "hs_5_0", null))
                            using (var parametricDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateParametric.hlsl", "DS_Parametric", "ds_5_0", null))
                            {
                                tessellateParametricIntegerShader        = ToDispose(new HullShader(device, parametricIntegerBytecode));
                                tessellateParametricPow2Shader           = ToDispose(new HullShader(device, parametricPow2Bytecode));
                                tessellateParametricFractionalEvenShader = ToDispose(new HullShader(device, parametricFractionalEvenBytecode));
                                tessellateParametricFractionalOddShader  = ToDispose(new HullShader(device, parametricFractionalOddBytecode));
                                tessellateParametricDomainShader         = ToDispose(new DomainShader(device, parametricDomainShaderBytecode));
                            }

            using (var geomShaderByteCode = HLSLCompiler.CompileFromFile(@"Shaders\GS_DebugNormals.hlsl", "GSMain", "gs_5_0", null))
            {
                debugNormals = ToDispose(new GeometryShader(device, geomShaderByteCode));
            }

            #endregion


            // IMPORTANT: A constant buffer's size must be a multiple of 16-bytes
            // use LayoutKind.Explicit and an explicit Size= to force this for structures
            // or alternatively add padding fields and use a LayoutKind.Sequential and Pack=1

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

            // Create the per frame constant buffer
            // lighting / camera position
            perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per material constant buffer
            perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per armature/skeletong constant buffer
            perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), 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
            context.InputAssembler.InputLayout = vertexLayout;

            // Set our constant buffer (to store worldViewProjection)
            context.VertexShader.SetConstantBuffer(0, perObjectBuffer);
            context.VertexShader.SetConstantBuffer(1, perFrameBuffer);
            context.VertexShader.SetConstantBuffer(2, perMaterialBuffer);
            context.VertexShader.SetConstantBuffer(3, perArmatureBuffer);

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

            // Set our hull/domain shader constant buffers
            context.HullShader.SetConstantBuffer(0, perObjectBuffer);
            context.HullShader.SetConstantBuffer(1, perFrameBuffer);
            context.DomainShader.SetConstantBuffer(0, perObjectBuffer);
            context.DomainShader.SetConstantBuffer(1, perFrameBuffer);

            // Set gemoetry shader buffers
            context.GeometryShader.SetConstantBuffer(0, perObjectBuffer);
            context.GeometryShader.SetConstantBuffer(1, perFrameBuffer);

            // Set our pixel constant buffers
            context.PixelShader.SetConstantBuffer(1, perFrameBuffer);
            context.PixelShader.SetConstantBuffer(2, perMaterialBuffer);

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

            // Set our depth stencil state
            context.OutputMerger.DepthStencilState = depthStencilState;

            // Back-face culling
            context.Rasterizer.State = ToDispose(new RasterizerState(device, new RasterizerStateDescription()
            {
                FillMode = FillMode.Wireframe,
                CullMode = CullMode.Back,
            }));
        }
Example #25
0
        public override void SetPipeline(Pipeline pipeline)
        {
            if (_pipeline != pipeline)
            {
                D3D11Pipeline d3dPipeline = Util.AssertSubtype <Pipeline, D3D11Pipeline>(pipeline);
                _pipeline = d3dPipeline;
                Util.ClearArray(_resourceSets); // Invalidate resource set bindings -- they may be invalid.

                BlendState blendState = d3dPipeline.BlendState;
                if (_blendState != blendState)
                {
                    _blendState = blendState;
                    _context.OutputMerger.SetBlendState(blendState);
                }

                DepthStencilState depthStencilState = d3dPipeline.DepthStencilState;
                if (_depthStencilState != depthStencilState)
                {
                    _depthStencilState = depthStencilState;
                    _context.OutputMerger.SetDepthStencilState(depthStencilState);
                }

                RasterizerState rasterizerState = d3dPipeline.RasterizerState;
                if (_rasterizerState != rasterizerState)
                {
                    _rasterizerState          = rasterizerState;
                    _context.Rasterizer.State = rasterizerState;
                }

                SharpDX.Direct3D.PrimitiveTopology primitiveTopology = d3dPipeline.PrimitiveTopology;
                if (_primitiveTopology != primitiveTopology)
                {
                    _primitiveTopology = primitiveTopology;
                    _context.InputAssembler.PrimitiveTopology = primitiveTopology;
                }

                InputLayout inputLayout = d3dPipeline.InputLayout;
                if (_inputLayout != inputLayout)
                {
                    _inputLayout = inputLayout;
                    _context.InputAssembler.InputLayout = inputLayout;
                }

                VertexShader vertexShader = d3dPipeline.VertexShader;
                if (_vertexShader != vertexShader)
                {
                    _vertexShader = vertexShader;
                    _context.VertexShader.Set(vertexShader);
                }

                GeometryShader geometryShader = d3dPipeline.GeometryShader;
                if (_geometryShader != geometryShader)
                {
                    _geometryShader = geometryShader;
                    _context.GeometryShader.Set(geometryShader);
                }

                HullShader hullShader = d3dPipeline.HullShader;
                if (_hullShader != hullShader)
                {
                    _hullShader = hullShader;
                    _context.HullShader.Set(hullShader);
                }

                DomainShader domainShader = d3dPipeline.DomainShader;
                if (_domainShader != domainShader)
                {
                    _domainShader = domainShader;
                    _context.DomainShader.Set(domainShader);
                }

                PixelShader pixelShader = d3dPipeline.PixelShader;
                if (_pixelShader != pixelShader)
                {
                    _pixelShader = pixelShader;
                    _context.PixelShader.Set(pixelShader);
                }

                _vertexStrides = d3dPipeline.VertexStrides;
                int vertexStridesCount = _vertexStrides.Length;
                Util.EnsureArraySize(ref _vertexBindings, (uint)vertexStridesCount);
                Util.EnsureArraySize(ref _vertexOffsets, (uint)vertexStridesCount);

                Util.EnsureArraySize(ref _resourceSets, (uint)d3dPipeline.ResourceLayouts.Length);
            }
        }
Example #26
0
        /// <summary>
        /// Compiles files into shader byte-code and creates a shader from the shader files that exist
        /// </summary>
        /// <param name="folderPath"></param>
        public static Shader CompileFromFiles(string folderPath)
        {
            // TODO simplify method with a loop
            // TODO build shaders on program build with dxc

            ShaderFlags shaderFlags = ShaderFlags.Debug;

            InputLayout    inputLayout    = null;
            VertexShader   vertexShader   = null;
            HullShader     hullShader     = null;
            DomainShader   domainShader   = null;
            GeometryShader geometryShader = null;
            PixelShader    pixelShader    = null;

            // Handler for #include directive
            HLSLFileIncludeHandler includeHandler = new HLSLFileIncludeHandler(folderPath);

            // Vertex shader + Shader signature
            {
                string path = Path.Combine(folderPath, "Vertex.hlsl");

                if (File.Exists(path))
                {
                    CompilationResult byteCode = ShaderBytecode.CompileFromFile(path, "main", "vs_5_0", shaderFlags,
                                                                                EffectFlags.None, null, includeHandler);
                    vertexShader = new VertexShader(Engine.RenderDevice.device, byteCode);

                    ShaderSignature inputSignature = ShaderSignature.GetInputSignature(byteCode);
                    inputLayout = new InputLayout(Engine.RenderDevice.device, inputSignature,
                                                  RenderVertex.InputElements);
                }
                else
                {
                    // TODO fail
                }
            }

            // Hull shader
            {
                string path = Path.Combine(folderPath, "Hull.hlsl");

                if (File.Exists(path))
                {
                    CompilationResult byteCode = ShaderBytecode.CompileFromFile(path, "main", "hs_5_0", shaderFlags,
                                                                                EffectFlags.None, null, includeHandler);
                    hullShader = new HullShader(Engine.RenderDevice.device, byteCode);
                }
            }

            // Domain shader
            {
                string path = Path.Combine(folderPath, "Domain.hlsl");

                if (File.Exists(path))
                {
                    CompilationResult byteCode = ShaderBytecode.CompileFromFile(path, "main", "ds_5_0", shaderFlags,
                                                                                EffectFlags.None, null, includeHandler);
                    domainShader = new DomainShader(Engine.RenderDevice.device, byteCode);
                }
            }

            // Geometry shader
            {
                string path = Path.Combine(folderPath, "Geometry.hlsl");

                if (File.Exists(path))
                {
                    CompilationResult byteCode = ShaderBytecode.CompileFromFile(path, "main", "gs_5_0", shaderFlags,
                                                                                EffectFlags.None, null, includeHandler);
                    geometryShader = new GeometryShader(Engine.RenderDevice.device, byteCode);
                }
            }

            // Pixel shader
            {
                string path = Path.Combine(folderPath, "Pixel.hlsl");

                if (File.Exists(path))
                {
                    CompilationResult byteCode = ShaderBytecode.CompileFromFile(path, "main", "ps_5_0", shaderFlags,
                                                                                EffectFlags.None, null, includeHandler);
                    pixelShader = new PixelShader(Engine.RenderDevice.device, byteCode);
                }
            }

            return(new Shader(inputLayout, vertexShader, hullShader, domainShader, geometryShader, pixelShader));
        }
Example #27
0
 /// <summary>
 /// Sets the shader.
 /// </summary>
 /// <param name="shader">The shader.</param>
 public void SetShader(DomainShader shader)
 {
     DomainShader = shader;
 }
Example #28
0
        /// <summary>
        /// Create Shader.
        /// <para>All constant buffers for all shaders are created here./></para>
        /// </summary>
        /// <param name="device"></param>
        /// <param name="pool"></param>
        /// <returns></returns>
        public ShaderBase CreateShader(Device device, IConstantBufferPool pool)
        {
            if (ByteCode == null)
            {
                return(null);
            }
            if (shaderReflector != null)
            {
                shaderReflector.Parse(ByteCode, ShaderType);
                Level = shaderReflector.FeatureLevel;
                if (Level > device.FeatureLevel)
                {
                    throw new Exception($"Shader {this.Name} requires FeatureLevel {Level}. Current device only supports FeatureLevel {device.FeatureLevel} and below.");
                }
                this.ConstantBufferMappings = shaderReflector.ConstantBufferMappings.Values.ToArray();
                this.TextureMappings        = shaderReflector.TextureMappings.Values.ToArray();
                this.UAVMappings            = shaderReflector.UAVMappings.Values.ToArray();
                this.SamplerMappings        = shaderReflector.SamplerMappings.Values.ToArray();
            }
            ShaderBase shader = null;

            switch (ShaderType)
            {
            case ShaderStage.Vertex:
                shader = new VertexShader(device, Name, ByteCode);
                break;

            case ShaderStage.Pixel:
                shader = new PixelShader(device, Name, ByteCode);
                break;

            case ShaderStage.Compute:
                shader = new ComputeShader(device, Name, ByteCode);
                break;

            case ShaderStage.Domain:
                shader = new DomainShader(device, Name, ByteCode);
                break;

            case ShaderStage.Hull:
                shader = new HullShader(device, Name, ByteCode);
                break;

            case ShaderStage.Geometry:
                shader = new GeometryShader(device, Name, ByteCode);
                break;

            default:
                shader = NullShader.GetNullShader(ShaderType);
                break;
            }
            if (ConstantBufferMappings != null)
            {
                foreach (var mapping in ConstantBufferMappings)
                {
                    shader.ConstantBufferMapping.AddMapping(mapping.Description.Name, mapping.Slot, pool.Register(mapping.Description));
                }
            }
            if (TextureMappings != null)
            {
                foreach (var mapping in TextureMappings)
                {
                    shader.ShaderResourceViewMapping.AddMapping(mapping.Description.Name, mapping.Slot, mapping);
                }
            }
            if (UAVMappings != null)
            {
                foreach (var mapping in UAVMappings)
                {
                    shader.UnorderedAccessViewMapping.AddMapping(mapping.Description.Name, mapping.Slot, mapping);
                }
            }
            if (SamplerMappings != null)
            {
                foreach (var mapping in SamplerMappings)
                {
                    shader.SamplerMapping.AddMapping(mapping.Name, mapping.Slot, mapping);
                }
            }
            return(shader);
        }
Example #29
0
        internal DeviceChild GetOrCompileShader(EffectShaderType shaderType, int index, int soRasterizedStream, StreamOutputElement[] soElements, out string profileError)
        {
            DeviceChild shader = null;

            profileError = null;
            lock (sync)
            {
                shader = compiledShadersGroup[(int)shaderType][index];
                if (shader == null)
                {
                    if (RegisteredShaders[index].Level > graphicsDevice.Features.Level)
                    {
                        profileError = string.Format("{0}", RegisteredShaders[index].Level);
                        return(null);
                    }

                    var bytecodeRaw = RegisteredShaders[index].Bytecode;
                    switch (shaderType)
                    {
                    case EffectShaderType.Vertex:
                        shader = new VertexShader(graphicsDevice, bytecodeRaw);
                        break;

                    case EffectShaderType.Domain:
                        shader = new DomainShader(graphicsDevice, bytecodeRaw);
                        break;

                    case EffectShaderType.Hull:
                        shader = new HullShader(graphicsDevice, bytecodeRaw);
                        break;

                    case EffectShaderType.Geometry:
                        if (soElements != null)
                        {
                            // Calculate the strides
                            var soStrides = new List <int>();
                            foreach (var streamOutputElement in soElements)
                            {
                                for (int i = soStrides.Count; i < (streamOutputElement.Stream + 1); i++)
                                {
                                    soStrides.Add(0);
                                }

                                soStrides[streamOutputElement.Stream] += streamOutputElement.ComponentCount * sizeof(float);
                            }
                            shader = new GeometryShader(graphicsDevice, bytecodeRaw, soElements, soStrides.ToArray(), soRasterizedStream);
                        }
                        else
                        {
                            shader = new GeometryShader(graphicsDevice, bytecodeRaw);
                        }
                        break;

                    case EffectShaderType.Pixel:
                        shader = new PixelShader(graphicsDevice, bytecodeRaw);
                        break;

                    case EffectShaderType.Compute:
                        shader = new ComputeShader(graphicsDevice, bytecodeRaw);
                        break;
                    }
                    compiledShadersGroup[(int)shaderType][index] = ToDispose(shader);
                }
            }
            return(shader);
        }
Example #30
0
        private void CreateShaders()
        {
            foreach (var shaderBytecode in effectBytecode.Stages)
            {
                var bytecodeRaw = shaderBytecode.Data;
                var reflection  = effectBytecode.Reflection;

                // TODO CACHE Shaders with a bytecode hash
                switch (shaderBytecode.Stage)
                {
                case ShaderStage.Vertex:
                    vertexShader = new VertexShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                    // Note: input signature can be reused when reseting device since it only stores non-GPU data,
                    // so just keep it if it has already been created before.
                    if (inputSignature == null)
                    {
                        inputSignature = EffectInputSignature.GetOrCreateLayout(new EffectInputSignature(shaderBytecode.Id, bytecodeRaw));
                    }
                    break;

                case ShaderStage.Domain:
                    domainShader = new DomainShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                    break;

                case ShaderStage.Hull:
                    hullShader = new HullShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                    break;

                case ShaderStage.Geometry:
                    if (reflection.ShaderStreamOutputDeclarations != null && reflection.ShaderStreamOutputDeclarations.Count > 0)
                    {
                        // Calculate the strides
                        var soStrides = new List <int>();
                        foreach (var streamOutputElement in reflection.ShaderStreamOutputDeclarations)
                        {
                            for (int i = soStrides.Count; i < (streamOutputElement.Stream + 1); i++)
                            {
                                soStrides.Add(0);
                            }

                            soStrides[streamOutputElement.Stream] += streamOutputElement.ComponentCount * sizeof(float);
                        }
                        var soElements = new StreamOutputElement[0];     // TODO CREATE StreamOutputElement from bytecode.Reflection.ShaderStreamOutputDeclarations
                        geometryShader = new GeometryShader(GraphicsDevice.NativeDevice, bytecodeRaw, soElements, soStrides.ToArray(), reflection.StreamOutputRasterizedStream);
                    }
                    else
                    {
                        geometryShader = new GeometryShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                    }
                    break;

                case ShaderStage.Pixel:
                    pixelShader = new PixelShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                    break;

                case ShaderStage.Compute:
                    computeShader = new ComputeShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                    break;
                }
            }
        }
            /// <summary>
            /// Create Shader.
            /// <para>All constant buffers for all shaders are created here./></para>
            /// </summary>
            /// <param name="device"></param>
            /// <param name="pool"></param>
            /// <param name="logger"></param>
            /// <returns></returns>
            public ShaderBase CreateShader(Device device, IConstantBufferPool pool, LogWrapper logger)
            {
                if (ByteCode == null)
                {
                    return(null);
                }
                ShaderReflector = ShaderReflector ?? new ShaderReflector();
                ShaderReflector.Parse(ByteCode, ShaderType);
                Level = ShaderReflector.FeatureLevel;
                if (Level > device.FeatureLevel)
                {
                    logger?.Log(LogLevel.Warning, $"Shader {this.Name} requires FeatureLevel {Level}. Current device only supports FeatureLevel {device.FeatureLevel} and below.");
                    return(null);
                    //throw new Exception($"Shader {this.Name} requires FeatureLevel {Level}. Current device only supports FeatureLevel {device.FeatureLevel} and below.");
                }
                this.ConstantBufferMappings = ShaderReflector.ConstantBufferMappings.Values.ToArray();
                this.TextureMappings        = ShaderReflector.TextureMappings.Values.ToArray();
                this.UAVMappings            = ShaderReflector.UAVMappings.Values.ToArray();
                this.SamplerMappings        = ShaderReflector.SamplerMappings.Values.ToArray();

                ShaderBase shader = null;

                switch (ShaderType)
                {
                case ShaderStage.Vertex:
                    shader = new VertexShader(device, Name, ByteCode);
                    break;

                case ShaderStage.Pixel:
                    shader = new PixelShader(device, Name, ByteCode);
                    break;

                case ShaderStage.Compute:
                    shader = new ComputeShader(device, Name, ByteCode);
                    break;

                case ShaderStage.Domain:
                    shader = new DomainShader(device, Name, ByteCode);
                    break;

                case ShaderStage.Hull:
                    shader = new HullShader(device, Name, ByteCode);
                    break;

                case ShaderStage.Geometry:
                    if (IsGSStreamOut)
                    {
                        shader = new GeometryShader(device, Name, ByteCode, GSSOElement, GSSOStrides, GSSORasterized);
                    }
                    else
                    {
                        shader = new GeometryShader(device, Name, ByteCode);
                    }
                    break;

                default:
                    break;
                }
                if (ConstantBufferMappings != null)
                {
                    foreach (var mapping in ConstantBufferMappings)
                    {
                        shader.ConstantBufferMapping.AddMapping(mapping.Description.Name, mapping.Slot, pool.Register(mapping.Description));
                    }
                }
                if (TextureMappings != null)
                {
                    foreach (var mapping in TextureMappings)
                    {
                        shader.ShaderResourceViewMapping.AddMapping(mapping.Description.Name, mapping.Slot, mapping);
                    }
                }
                if (UAVMappings != null)
                {
                    foreach (var mapping in UAVMappings)
                    {
                        shader.UnorderedAccessViewMapping.AddMapping(mapping.Description.Name, mapping.Slot, mapping);
                    }
                }
                if (SamplerMappings != null)
                {
                    foreach (var mapping in SamplerMappings)
                    {
                        shader.SamplerMapping.AddMapping(mapping.Name, mapping.Slot, mapping);
                    }
                }
                return(shader);
            }
Example #32
0
        protected override void SetPipelineCore(Pipeline pipeline)
        {
            if (!pipeline.IsComputePipeline && _graphicsPipeline != pipeline)
            {
                D3D11Pipeline d3dPipeline = Util.AssertSubtype <Pipeline, D3D11Pipeline>(pipeline);
                _graphicsPipeline = d3dPipeline;
                Util.ClearArray(_graphicsResourceSets); // Invalidate resource set bindings -- they may be invalid.
                Util.ClearArray(_invalidatedGraphicsResourceSets);

                BlendState blendState = d3dPipeline.BlendState;
                if (_blendState != blendState)
                {
                    _blendState = blendState;
                    _context.OutputMerger.SetBlendState(blendState);
                }

                DepthStencilState depthStencilState = d3dPipeline.DepthStencilState;
                uint stencilReference = d3dPipeline.StencilReference;
                if (_depthStencilState != depthStencilState || _stencilReference != stencilReference)
                {
                    _depthStencilState = depthStencilState;
                    _stencilReference  = stencilReference;
                    _context.OutputMerger.SetDepthStencilState(depthStencilState, (int)stencilReference);
                }

                RasterizerState rasterizerState = d3dPipeline.RasterizerState;
                if (_rasterizerState != rasterizerState)
                {
                    _rasterizerState          = rasterizerState;
                    _context.Rasterizer.State = rasterizerState;
                }

                SharpDX.Direct3D.PrimitiveTopology primitiveTopology = d3dPipeline.PrimitiveTopology;
                if (_primitiveTopology != primitiveTopology)
                {
                    _primitiveTopology = primitiveTopology;
                    _context.InputAssembler.PrimitiveTopology = primitiveTopology;
                }

                InputLayout inputLayout = d3dPipeline.InputLayout;
                if (_inputLayout != inputLayout)
                {
                    _inputLayout = inputLayout;
                    _context.InputAssembler.InputLayout = inputLayout;
                }

                VertexShader vertexShader = d3dPipeline.VertexShader;
                if (_vertexShader != vertexShader)
                {
                    _vertexShader = vertexShader;
                    _context.VertexShader.Set(vertexShader);
                }

                GeometryShader geometryShader = d3dPipeline.GeometryShader;
                if (_geometryShader != geometryShader)
                {
                    _geometryShader = geometryShader;
                    _context.GeometryShader.Set(geometryShader);
                }

                HullShader hullShader = d3dPipeline.HullShader;
                if (_hullShader != hullShader)
                {
                    _hullShader = hullShader;
                    _context.HullShader.Set(hullShader);
                }

                DomainShader domainShader = d3dPipeline.DomainShader;
                if (_domainShader != domainShader)
                {
                    _domainShader = domainShader;
                    _context.DomainShader.Set(domainShader);
                }

                PixelShader pixelShader = d3dPipeline.PixelShader;
                if (_pixelShader != pixelShader)
                {
                    _pixelShader = pixelShader;
                    _context.PixelShader.Set(pixelShader);
                }

                _vertexStrides = d3dPipeline.VertexStrides;
                if (_vertexStrides != null)
                {
                    int vertexStridesCount = _vertexStrides.Length;
                    Util.EnsureArrayMinimumSize(ref _vertexBindings, (uint)vertexStridesCount);
                    Util.EnsureArrayMinimumSize(ref _vertexOffsets, (uint)vertexStridesCount);
                }

                Util.EnsureArrayMinimumSize(ref _graphicsResourceSets, (uint)d3dPipeline.ResourceLayouts.Length);
                Util.EnsureArrayMinimumSize(ref _invalidatedGraphicsResourceSets, (uint)d3dPipeline.ResourceLayouts.Length);
            }
            else if (pipeline.IsComputePipeline && _computePipeline != pipeline)
            {
                D3D11Pipeline d3dPipeline = Util.AssertSubtype <Pipeline, D3D11Pipeline>(pipeline);
                _computePipeline = d3dPipeline;
                Util.ClearArray(_computeResourceSets); // Invalidate resource set bindings -- they may be invalid.
                Util.ClearArray(_invalidatedComputeResourceSets);

                ComputeShader computeShader = d3dPipeline.ComputeShader;
                _context.ComputeShader.Set(computeShader);
                Util.EnsureArrayMinimumSize(ref _computeResourceSets, (uint)d3dPipeline.ResourceLayouts.Length);
                Util.EnsureArrayMinimumSize(ref _invalidatedComputeResourceSets, (uint)d3dPipeline.ResourceLayouts.Length);
            }
        }