예제 #1
0
        public DepthStencilState(bool depthEnabled, bool stencilEnabled, Comparison depthComparison,
            Comparison frontFaceComparison, StencilOperation frontFaceDepthFailOp, StencilOperation frontFaceFailOp, StencilOperation frontFacePassOp,
            Comparison backFaceComparison, StencilOperation backFaceDepthFailOp, StencilOperation backFaceFailOp, StencilOperation backFacePassOp)
        {

            DepthStencilStateDescription desc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = depthEnabled,
                IsStencilEnabled = stencilEnabled,
                DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All,
                FrontFace = new DepthStencilOperationDescription()
                {
                    Comparison = frontFaceComparison,
                    DepthFailOperation = frontFaceDepthFailOp,
                    FailOperation = frontFaceFailOp,
                    PassOperation = frontFacePassOp
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison = backFaceComparison,
                    DepthFailOperation = backFaceDepthFailOp,
                    FailOperation = backFaceFailOp,
                    PassOperation = backFacePassOp
                },
                DepthComparison = depthComparison
            };

            NativeDepthStencilState = new SharpDX.Direct3D11.DepthStencilState(GraphicManager.Device, desc);

        }
예제 #2
0
        internal void Clear()
        {
            m_deviceContext.ClearState();

            m_inputLayout = null;
            m_primitiveTopology = PrimitiveTopology.Undefined;
            m_indexBufferRef = null;
            m_indexBufferFormat = 0;
            m_indexBufferOffset = 0;
            for (int i = 0; i < m_vertexBuffers.Length; i++)
                m_vertexBuffers[i] = null;
            for (int i = 0; i < m_vertexBuffersStrides.Length; i++)
                m_vertexBuffersStrides[i] = 0;

            m_blendState = null;
            m_stencilRef = 0;
            m_depthStencilState = null;
            m_rtvsCount = 0;
            for (int i = 0; i < m_rtvs.Length; i++)
                m_rtvs[i] = null;
            m_dsv = null;

            m_rasterizerState = null;
            m_scissorLeftTop = new Vector2I(-1, -1);
            m_scissorRightBottom = new Vector2I(-1, -1);
            m_viewport = default(RawViewportF);

            m_targetBuffer = null;
            m_targetOffsets = 0;

            m_statistics.ClearStates++;
        }
예제 #3
0
            public DepthStencilStatesStruct(D3D.Device device)
            {
                D3D.DepthStencilStateDescription desc = new D3D.DepthStencilStateDescription()
                {
                    IsDepthEnabled  = true,
                    DepthWriteMask  = D3D.DepthWriteMask.All,
                    DepthComparison = D3D.Comparison.Less,

                    IsStencilEnabled = false,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,

                    FrontFace = new D3D.DepthStencilOperationDescription()
                    {
                        FailOperation      = D3D.StencilOperation.Keep,
                        DepthFailOperation = D3D.StencilOperation.Increment,
                        PassOperation      = D3D.StencilOperation.Keep,
                        Comparison         = D3D.Comparison.Always
                    },

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

                Enabled               = new D3D.DepthStencilState(device, desc);
                desc.IsDepthEnabled   = false;
                desc.IsStencilEnabled = false;
                Disabled              = new D3D.DepthStencilState(device, desc);
            }
예제 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="device"></param>
        internal void Apply(GraphicsDevice device)
        {
            if (state == null)
            {
                var dss = new DepthStencilStateDescription();

                dss.DepthComparison  = Converter.Convert(this.depthComparison);
                dss.DepthWriteMask   = this.depthWriteEnabled ? DepthWriteMask.All : DepthWriteMask.Zero;
                dss.IsDepthEnabled   = this.depthEnabled;
                dss.IsStencilEnabled = this.stencilEnabled;
                dss.StencilReadMask  = this.stencilReadMask;
                dss.StencilWriteMask = this.stencilWriteMask;

                dss.BackFace.Comparison         = Converter.Convert(this.backStencilComparison);
                dss.BackFace.FailOperation      = Converter.Convert(this.backFailOp);
                dss.BackFace.DepthFailOperation = Converter.Convert(this.backDepthFailOp);
                dss.BackFace.PassOperation      = Converter.Convert(this.backPassOp);

                dss.FrontFace.Comparison         = Converter.Convert(this.backStencilComparison);
                dss.FrontFace.FailOperation      = Converter.Convert(this.backFailOp);
                dss.FrontFace.DepthFailOperation = Converter.Convert(this.backDepthFailOp);
                dss.FrontFace.PassOperation      = Converter.Convert(this.backPassOp);

                state = new D3DDepthStencilState(device.Device, dss);
            }

            device.DeviceContext.OutputMerger.DepthStencilState     = state;
            device.DeviceContext.OutputMerger.DepthStencilReference = stencilReference;
        }
예제 #5
0
        /// <summary>
        /// Function to retrieve the D3D state object.
        /// </summary>
        /// <param name="stateType">The state type information.</param>
        /// <returns>The D3D state object.</returns>
        internal override D3D.DeviceChild GetStateObject(ref GorgonDepthStencilStates stateType)
        {
            var desc = new D3D.DepthStencilStateDescription
            {
                IsDepthEnabled   = States.IsDepthEnabled,
                IsStencilEnabled = States.IsStencilEnabled,
                DepthComparison  = (D3D.Comparison)States.DepthComparison,
                DepthWriteMask   = (States.IsDepthWriteEnabled ? D3D.DepthWriteMask.All : D3D.DepthWriteMask.Zero),
                StencilReadMask  = States.StencilReadMask,
                StencilWriteMask = States.StencilWriteMask,
                FrontFace        = new D3D.DepthStencilOperationDescription
                {
                    Comparison         = (D3D.Comparison)States.StencilFrontFace.ComparisonOperator,
                    DepthFailOperation = (D3D.StencilOperation)States.StencilFrontFace.DepthFailOperation,
                    FailOperation      = (D3D.StencilOperation)States.StencilFrontFace.FailOperation,
                    PassOperation      = (D3D.StencilOperation)States.StencilFrontFace.PassOperation
                },
                BackFace = new D3D.DepthStencilOperationDescription
                {
                    Comparison         = (D3D.Comparison)States.StencilBackFace.ComparisonOperator,
                    DepthFailOperation = (D3D.StencilOperation)States.StencilBackFace.DepthFailOperation,
                    FailOperation      = (D3D.StencilOperation)States.StencilBackFace.FailOperation,
                    PassOperation      = (D3D.StencilOperation)States.StencilBackFace.PassOperation
                }
            };

            var state = new D3D.DepthStencilState(Graphics.D3DDevice, desc)
            {
                DebugName = "Gorgon Depth/stencil state #" + StateCacheCount
            };

            return(state);
        }
예제 #6
0
        public DepthStencilState(GraphicsDevice graphicsDevice, DepthStencilStateInfo info)
            : base(graphicsDevice, new StackTrace(1))
        {
            this.Info = info;

            this.Handle = new SharpDX.Direct3D11.DepthStencilState(graphicsDevice.Device, new DepthStencilStateDescription()
            {
                IsDepthEnabled   = info.IsDepthEnabled,
                DepthComparison  = EnumConverter.Convert(info.DepthComparsion),
                DepthWriteMask   = EnumConverter.Convert(info.DepthWriteMask),
                IsStencilEnabled = info.IsStencilEnabled,
                StencilReadMask  = info.StencilReadMask,
                StencilWriteMask = info.StencilWriteMask,
                FrontFace        = new DepthStencilOperationDescription()
                {
                    Comparison         = EnumConverter.Convert(info.FrontFace.Comparsion),
                    FailOperation      = EnumConverter.Convert(info.FrontFace.FailOperation),
                    PassOperation      = EnumConverter.Convert(info.FrontFace.PassOperation),
                    DepthFailOperation = EnumConverter.Convert(info.FrontFace.DepthFailOperation)
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison         = EnumConverter.Convert(info.BackFace.Comparsion),
                    FailOperation      = EnumConverter.Convert(info.BackFace.FailOperation),
                    PassOperation      = EnumConverter.Convert(info.BackFace.PassOperation),
                    DepthFailOperation = EnumConverter.Convert(info.BackFace.DepthFailOperation)
                }
            });
        }
        public ProjectiveTexturingShader(Device device)
        {
            var shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndProjectiveTextureVS.cso"));
            vertexShader = new VertexShader(device, shaderByteCode);
            geometryShader = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso")));
            pixelShader = 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 states
            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsDepthClipEnabled = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = true,
            };
            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

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

            // user view 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);

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });

        }
        internal static void RunWithStencil(MyBindableResource destinationResource, MyBindableResource sourceResource, BlendState blendState, DepthStencilState depthStencilState, int stencilMask)
        {
            RC.SetDS(depthStencilState, stencilMask);
            RC.SetBS(blendState);
            RC.SetRS(null);
            RC.BindDepthRT(MyGBuffer.Main.DepthStencil, DepthStencilAccess.ReadOnly, destinationResource);
            RC.BindSRV(0, sourceResource);
            RC.SetPS(m_copyPixelShader);

            DrawFullscreenQuad();
            RC.SetBS(null);
        }
예제 #9
0
        internal static void Run(RenderTargetView renderTarget, RenderTargetView intermediateRenderTarget, ShaderResourceView intermediateResourceView, ShaderResourceView initialResourceView,
                                 int maxOffset = 5, MyBlurDensityFunctionType densityFunctionType = MyBlurDensityFunctionType.Gaussian, float WeightParameter = 1.5f,
                                 DepthStencilState depthStencilState = null, int stencilRef = 0x0, bool copyOnStencilFail = false,
                                 float depthDiscardThreshold = 0.0f, MyViewport? viewport = null)
        {
            ProfilerShort.Begin("MyBlur.Run");
            MyGpuProfiler.IC_BeginBlock("MyBlur.Run");
            Debug.Assert(initialResourceView != null);
            Debug.Assert(intermediateResourceView != null);
            Debug.Assert(intermediateRenderTarget != null);
            Debug.Assert(renderTarget != null);

            int shaderKey = InitShaders(densityFunctionType, maxOffset, copyOnStencilFail, depthDiscardThreshold);

            RC.DeviceContext.PixelShader.SetConstantBuffer(5, m_blurConstantBuffer);

            BlurConstants constants = new BlurConstants
            {
                DistributionWeight = WeightParameter,
                StencilRef = stencilRef,
            };
            var mapping = MyMapping.MapDiscard(m_blurConstantBuffer);
            mapping.WriteAndPosition(ref constants);
            mapping.Unmap();

            // Horizontal pass
            MyRender11.DeviceContext.ClearRenderTargetView(intermediateRenderTarget, Color4.White);
            RC.DeviceContext.OutputMerger.SetTargets(intermediateRenderTarget);
            RC.SetDS(depthStencilState, stencilRef);
            RC.DeviceContext.PixelShader.SetShaderResource(0, MyGBuffer.Main.DepthStencil.m_SRV_depth);
            RC.DeviceContext.PixelShader.SetShaderResource(4, MyGBuffer.Main.DepthStencil.m_SRV_stencil);
            RC.DeviceContext.PixelShader.SetShaderResource(5, initialResourceView);
            RC.SetPS(m_blurShaders[shaderKey].Item1);
            MyScreenPass.DrawFullscreenQuad(viewport);
            RC.DeviceContext.PixelShader.SetShaderResource(5, null);

            // Vertical pass
            MyRender11.DeviceContext.ClearRenderTargetView(renderTarget, Color4.White);
            RC.DeviceContext.OutputMerger.SetTargets(renderTarget);
            RC.SetDS(depthStencilState, stencilRef);
            RC.DeviceContext.PixelShader.SetShaderResource(0, MyGBuffer.Main.DepthStencil.m_SRV_depth);
            RC.DeviceContext.PixelShader.SetShaderResource(4, MyGBuffer.Main.DepthStencil.m_SRV_stencil);
            RC.DeviceContext.PixelShader.SetShaderResource(5, intermediateResourceView);
            RC.SetPS(m_blurShaders[shaderKey].Item2);
            MyScreenPass.DrawFullscreenQuad(viewport);

            RC.DeviceContext.PixelShader.SetShaderResource(0, null);
            RC.DeviceContext.PixelShader.SetShaderResource(4, null);
            RC.DeviceContext.PixelShader.SetShaderResource(5, null);

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
        }
예제 #10
0
        public D3DDepthStencilState(Device device, bool isDepthEnabled, DepthComparison comparison, bool isDepthWriteEnabled)
        {
            _device             = device;
            IsDepthEnabled      = IsDepthEnabled;
            IsDepthWriteEnabled = isDepthWriteEnabled;
            DepthComparison     = comparison;

            DepthStencilStateDescription desc = DepthStencilStateDescription.Default();

            desc.DepthComparison = D3DFormats.ConvertDepthComparison(comparison);
            desc.IsDepthEnabled  = isDepthEnabled;
            desc.DepthWriteMask  = isDepthWriteEnabled ? DepthWriteMask.All : DepthWriteMask.Zero;

            _deviceState = new SharpDX.Direct3D11.DepthStencilState(device, desc);
        }
예제 #11
0
        // https://gamedev.stackexchange.com/questions/75461/how-do-i-set-up-a-depth-buffer-in-sharpdx
        // https://docs.microsoft.com/en-us/windows/desktop/direct3d11/d3d10-graphics-programming-guide-depth-stencil
        private void EnableDepthTest()
        {
            if (depthStencilView != null)
            {
                depthStencilView.Dispose();
            }

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

            // Create the depth stencil description
            depthTextureDesc = new D3D11.Texture2DDescription
            {
                Format            = Format.D16_UNorm,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = this.Width,
                Height            = this.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.DepthStencil,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            };

            // Create the depth stencil view
            using (var depthTex = new D3D11.Texture2D(d3dDevice, depthTextureDesc))
            {
                depthStencilView = new D3D11.DepthStencilView(d3dDevice, depthTex);
            }

            // Create the depth stencil state description
            depthStencilStateDesc = new D3D11.DepthStencilStateDescription();
            depthStencilStateDesc.IsDepthEnabled   = true;
            depthStencilStateDesc.DepthWriteMask   = D3D11.DepthWriteMask.All;
            depthStencilStateDesc.DepthComparison  = D3D11.Comparison.Less;
            depthStencilStateDesc.IsStencilEnabled = false;

            // Create the depth stencil state
            depthStencilState = new D3D11.DepthStencilState(d3dDevice, depthStencilStateDesc);

            // Update the context
            d3dDeviceContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);
            d3dDeviceContext.OutputMerger.SetDepthStencilState(depthStencilState);
        }
예제 #12
0
        public void ShutDown()
        {
            // Before shutting down set to windowed mode or when you release the swap chain it will throw an exception.
            SwapChain?.SetFullscreenState(false, null);
            RasterState?.Dispose();
            RasterState = null;
            depthStencilState?.Dispose();
            depthStencilState = null;
            DepthStencilBuffer?.Dispose();
            DepthStencilBuffer = null;
            _depthStencilView?.Dispose();
            _depthStencilView = null;
            _renderTargetView?.Dispose();
            _renderTargetView = null;
            DeviceContext?.Dispose();
            Device?.Dispose();
            SwapChain?.Dispose();



            AlphaEnableBlendingState?.Dispose();
            AlphaEnableBlendingState = null;
            AlphaDisableBlendingState?.Dispose();
            AlphaDisableBlendingState = null;
            DepthDisabledStencilState?.Dispose();
            DepthDisabledStencilState = null;
            //DepthStencilView?.Dispose();
            //DepthStencilView = null;
            DepthStencilState?.Dispose();
            DepthStencilState = null;
            DepthStencilBuffer?.Dispose();
            DepthStencilBuffer = null;


            if (main_thread_update != null)
            {
                //main_thread_update.Suspend();
                main_thread_update = null;
            }
            ShutDownGraphics();
        }
예제 #13
0
        /// <summary>
        ///
        /// </summary>
        void SetupDepthStencilState()
        {
            var dss = new DepthStencilStateDescription();

            dss.DepthComparison  = Converter.Convert(DepthStencilState.DepthComparison);
            dss.DepthWriteMask   = DepthStencilState.DepthWriteEnabled ? DepthWriteMask.All : DepthWriteMask.Zero;
            dss.IsDepthEnabled   = DepthStencilState.DepthEnabled;
            dss.IsStencilEnabled = DepthStencilState.StencilEnabled;
            dss.StencilReadMask  = DepthStencilState.StencilReadMask;
            dss.StencilWriteMask = DepthStencilState.StencilWriteMask;

            dss.BackFace.Comparison         = Converter.Convert(DepthStencilState.BackFaceStencilComparison);
            dss.BackFace.FailOperation      = Converter.Convert(DepthStencilState.BackFaceFailOp);
            dss.BackFace.DepthFailOperation = Converter.Convert(DepthStencilState.BackFaceDepthFailOp);
            dss.BackFace.PassOperation      = Converter.Convert(DepthStencilState.BackFacePassOp);

            dss.FrontFace.Comparison         = Converter.Convert(DepthStencilState.FrontFaceStencilComparison);
            dss.FrontFace.FailOperation      = Converter.Convert(DepthStencilState.FrontFaceFailOp);
            dss.FrontFace.DepthFailOperation = Converter.Convert(DepthStencilState.FrontFaceDepthFailOp);
            dss.FrontFace.PassOperation      = Converter.Convert(DepthStencilState.FrontFacePassOp);

            depthStencilRef   = DepthStencilState.StencilReference;
            depthStencilState = new D3DDepthStencilState(device.Device, dss);
        }
예제 #14
0
 /// <summary>
 /// Create a depth-stencil state object that encapsulates depth-stencil test information for the output-merger stage.
 /// </summary>
 /// <param name="device">The <see cref="DirectXDevice"/>.</param>
 /// <param name="depthStencilState">An existing <see cref="Direct3D11.DepthStencilState"/> instance.</param>
 /// <returns>A new instance of <see cref="DepthStencilState"/></returns>
 /// <remarks>
 /// <p>4096 unique depth-stencil state objects can be created on a device at a time.</p><p>If an application attempts to create a depth-stencil-state interface with the same state as an existing interface, the same interface will be returned and the total number of unique depth-stencil state objects will stay the same.</p>
 /// </remarks>
 /// <msdn-id>ff476506</msdn-id>
 /// <unmanaged>HRESULT ID3D11Device::CreateDepthStencilState([In] const D3D11_DEPTH_STENCIL_DESC* pDepthStencilDesc,[Out, Fast] ID3D11DepthStencilState** ppDepthStencilState)</unmanaged>
 /// <unmanaged-short>ID3D11Device::CreateDepthStencilState</unmanaged-short>
 public static DepthStencilState New(DirectXDevice device, SharpDX.Direct3D11.DepthStencilState depthStencilState)
 {
     return(new DepthStencilState(device, depthStencilState));
 }
예제 #15
0
        internal void SetDepthStencilState(DepthStencilState dss, int stencilRef)
        {
            if (dss == m_depthStencilState && stencilRef == m_stencilRef)
                return;

            m_depthStencilState = dss;
            m_stencilRef = stencilRef;

            m_deviceContext.OutputMerger.SetDepthStencilState(dss, stencilRef);
            m_statistics.SetDepthStencilStates++;
        }
예제 #16
0
        // Define how the depth buffer will be used to filter out objects, based on their distance from the viewer.
        void DefineDepthStencilState()
        {
            var desc = DepthStencilStateDescription.Default();

            // NoDepthWriteState
            /*
            desc.IsDepthEnabled = true;
            desc.DepthWriteMask = DepthWriteMask.Zero;
            */
            desc.DepthComparison = Comparison.LessEqual;

            default_depth_stencil_state = new DepthStencilState(device, desc);
        }
        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 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"))
            {
                vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode));
                // 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),
                    // "SkinIndices"
                    new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0),
                    // "SkinWeights"
                    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));

            // 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
            // 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, 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 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.Solid,
                CullMode = CullMode.Back,
            }));
        }
        // Example using async
        protected override void CreateDeviceDependentResources(Common.DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            RemoveAndDispose(ref fpsRenderer);
            RemoveAndDispose(ref cubeRenderer);
            RemoveAndDispose(ref textRenderer);

            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref pixelShader);

            var device = deviceManager.Direct3DDevice;

            #region Compile shaders
            // Compile Vertex Shader and create vertex InputLayout
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = new VertexShader(device, bytecode);
                vertexLayout = ToDispose(new InputLayout(device,
                   bytecode.GetPart(ShaderBytecodePart.InputSignatureBlob).Data,
                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 pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0"))
                pixelShader = ToDispose(new PixelShader(device, bytecode));
            #endregion

            #region Create constant buffers
            // Create constant buffers

            // 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));

            #endregion

            #region Create pipeline state variables
            // 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)
                }));

            rsCullBack = ToDispose(new RasterizerState(device, new RasterizerStateDescription
            {
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = false,
                FillMode = FillMode.Solid,
            }));
            #endregion

            #region Create Renderers
            cubeRenderer = new CubeRenderer();
            cubeRenderer.Initialize(this);

            textRenderer = ToDispose(new TextRenderer("Calibri", SharpDX.Color.Black, new Point(20, 100), 48, 800));
            textRenderer.Initialize(this);

            fpsRenderer = ToDispose(new FpsRenderer());
            fpsRenderer.Initialize(this);
            #endregion

            clock.Start();
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref vertexShaderInstanced);
            RemoveAndDispose(ref geomShader);
            RemoveAndDispose(ref pixelShader);

            RemoveAndDispose(ref blendState);
            RemoveAndDispose(ref linearSampler);

            RemoveAndDispose(ref perComputeBuffer);
            RemoveAndDispose(ref perFrame);

            // Dispose of any loaded particle textures
            particleTextureSRVs.ForEach(srv => RemoveAndDispose(ref srv));
            particleTextureSRVs.Clear();

            // Dispose of any compute shaders
            computeShaders.Select(kv => kv.Value).ToList().ForEach(cs => RemoveAndDispose(ref cs));
            computeShaders.Clear();

            var device = this.DeviceManager.Direct3DDevice;

            #region Compile Vertex/Pixel/Geometry shaders

            // Compile and create the vertex shader
            using (var vsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticleVS.hlsl", "VSMain", "vs_5_0"))
            using (var vsInstance = HLSLCompiler.CompileFromFile(@"Shaders\ParticleVS.hlsl", "VSMainInstance", "vs_5_0"))
            // Compile and create the pixel shader
            using (var psBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticlePS.hlsl", "PSMain", "ps_5_0"))
            // Compile and create the geometry shader
            using (var gsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticleGS.hlsl", "PointToQuadGS", "gs_5_0"))
            {
                vertexShader = ToDispose(new VertexShader(device, vsBytecode));
                vertexShaderInstanced = ToDispose(new VertexShader(device, vsInstance));
                pixelShader = ToDispose(new PixelShader(device, psBytecode));
                geomShader = ToDispose(new GeometryShader(device, gsBytecode));
            }
            #endregion

            #region Blend States
            var blendDesc = new BlendStateDescription() {
                IndependentBlendEnable = false,
                AlphaToCoverageEnable = false,
            };
            // Additive blend state that darkens
            blendDesc.RenderTarget[0] = new RenderTargetBlendDescription
            {
                IsBlendEnabled = true,
                BlendOperation = BlendOperation.Add,
                AlphaBlendOperation = BlendOperation.Add,
                SourceBlend = BlendOption.SourceAlpha,
                DestinationBlend = BlendOption.InverseSourceAlpha,
                SourceAlphaBlend = BlendOption.One,
                DestinationAlphaBlend = BlendOption.Zero,
                RenderTargetWriteMask = ColorWriteMaskFlags.All
            };
            blendState = ToDispose(new BlendState(device, blendDesc));

            // Additive blend state that lightens
            // (needs a dark background)
            blendDesc.RenderTarget[0].DestinationBlend = BlendOption.One;

            blendStateLight = ToDispose(new BlendState(device, blendDesc));
            #endregion

            // depth stencil state to disable Z-buffer
            disableDepthWrite = ToDispose(new DepthStencilState(device, new DepthStencilStateDescription {
                DepthComparison = Comparison.Less,
                DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.Zero,
                IsDepthEnabled = true,
                IsStencilEnabled = false
            }));

            // Create a linear sampler
            linearSampler = ToDispose(new SamplerState(device, new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.MinMagMipLinear, // Bilinear
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
            }));

            // Create the per compute shader constant buffer
            perComputeBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ParticleConstants>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            // Create the particle frame buffer
            perFrame = ToDispose(new Buffer(device, Utilities.SizeOf<ParticleFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Particle.png")));
            particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Snowflake.png")));
            particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Square.png")));
            activeParticleTextureIndex = 0;

            // Reinitialize particles if > 0
            if (this.Constants.MaxParticles > 0)
            {
                InitializeParticles(this.Constants.MaxParticles, this.Constants.MaxLifetime);
            }
        }
예제 #20
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample");

            // SwapChain description
            var desc = new SwapChainDescription()
                           {
                               BufferCount = 3,
                               ModeDescription=
                                   new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                                       new Rational(60, 1), Format.R8G8B8A8_UNorm),
                               IsWindowed = true,
                               OutputHandle = form.Handle,
                               SampleDescription = new SampleDescription(1,0),
                               SwapEffect = SwapEffect.Sequential,
                               Usage = Usage.RenderTargetOutput

                           };

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Ignore all windows events
            var factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            Texture2DDescription depthBufferDesc;
            depthBufferDesc.Width = form.Width;
            depthBufferDesc.Height = form.Height;
            depthBufferDesc.MipLevels = 1;
            depthBufferDesc.ArraySize = 1;
            depthBufferDesc.Format = Format.D24_UNorm_S8_UInt;
            depthBufferDesc.SampleDescription.Count = 1;
            depthBufferDesc.SampleDescription.Quality = 0;
            depthBufferDesc.Usage = ResourceUsage.Default;
            depthBufferDesc.BindFlags = BindFlags.DepthStencil;
            depthBufferDesc.CpuAccessFlags = CpuAccessFlags.None ;
            depthBufferDesc.OptionFlags = ResourceOptionFlags.None;

            Texture2D DepthStencilTexture = new Texture2D(device, depthBufferDesc);

            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription();
            depthStencilViewDesc.Format = Format.D24_UNorm_S8_UInt;
            depthStencilViewDesc.Dimension =  DepthStencilViewDimension.Texture2D;
            depthStencilViewDesc.Texture2D.MipSlice = 0;
            DepthStencilView depthStencilView = new DepthStencilView(device, DepthStencilTexture, depthStencilViewDesc);
            context.OutputMerger.SetTargets(depthStencilView,renderView);

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

            RasterizerStateDescription rasdesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
                IsMultisampleEnabled =true,
            };
            context.Rasterizer.State = new RasterizerState(device, rasdesc);

            //////////////////////////////

            var flags = (ppsteps |
                aiPostProcessSteps.aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing
                aiPostProcessSteps.aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes
                aiPostProcessSteps.aiProcess_Triangulate | // triangulate polygons with more than 3 edges
                aiPostProcessSteps.aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
                aiPostProcessSteps.aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
                (aiPostProcessSteps)0);

            // default model
            var path = @"jeep1.ms3d";

            Importer importer = new Importer();

            //var path = "man.3ds";
            aiScene scene = importer.ReadFile(path, flags);
            String directory = null;
            if (scene != null)
            {
                directory = Path.GetDirectoryName(path);
            }
            else
            {
                MessageBox.Show("Failed to open file: " + path + ". Either Assimp screwed up or the path is not valid.");
                Application.Exit();
            }

            SceneLoader SceneLoader = new SceneLoader();
            List<model> models = new List<model>();
            for (int i = 0; i < scene.mNumMeshes; i++)
            {
                models.Add(SceneLoader.CreateMesh(device, scene.mMeshes[i], scene.mMaterials,directory));
            }

            //////////////////////////////

            // Compile Vertex and Pixel shaders
            var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, effectByteCode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);

            // Layout from VertexShader input signature
            var passSignature = pass.Description.Signature;

            // Layout from VertexShader input signature
            var layout = new InputLayout(
                device,
                passSignature,
                new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
                    });

            // Prepare All the stages
            context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            context.OutputMerger.DepthStencilState = depthStencilState;

            Input input = new Input(form);
            //FreeLook FreeLook = new SharpExamples.FreeLook(input, (float)form.Width / (float)form.Height);
            CameraFirstPerson FreeLook = new CameraFirstPerson(input, 0, 0, Vector3.Zero, form.Width, form.Height);
            //FreeLook.SetEyeTarget(new Vector3(300), Vector3.Zero);
            Clock Clock = new SharpExamples.Clock();
            Clock.Start();

            effect.GetVariableByName("projection").AsMatrix().SetMatrix(FreeLook.Projection);

            // Main loop
            RenderLoop.Run(form, () =>
                                      {
                                          foreach (var item in models)
                                          {
                                                context.InputAssembler.InputLayout = layout;
                                                context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                                                int SizeInBytes = Marshal.SizeOf(typeof(VertexPostitionTexture));
                                                context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(item.vertex, SizeInBytes, 0));
                                                context.InputAssembler.SetIndexBuffer(item.indices, Format.R32_UInt, 0);

                                                float elapsed = Clock.Update();
                                                FreeLook.Update(elapsed);

                                                effect.GetVariableByName("view").AsMatrix().SetMatrix(FreeLook.View);
                                                effect.GetVariableByName("World").AsMatrix().SetMatrix(Matrix.Scaling(5));
                                                effect.GetVariableByName("tex0").AsShaderResource().SetResource(item.ShaderResourceView);
                                                context.ClearRenderTargetView(renderView, Colors.Black);
                                                context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0);

                                                for (int i = 0; i < technique.Description.PassCount; ++i)
                                                {
                                                    pass.Apply(context);
                                                    context.DrawIndexed(item.numberIndices, 0, 0);
                                                }
                                                swapChain.Present(0, PresentFlags.None);
                                          }

                                      });

            // Release all resources
            foreach (var item in models)
            {
                item.vertex.Dispose();
                item.indices.Dispose();
                item.ShaderResourceView.Dispose();
            }

            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
예제 #21
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="device"></param>
		internal void Apply ( GraphicsDevice device )
		{
			if ( state == null ) {
				
				var dss	=	new DepthStencilStateDescription();

				dss.DepthComparison		=	Converter.Convert( this.depthComparison );
				dss.DepthWriteMask		=	this.depthWriteEnabled ? DepthWriteMask.All : DepthWriteMask.Zero;
				dss.IsDepthEnabled		=	this.depthEnabled;
				dss.IsStencilEnabled	=	this.stencilEnabled;
				dss.StencilReadMask		=	this.stencilReadMask;
				dss.StencilWriteMask	=	this.stencilWriteMask;

				dss.BackFace.Comparison				=	Converter.Convert( this.backStencilComparison	);
				dss.BackFace.FailOperation			=	Converter.Convert( this.backFailOp				);
				dss.BackFace.DepthFailOperation		=	Converter.Convert( this.backDepthFailOp			);
				dss.BackFace.PassOperation			=	Converter.Convert( this.backPassOp				);

				dss.FrontFace.Comparison			=	Converter.Convert( this.backStencilComparison	);
				dss.FrontFace.FailOperation			=	Converter.Convert( this.backFailOp				);
				dss.FrontFace.DepthFailOperation	=	Converter.Convert( this.backDepthFailOp			);
				dss.FrontFace.PassOperation			=	Converter.Convert( this.backPassOp				);

				state	=	new D3DDepthStencilState( device.Device, dss );
			}

			device.DeviceContext.OutputMerger.DepthStencilState		=	state;
			device.DeviceContext.OutputMerger.DepthStencilReference	=	stencilReference;
		}
예제 #22
0
        public void InitializeBuffers()
        {
            //Create back buffer
            Texture2D backBuffer = Resource.FromSwapChain<Texture2D>(SwapChain, 0);
            _renderTargetView = new RenderTargetView(Device, backBuffer);
            backBuffer.Dispose();

            //Create the depth/stencil buffer
            var depthBufferDesc = new Texture2DDescription
            {
                Width = ConfigurationManager.Config.Width,
                Height = ConfigurationManager.Config.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = ConfigurationManager.Config.AntiAliasing ? new SampleDescription(4, _maxQualityLevel-1) : new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };
            _depthStencilBuffer = new Texture2D(Device, depthBufferDesc);

            DepthStencilStateDescription depthStencilDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF,
                // Stencil operation if pixel front-facing.
                FrontFace = new DepthStencilOperationDescription
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },
                // Stencil operation if pixel is back-facing.
                BackFace = new DepthStencilOperationDescription
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                }
            };

            // Create the depth stencil state.
            _depthStencilState = new DepthStencilState(Device, depthStencilDesc);

            DepthStencilStateDescription depthDisabledStencilDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF,
                // Stencil operation if pixel front-facing.
                FrontFace = new DepthStencilOperationDescription
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },
                // Stencil operation if pixel is back-facing.
                BackFace = new DepthStencilOperationDescription
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                }
            };

            _depthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);

            // Set the depth stencil state.
            _isZBufferEnabled = true;
            DeviceContext.OutputMerger.SetDepthStencilState(_depthStencilState, 1);

            // Initialize and set up the depth stencil view.
            DepthStencilViewDescription depthStencilViewDesc;
            if(ConfigurationManager.Config.AntiAliasing)
                depthStencilViewDesc = new DepthStencilViewDescription
                {
                    Format = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2DMultisampled,
                    Texture2DMS = new DepthStencilViewDescription.Texture2DMultisampledResource()
                };
            else
                depthStencilViewDesc = new DepthStencilViewDescription
                {
                    Format = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    { MipSlice = 0 }
                };

            // Create the depth stencil view.
            DepthStencilView = new DepthStencilView(Device, _depthStencilBuffer, depthStencilViewDesc);

            RenderToTextureDepthStencilView = new DepthStencilView(Device, new Texture2D(Device, new Texture2DDescription
            {
                Width = ConfigurationManager.Config.Width,
                Height = ConfigurationManager.Config.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            }), new DepthStencilViewDescription
            {
                Format = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 }
            });

            // Bind the render target view and depth stencil buffer to the output render pipeline.
            DeviceContext.OutputMerger.SetTargets(DepthStencilView, _renderTargetView);

            // Setup the raster description which will determine how and what polygon will be drawn.
            var rasterDesc = new RasterizerStateDescription
            {
                IsAntialiasedLineEnabled = false,
                CullMode = CullMode.Back,
                DepthBias = 0,
                DepthBiasClamp = .0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled = false,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = .0f
            };

            // Create the rasterizer state from the description we just filled out.
            _rasterStateSolid = new RasterizerState(Device, rasterDesc);

            rasterDesc.FillMode = FillMode.Wireframe;

            _rasterStateWireFrame = new RasterizerState(Device, rasterDesc);

            // Now set the rasterizer state.
            DeviceContext.Rasterizer.State = _rasterStateSolid;

            // Setup and create the viewport for rendering.
            DeviceContext.Rasterizer.SetViewport(0, 0, ConfigurationManager.Config.Width, ConfigurationManager.Config.Height, 0, 1);

            var blendStateDescription = new BlendStateDescription();
            blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
            blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            // Create the blend state using the description.
            _alphaEnabledBlendState = new BlendState(Device, blendStateDescription);

            blendStateDescription.RenderTarget[0].IsBlendEnabled = false;
            // Create the blend state using the description.
            _alphaDisabledBlendState = new BlendState(Device, blendStateDescription);
        }
예제 #23
0
        private void InitializeInternal(Device device) {
            Debug.Assert(device != null);

            var wfDesc = new RasterizerStateDescription {
                FillMode = FillMode.Wireframe,
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = false,
                IsDepthClipEnabled = true
            };
            _wireframeRs = new RasterizerState(device, wfDesc);

            var noCullDesc = new RasterizerStateDescription {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                IsFrontCounterClockwise = false,
                IsDepthClipEnabled = true
            };
            _noCullRs = new RasterizerState(device, noCullDesc);

            var cullClockwiseDesc = new RasterizerStateDescription {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = true,
                IsDepthClipEnabled = true
            };
            _cullClockwiseRs = new RasterizerState(device, cullClockwiseDesc);

            var atcDesc = new BlendStateDescription {
                AlphaToCoverageEnable = true,
                IndependentBlendEnable = false,
            };
            atcDesc.RenderTarget[0].IsBlendEnabled = false;
            atcDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            _alphaToCoverageBs = new BlendState(device, atcDesc);

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

            _transparentBs = new BlendState(device, transDesc);

            var noRenderTargetWritesDesc = new BlendStateDescription {
                AlphaToCoverageEnable = false,
                IndependentBlendEnable = false
            };
            noRenderTargetWritesDesc.RenderTarget[0].IsBlendEnabled = false;
            noRenderTargetWritesDesc.RenderTarget[0].SourceBlend = BlendOption.One;
            noRenderTargetWritesDesc.RenderTarget[0].DestinationBlend = BlendOption.Zero;
            noRenderTargetWritesDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            noRenderTargetWritesDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            noRenderTargetWritesDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            noRenderTargetWritesDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            noRenderTargetWritesDesc.RenderTarget[0].RenderTargetWriteMask = 0;

            _noRenderTargetWritesBs = new BlendState(device, noRenderTargetWritesDesc);

            var mirrorDesc = new DepthStencilStateDescription {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xff,
                StencilWriteMask = 0xff,
                FrontFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always
                },
                BackFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always
                }
            };

            _markMirrorDss = new DepthStencilState(device, mirrorDesc);

            var drawReflectionDesc = new DepthStencilStateDescription {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xff,
                StencilWriteMask = 0xff,
                FrontFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal
                },
                BackFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal
                }
            };
            _drawReflectionDss = new DepthStencilState(device, drawReflectionDesc);

            var noDoubleBlendDesc = new DepthStencilStateDescription {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xff,
                StencilWriteMask = 0xff,
                FrontFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Increment,
                    Comparison = Comparison.Equal
                },
                BackFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Increment,
                    Comparison = Comparison.Equal
                }
            };
            _noDoubleBlendDss = new DepthStencilState(device, noDoubleBlendDesc);

            var lessEqualDesc = new DepthStencilStateDescription {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.LessEqual,
                IsStencilEnabled = false
            };
            _lessEqualDss = new DepthStencilState(device, lessEqualDesc);

            var equalsDesc = new DepthStencilStateDescription() {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.LessEqual,

            };
            _equalsDss = new DepthStencilState(device, equalsDesc);

            var noDepthDesc = new DepthStencilStateDescription() {
                IsDepthEnabled = false,
                DepthComparison = Comparison.Always,
                DepthWriteMask = DepthWriteMask.Zero
            };
            _noDepthDss = new DepthStencilState(device, noDepthDesc);
        }
예제 #24
0
        public void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                    return;

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                    return;

                Width = Form.ClientSize.Width;
                Height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            Width = 1024;
            Height = 768;
            NearPlane = 1.0f;
            FarPlane = 200.0f;
            FieldOfView = (float)Math.PI / 4;

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


            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;

            string[] sources = new[] { "shader.fx", "grender.fx" };
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags))
            {
                effect = new Effect(_device, shaderByteCode);
            }
            EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate");
            shadowGenPass = technique.GetPassByName("ShadowMap");
            gBufferGenPass = technique.GetPassByName("GBufferGen");
            debugDrawPass = technique.GetPassByName("DebugDraw");

            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 _rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
            };
            noCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Back;
            backCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Front;
            frontCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState;

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            depthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthWriteMask = DepthWriteMask.Zero;
            outsideLightVolumeDepthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthComparison = Comparison.Greater;
            insideLightVolumeDepthState = 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
            technique = effect.GetTechniqueByName("DeferredShader");
            gBufferRenderPass = technique.GetPassByName("DeferredShader");
            gBufferPostProcessPass = technique.GetPassByName("Blur");
            gBufferPostProcessPass2 = technique.GetPassByName("PostProcess");
            gBufferOverlayPass = technique.GetPassByName("Overlay");

            lightBufferVar = effect.GetVariableByName("lightBuffer").AsShaderResource();
            normalBufferVar = effect.GetVariableByName("normalBuffer").AsShaderResource();
            diffuseBufferVar = effect.GetVariableByName("diffuseBuffer").AsShaderResource();
            depthMapVar = effect.GetVariableByName("depthMap").AsShaderResource();
            shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource();

            sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector();
            viewportWidthVar = effect.GetVariableByName("ViewportWidth").AsScalar();
            viewportHeightVar = effect.GetVariableByName("ViewportHeight").AsScalar();
            viewParametersVar = effect.GetVariableByName("ViewParameters").AsVector();

            overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix();


            // light.fx
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags))
            {
                lightShader = new Effect(_device, shaderByteCode);
            }

            technique = lightShader.GetTechniqueByIndex(0);
            lightAccumulationPass = technique.GetPassByName("Light");

            lightWorldVar = lightShader.GetVariableByName("World").AsMatrix();
            lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector();
            lightColorVar = lightShader.GetVariableByName("Color").AsVector();

            lightProjectionVar = lightShader.GetVariableByName("Projection").AsMatrix();
            lightViewVar = lightShader.GetVariableByName("View").AsMatrix();
            lightViewInverseVar = lightShader.GetVariableByName("ViewInverse").AsMatrix();
            lightViewportWidthVar = lightShader.GetVariableByName("ViewportWidth").AsScalar();
            lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar();
            lightEyePositionVar = lightShader.GetVariableByName("EyePosition").AsVector();
            lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector();

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
            };
            lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements);

            pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices);
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer,
            };

            using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeVertices);
                data.Position = 0;
                pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc);
            }
            pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0);

            BufferDescription indexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.IndexBuffer
            };
            using (var data = new SharpDX.DataStream(indexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeIndices);
                data.Position = 0;
                pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc);
            }

            lightDepthBufferVar = lightShader.GetVariableByName("depthBuffer").AsShaderResource();
            lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource();

            lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1)));
            //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1)));
            //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1)));
            //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1)));
            //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1)));


            Info = new InfoText(_device, 256, 256);
            _meshFactory = new MeshFactory(this);

            CreateBuffers();
        }
예제 #25
0
        public void InitRenderTargets()
        {
            D3D11.DeviceContext deviceContext = deviceResources.DeviceContext;

            var renderTargetDesc = new D3D11.Texture2DDescription()
            {
                Format            = Format.R16G16B16A16_Float,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = deviceResources.BackBuffer.Description.Width,
                Height            = deviceResources.BackBuffer.Description.Height,
                SampleDescription = sampleDescription,
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            };

            var depthStencilDesc = new D3D11.Texture2DDescription()
            {
                Format            = Format.R24G8_Typeless,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = deviceResources.BackBuffer.Description.Width,
                Height            = deviceResources.BackBuffer.Description.Height,
                SampleDescription = sampleDescription,
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.DepthStencil | D3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            };

            var depthStencilStateDesc = new D3D11.DepthStencilStateDescription
            {
                IsDepthEnabled  = true,
                DepthComparison = D3D11.Comparison.LessEqual,
                DepthWriteMask  = D3D11.DepthWriteMask.All,
            };


            // Create Descripptions for DepthStencil
            // RenderTarget works without Desc
            D3D11.DepthStencilViewDescription dsvDesc = new D3D11.DepthStencilViewDescription();
            dsvDesc.Format             = Format.D24_UNorm_S8_UInt;
            dsvDesc.Dimension          = D3D11.DepthStencilViewDimension.Texture2D;
            dsvDesc.Texture2D.MipSlice = 0;
            dsvDesc.Flags = 0;

            D3D11.ShaderResourceViewDescription dsSrvtDesc = new D3D11.ShaderResourceViewDescription();
            dsSrvtDesc.Texture2D.MipLevels = 1;
            dsSrvtDesc.Dimension           = ShaderResourceViewDimension.Texture2D;
            dsSrvtDesc.Format = Format.R24_UNorm_X8_Typeless; // TODO: Check Format


            // Create RenderTarget Textures
            renderTargetHandler.CreateRenderTarget(deviceResources.Device, renderTargetDesc);
            renderTargetHandler.CreateDepthStencil(deviceResources.Device, depthStencilDesc, dsvDesc, dsSrvtDesc);


            deviceContext.OutputMerger.SetRenderTargets(
                renderTargetHandler.GetDepthStencilView(),
                renderTargetHandler.GetRenderTargetView()
                );



            // Create DepthStencilState
            var depthStencilState = new D3D11.DepthStencilState(deviceResources.Device, depthStencilStateDesc);

            deviceContext.OutputMerger.SetDepthStencilState(depthStencilState);

            // Create Sampler
            sampler = CreateSampler();
            deviceContext.VertexShader.SetSampler(0, sampler);
            deviceContext.PixelShader.SetSampler(0, sampler);

            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            Logger.Write(LogType.Info, "Renderer Created");
        }
        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 tessellatePhongDomainShader);

            RemoveAndDispose(ref debugNormals);

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

            RemoveAndDispose(ref decalBuffer);
            RemoveAndDispose(ref decalDiffuse);
            RemoveAndDispose(ref decalDisplacement);
            RemoveAndDispose(ref decalNormal);

            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),
                    // "TANGENT"
                    new InputElement("TANGENT", 0, Format.R32G32B32A32_Float, 68, 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 triIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesInteger", "hs_5_0", null))
            using (var triPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesPow2", "hs_5_0", null))
            using (var triFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesFractionalEven", "hs_5_0", null))
            using (var triFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesFractionalOdd", "hs_5_0", null))
            using (var triDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "DS_Triangles", "ds_5_0", null))
            {
                tessellateTriIntegerShader = ToDispose(new HullShader(device, triIntegerBytecode));
                tessellateTriPow2Shader = ToDispose(new HullShader(device, triPow2Bytecode));
                tessellateTriFractionalEvenShader = ToDispose(new HullShader(device, triFractionalEvenBytecode));
                tessellateTriFractionalOddShader = ToDispose(new HullShader(device, triFractionalOddBytecode));
                tessellateTriDomainShader = ToDispose(new DomainShader(device, triDomainShaderBytecode));
            }

            using (var phongDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePhong.hlsl", "DS_PhongTessellation", "ds_5_0", null))
            {
                tessellatePhongDomainShader = ToDispose(new DomainShader(device, phongDomainShaderBytecode));
            }

            using (var pnTriIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesInteger", "hs_5_0", null))
            using (var pnTriPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesPow2", "hs_5_0", null))
            using (var pnTriFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesFractionalEven", "hs_5_0", null))
            using (var pnTriFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesFractionalOdd", "hs_5_0", null))
            using (var pnTriDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "DS_PNTriangles", "ds_5_0", null))
            {
                pnTriIntegerShader = ToDispose(new HullShader(device, pnTriIntegerBytecode));
                pnTriPow2Shader = ToDispose(new HullShader(device, pnTriPow2Bytecode));
                pnTriFractionalEvenShader = ToDispose(new HullShader(device, pnTriFractionalEvenBytecode));
                pnTriFractionalOddShader = ToDispose(new HullShader(device, pnTriFractionalOddBytecode));
                pnTriDomainShader = ToDispose(new DomainShader(device, pnTriDomainShaderBytecode));
            }

            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));

            // Create the decal buffer
            decalBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ConstantBuffers.DecalBuffer>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Load the decal textures
            decalDiffuse = ToDispose(ShaderResourceView.FromFile(device, "Crater_Diffuse.png"));
            decalDisplacement = ToDispose(ShaderResourceView.FromFile(device, "Crater_Displacement.png"));
            decalNormal = ToDispose(ShaderResourceView.FromFile(device, "Crater_Normal.png"));

            // 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, 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 shader constant buffers
            context.HullShader.SetConstantBuffer(0, perObjectBuffer);
            context.HullShader.SetConstantBuffer(1, perFrameBuffer);

            // Set default Hull Shader
            context.HullShader.Set(tessellateTriIntegerShader);

            context.DomainShader.SetConstantBuffer(0, perObjectBuffer);
            context.DomainShader.SetConstantBuffer(1, perFrameBuffer);
            context.DomainShader.SetConstantBuffer(2, perMaterialBuffer);
            context.DomainShader.Set(tessellateTriDomainShader);

            // 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;

            // Add the decal buffer to the pixel, hull and domain shaders (it uses the 5th slot 0-indexed)
            context.HullShader.SetConstantBuffer(4, decalBuffer);
            context.DomainShader.SetConstantBuffer(4, decalBuffer);
            context.PixelShader.SetConstantBuffer(4, decalBuffer);

            // No culling
            context.Rasterizer.State = ToDispose(new RasterizerState(device, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None
            }));
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref lightBuffer);
            RemoveAndDispose(ref RTV);
            RemoveAndDispose(ref SRV);
            RemoveAndDispose(ref rsCullBack);
            RemoveAndDispose(ref rsCullFront);
            RemoveAndDispose(ref rsWireframe);
            RemoveAndDispose(ref blendStateAdd);
            RemoveAndDispose(ref depthLessThan);
            RemoveAndDispose(ref depthGreaterThan);
            RemoveAndDispose(ref depthDisabled);
            RemoveAndDispose(ref perLightBuffer);

            RemoveAndDispose(ref psAmbientLight);
            RemoveAndDispose(ref psDirectionalLight);
            RemoveAndDispose(ref psPointLight);
            RemoveAndDispose(ref psSpotLight);
            RemoveAndDispose(ref psDebugLight);
            RemoveAndDispose(ref perLightBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            int width, height;
            SampleDescription sampleDesc;

            // Retrieve DSV from GBuffer and extract width/height
            // then create a new read-only DSV
            using (var depthTexture = gbuffer.DSV.ResourceAs<Texture2D>())
            {
                width = depthTexture.Description.Width;
                height = depthTexture.Description.Height;
                sampleDesc = depthTexture.Description.SampleDescription;

                // Initialize read-only DSV
                var dsvDesc = gbuffer.DSV.Description;
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth | DepthStencilViewFlags.ReadOnlyStencil;
                DSVReadonly = ToDispose(new DepthStencilView(device, depthTexture, dsvDesc));
            }
            // Check if GBuffer is multi-sampled
            bool isMSAA = sampleDesc.Count > 1;

            // Initialize the light render target
            var texDesc = new Texture2DDescription();
            texDesc.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget;
            texDesc.ArraySize = 1;
            texDesc.CpuAccessFlags = CpuAccessFlags.None;
            texDesc.Usage = ResourceUsage.Default;
            texDesc.Width = width;
            texDesc.Height = height;
            texDesc.MipLevels = 1; // No mip levels
            texDesc.SampleDescription = sampleDesc;
            texDesc.Format = Format.R8G8B8A8_UNorm;

            lightBuffer = ToDispose(new Texture2D(device, texDesc));

            // Render Target View description
            var rtvDesc = new RenderTargetViewDescription();
            rtvDesc.Format = Format.R8G8B8A8_UNorm;
            rtvDesc.Dimension = isMSAA ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D;
            rtvDesc.Texture2D.MipSlice = 0;
            RTV = ToDispose(new RenderTargetView(device, lightBuffer, rtvDesc));

            // SRV description for render targets
            var srvDesc = new ShaderResourceViewDescription();
            srvDesc.Format = Format.R8G8B8A8_UNorm;
            srvDesc.Dimension = isMSAA ? SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled : SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
            srvDesc.Texture2D.MipLevels = -1;
            srvDesc.Texture2D.MostDetailedMip = 0;
            SRV = ToDispose(new ShaderResourceView(device, lightBuffer, srvDesc));

            // Initialize additive blend state (assuming single render target)
            BlendStateDescription bsDesc = new BlendStateDescription();
            bsDesc.RenderTarget[0].IsBlendEnabled = true;
            bsDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            bsDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            bsDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
            bsDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            bsDesc.RenderTarget[0].SourceBlend = BlendOption.One;
            bsDesc.RenderTarget[0].DestinationBlend = BlendOption.One;
            bsDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            blendStateAdd = ToDispose(new BlendState(device, bsDesc));

            // Initialize rasterizer states
            RasterizerStateDescription rsDesc = new RasterizerStateDescription();
            rsDesc.FillMode = FillMode.Solid;
            rsDesc.CullMode = CullMode.Back;
            rsCullBack = ToDispose(new RasterizerState(device, rsDesc));
            rsDesc.CullMode = CullMode.Front;
            rsCullFront = ToDispose(new RasterizerState(device, rsDesc));
            rsDesc.CullMode = CullMode.Front;
            rsDesc.FillMode = FillMode.Wireframe;
            rsWireframe = ToDispose(new RasterizerState(device, rsDesc));

            // Initialize depth state
            var dsDesc = new DepthStencilStateDescription();
            dsDesc.IsStencilEnabled = false;
            dsDesc.IsDepthEnabled = true;

            // Less-than depth comparison
            dsDesc.DepthComparison = Comparison.Less;
            depthLessThan = ToDispose(new DepthStencilState(device, dsDesc));
            // Greater-than depth comparison
            dsDesc.DepthComparison = Comparison.Greater;
            depthGreaterThan = ToDispose(new DepthStencilState(device, dsDesc));
            // Depth/stencil testing disabled
            dsDesc.IsDepthEnabled = false;
            depthDisabled = ToDispose(new DepthStencilState(device, dsDesc));

            // Buffer to light parameters
            perLightBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<PerLight>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            if (isMSAA)
            {
                // Compile and create the vertex shader
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "VSLight", "vs_5_0"))
                    vertexShader = ToDispose(new VertexShader(device, bytecode));
                // Compile pixel shaders
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSAmbientLight", "ps_5_0"))
                    psAmbientLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDirectionalLight", "ps_5_0"))
                    psDirectionalLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSPointLight", "ps_5_0"))
                    psPointLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSSpotLight", "ps_5_0"))
                    psSpotLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDebugLight", "ps_5_0"))
                    psDebugLight = ToDispose(new PixelShader(device, bytecode));
            }
            else
            {
                // Compile and create the vertex shader
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "VSLight", "vs_5_0"))
                    vertexShader = ToDispose(new VertexShader(device, bytecode));
                // Compile pixel shaders
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSAmbientLight", "ps_5_0"))
                    psAmbientLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDirectionalLight", "ps_5_0"))
                    psDirectionalLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSPointLight", "ps_5_0"))
                    psPointLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSSpotLight", "ps_5_0"))
                    psSpotLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDebugLight", "ps_5_0"))
                    psDebugLight = ToDispose(new PixelShader(device, bytecode));
            }
        }
예제 #28
0
        public DX(int width, int height, float screenDepth, float screenNear, bool vSync, bool fullScreen, IntPtr hwnd)
        {
            this.vSync = vSync;
            var factory = new Factory();
            var adapter = factory.GetAdapter(0);
            var monitor = adapter.Outputs[0];
            var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);

            var rational = new Rational(0, 1);
            if(vSync)
            {
                foreach(var mode in modes)
                {
                    if(mode.Width == width && mode.Height == height)
                    {
                        rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                        break;
                    }
                }
            }

            monitor.Dispose();
            adapter.Dispose();
            factory.Dispose();

            var swapChainDesc = new SwapChainDescription
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(width, height, rational, Format.R8G8B8A8_UNorm),
                Usage = Usage.RenderTargetOutput,
                OutputHandle = hwnd,
                SampleDescription = new SampleDescription(1, 0),
                IsWindowed = !fullScreen,
                Flags = SwapChainFlags.None,
                SwapEffect = SwapEffect.Discard
            };

            Device device;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, new[] {FeatureLevel.Level_10_0}, swapChainDesc, out device, out swapChain);

            DXDevice = device;
            DXContext = device.ImmediateContext;

            var backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0);
            renderTarget = new RenderTargetView(device, backBuffer);
            backBuffer.Dispose();

            var depthBufferDesc = new Texture2DDescription
            {
                Width = width,
                Height = height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };
            depthStenBuffer = new Texture2D(device, depthBufferDesc);

            var depthStencilDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF,
                FrontFace = new DepthStencilOperationDescription
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },
                BackFace = new DepthStencilOperationDescription
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                }
            };

            depthStenState = new DepthStencilState(DXDevice, depthStencilDesc);

            DXContext.OutputMerger.SetDepthStencilState(depthStenState, 1);

            var depthStencilViewDesc = new DepthStencilViewDescription
            {
                Format = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource
                {
                    MipSlice = 0
                }
            };

            depthStenView = new DepthStencilView(DXDevice, depthStenBuffer, depthStencilViewDesc);
            DXContext.OutputMerger.SetTargets(depthStenView, renderTarget);

            var rasterDesc = new RasterizerStateDescription
            {
                IsAntialiasedLineEnabled = false,
                CullMode = CullMode.Back,
                DepthBias = 0,
                DepthBiasClamp = .0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled = false,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = .0f
            };

            rasterState = new RasterizerState(DXDevice, rasterDesc);
            DXContext.Rasterizer.State = rasterState;
            DXContext.Rasterizer.SetViewport(0, 0, width, height);

            Projection = Matrix.PerspectiveFovLH((float) (Math.PI / 4), ((float) width) / height, screenNear, screenDepth);
            World = Matrix.Identity;
            Ortho = Matrix.OrthoLH(width, height, screenNear, screenDepth);

            OnCleanup += swapChain.Dispose;
            OnCleanup += rasterState.Dispose;
            OnCleanup += depthStenBuffer.Dispose;
            OnCleanup += depthStenState.Dispose;
            OnCleanup += depthStenView.Dispose;
            OnCleanup += renderTarget.Dispose;
            OnCleanup += DXContext.Dispose;
            OnCleanup += DXDevice.Dispose;
        }
		public void Save(DeviceContext context)
		{
			this.topology = context.InputAssembler.PrimitiveTopology;
			this.layout = context.InputAssembler.InputLayout;
			this.viewports = context.Rasterizer.GetViewports();
			this.scissorRectangles = context.Rasterizer.GetScissorRectangles();
			this.rasterizerState = context.Rasterizer.State;
			this.blendState = context.OutputMerger.GetBlendState(out this.blendFactor, out this.sampleMaskRef);
			this.depthState = context.OutputMerger.GetDepthStencilState(out this.stencilRefRef);
			this.renderTargetView = context.OutputMerger.GetRenderTargets(1, out this.depthStencilView);

			this.ps = context.PixelShader.Get();
			this.psConstantBuffers = context.PixelShader.GetConstantBuffers(0, 4);
			this.psSamplers = context.PixelShader.GetSamplers(0, 4);
			this.psResources = context.PixelShader.GetShaderResources(0, 4);

			this.vs = context.VertexShader.Get();
			this.vsConstantBuffers = context.VertexShader.GetConstantBuffers(0, 4);
			this.vsSamplers = context.VertexShader.GetSamplers(0, 4);
			this.vsResources = context.VertexShader.GetShaderResources(0, 4);

			context.InputAssembler.GetIndexBuffer(out this.ib, out this.ibFormat, out this.ibOffset);
			context.InputAssembler.GetVertexBuffers(0, 1, this.vb, this.vbStride, this.vbOffset);
		}
예제 #30
0
        public Renderer(Game game, SharpDX.Windows.RenderForm renderForm)
        {
            this.game = game;
            int width = renderForm.ClientSize.Width, height = renderForm.ClientSize.Height;

            ResolutionX = width; ResolutionY = height;

            #region 3d device & context
            D3D11.DeviceCreationFlags creationFlags = D3D11.DeviceCreationFlags.BgraSupport;
            #if DEBUG
            creationFlags |= D3D11.DeviceCreationFlags.Debug;
            #endif
            DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
            {
                ModeDescription   = new DXGI.ModeDescription(width, height, new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm),
                SampleDescription = new DXGI.SampleDescription(SampleCount, SampleQuality),
                Usage             = DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = renderForm.Handle,
                IsWindowed        = true,
                SwapEffect        = DXGI.SwapEffect.Discard
            };
            D3D11.Device device;
            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out device, out swapChain);
            Device  = device;
            Context = Device.ImmediateContext;
            #endregion
            #region 2d device & context
            DXGI.Device dxgiDevice = Device.QueryInterface <D3D11.Device1>().QueryInterface <DXGI.Device2>();
            D2DDevice  = new D2D1.Device(dxgiDevice);
            D2DContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);
            D2DFactory = D2DDevice.Factory;
            #endregion
            #region 2d brushes/fonts
            Brushes = new Dictionary <string, D2D1.Brush>();
            Brushes.Add("Red", new D2D1.SolidColorBrush(D2DContext, Color.Red));
            Brushes.Add("Green", new D2D1.SolidColorBrush(D2DContext, Color.Green));
            Brushes.Add("Blue", new D2D1.SolidColorBrush(D2DContext, Color.Blue));
            Brushes.Add("White", new D2D1.SolidColorBrush(D2DContext, Color.White));
            Brushes.Add("Black", new D2D1.SolidColorBrush(D2DContext, Color.Black));
            Brushes.Add("TransparentWhite", new D2D1.SolidColorBrush(D2DContext, new Color(1, 1, 1, .5f)));
            Brushes.Add("TransparentBlack", new D2D1.SolidColorBrush(D2DContext, new Color(0, 0, 0, .5f)));
            Brushes.Add("LightGray", new D2D1.SolidColorBrush(D2DContext, Color.LightGray));
            Brushes.Add("OrangeRed", new D2D1.SolidColorBrush(D2DContext, Color.OrangeRed));
            Brushes.Add("CornflowerBlue", new D2D1.SolidColorBrush(D2DContext, Color.CornflowerBlue));
            Brushes.Add("Yellow", new D2D1.SolidColorBrush(D2DContext, Color.Yellow));
            Brushes.Add("Magenta", new D2D1.SolidColorBrush(D2DContext, Color.Magenta));
            Brushes.Add("RosyBrown", new D2D1.SolidColorBrush(D2DContext, Color.RosyBrown));

            DashStyle = new D2D1.StrokeStyle(D2DFactory, new D2D1.StrokeStyleProperties()
            {
                StartCap   = D2D1.CapStyle.Flat,
                DashCap    = D2D1.CapStyle.Round,
                EndCap     = D2D1.CapStyle.Flat,
                DashStyle  = D2D1.DashStyle.Custom,
                DashOffset = 0,
                LineJoin   = D2D1.LineJoin.Round,
                MiterLimit = 1
            }, new float[] { 4f, 4f });

            FontFactory = new DWrite.Factory();
            SegoeUI24   = new DWrite.TextFormat(FontFactory, "Segoe UI", 24f);
            SegoeUI14   = new DWrite.TextFormat(FontFactory, "Segoe UI", 14f);
            Consolas14  = new DWrite.TextFormat(FontFactory, "Consolas", 14f);
            #endregion

            #region blend states
            D3D11.BlendStateDescription opaqueDesc = new D3D11.BlendStateDescription();
            opaqueDesc.RenderTarget[0].IsBlendEnabled        = false;
            opaqueDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendStateOpaque = new D3D11.BlendState(Device, opaqueDesc);

            D3D11.BlendStateDescription alphaDesc = new D3D11.BlendStateDescription();
            alphaDesc.RenderTarget[0].IsBlendEnabled        = true;
            alphaDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            alphaDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.InverseSourceAlpha;
            alphaDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            alphaDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
            alphaDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero;
            alphaDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            alphaDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendStateTransparent = new D3D11.BlendState(Device, alphaDesc);
            #endregion
            #region rasterizer states
            rasterizerStateSolidCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.Back,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.Back,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateSolidNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.None,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.None,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateSolidCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.Front,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.Front,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            #endregion

            #region depth stencil states
            depthStencilStateDefault = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthComparison  = D3D11.Comparison.Less,
                DepthWriteMask   = D3D11.DepthWriteMask.All
            });

            depthStencilStateNoDepth = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = false,
                IsStencilEnabled = false,
                DepthComparison  = D3D11.Comparison.Less,
                DepthWriteMask   = D3D11.DepthWriteMask.All
            });

            Context.OutputMerger.SetDepthStencilState(depthStencilStateDefault);
            #endregion

            #region blank textures
            D3D11.Texture2D wtex   = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                Width             = 1,
                Height            = 1,
                Format            = DXGI.Format.R32G32B32A32_Float,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                MipLevels         = 0,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags         = D3D11.BindFlags.ShaderResource,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            });
            Context.UpdateSubresource(new Vector4[] { Vector4.One }, wtex);
            WhiteTextureView = new D3D11.ShaderResourceView(Device, wtex);

            D3D11.Texture2D btex = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                Width             = 1,
                Height            = 1,
                Format            = DXGI.Format.R32G32B32A32_Float,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                MipLevels         = 0,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags         = D3D11.BindFlags.ShaderResource,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            });
            Context.UpdateSubresource(new Vector4[] { new Vector4(0, 0, 0, 1) }, btex);
            BlackTextureView = new D3D11.ShaderResourceView(Device, btex);

            AnisotropicSampler = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription()
            {
                AddressU = D3D11.TextureAddressMode.Wrap,
                AddressV = D3D11.TextureAddressMode.Wrap,
                AddressW = D3D11.TextureAddressMode.Wrap,
                Filter   = D3D11.Filter.Anisotropic,
            });
            #endregion
            #region screen vertex & constants
            constants      = new CameraConstants();
            constantBuffer = D3D11.Buffer.Create(Device, D3D11.BindFlags.ConstantBuffer, ref constants);
            #endregion
            //swapChain.GetParent<DXGI.Factory>().MakeWindowAssociation(renderForm.Handle, DXGI.WindowAssociationFlags.);

            Cameras      = new List <Camera>();
            MainCamera   = Camera.CreatePerspective(MathUtil.DegreesToRadians(70), 16 / 9f);
            ActiveCamera = MainCamera;
            Cameras.Add(MainCamera);

            ShadowCamera       = Camera.CreateOrthographic(500, 1);
            ShadowCamera.zNear = 0;
            ShadowCamera.zFar  = 1000;
            ShadowCamera.CreateResources(Device, 1, 0, 1024, 1024);
            //Cameras.Add(ShadowCamera);
            // TODO: Shadow camera has no depth

            Resize(ResolutionX, ResolutionY);
        }
예제 #31
0
        private void InitializeDeviceResources()
        {
            ModeDescription      backBufferDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            SwapChainDescription swapChainDescription  = new SwapChainDescription()
            {
                ModeDescription   = backBufferDescription,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = renderForm.Handle,
                IsWindowed        = true
            };

            D3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDescription, out d3dDevice, out swapChain);
            d3dDeviceContext = d3dDevice.ImmediateContext;

            viewport = new Viewport(0, 0, width, height);
            d3dDeviceContext.Rasterizer.SetViewport(viewport);

            using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            // Create depth buffer. This is a 'texture' where the actual depth values of
            // each pixel is stored
            D3D11.Texture2DDescription depthStencilDescription = new D3D11.Texture2DDescription
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = width,
                Height            = height,
                SampleDescription = swapChain.Description.SampleDescription,
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.DepthStencil,
            };
            var depthStencil = new D3D11.Texture2D(d3dDevice, depthStencilDescription);

            // Create stencil state description.
            var depthStencilStateDesc = new D3D11.DepthStencilStateDescription
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = D3D11.DepthWriteMask.All,
                DepthComparison  = D3D11.Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask  = 0xff,
                StencilWriteMask = 0xff,
                FrontFace        = new D3D11.DepthStencilOperationDescription
                {
                    Comparison         = D3D11.Comparison.Always,
                    PassOperation      = D3D11.StencilOperation.Keep,
                    DepthFailOperation = D3D11.StencilOperation.Increment,
                    FailOperation      = D3D11.StencilOperation.Keep
                },
                BackFace = new D3D11.DepthStencilOperationDescription
                {
                    Comparison         = D3D11.Comparison.Always,
                    PassOperation      = D3D11.StencilOperation.Keep,
                    DepthFailOperation = D3D11.StencilOperation.Decrement,
                    FailOperation      = D3D11.StencilOperation.Keep
                },
            };
            var depthStencilState = new D3D11.DepthStencilState(d3dDevice, depthStencilStateDesc);

            // Create depth stencil view
            depthStencilView = new D3D11.DepthStencilView(d3dDevice, depthStencil, new D3D11.DepthStencilViewDescription
            {
                Dimension = D3D11.DepthStencilViewDimension.Texture2D,
                Format    = Format.D32_Float_S8X24_UInt,
            });

            d3dDeviceContext.OutputMerger.DepthStencilState = depthStencilState;
            d3dDeviceContext.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);
        }
예제 #32
0
        unsafe void InitializeInner(AntiAliasingMode antiAliasingMode)
        {
            worldMatrix = Matrix.Identity;
            textMatrix = Matrix.Identity;

            device = new D3D11.Device(DriverType.Hardware,
                D3D11.DeviceCreationFlags.None,
                new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 });
            tkDevice = TK.GraphicsDevice.New(device);
            deviceContext = device.ImmediateContext;
            deviceContext.Rasterizer.State = device.CreateRasterizerState();

            //TODO: replace with precompiled bytecode
            const string shaderFile = @"..\..\..\GameUtils\Graphics\shaders.fx";
            ShaderBytecode vertexShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "VS", "vs_4_0", ShaderFlags.Debug);
            ShaderBytecode pixelShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "PS", "ps_4_0", ShaderFlags.Debug);
            InitializeShaders(vertexShaderBytecode, pixelShaderBytecode);

            indexBuffers = new D3D11.Buffer[BufferCount];
            vertexBuffers = new D3D11.Buffer[BufferCount];
            for (int i = 0, indexBufferSize = IndexBufferStartSize, vertexBufferSize = VertexBufferStartSize;
                i < BufferCount;
                i++, indexBufferSize <<= BufferSizeStep, vertexBufferSize <<= BufferSizeStep)
            {
                indexBuffers[i] = device.CreateDynamicBuffer(sizeof(int) * indexBufferSize, D3D11.BindFlags.IndexBuffer);
                vertexBuffers[i] = device.CreateDynamicBuffer(sizeof(Vertex) * vertexBufferSize, D3D11.BindFlags.VertexBuffer);
            }
            currentBufferIndex = 0;
            indexBuffer = indexBuffers[0];
            vertexBuffer = vertexBuffers[0];

            //indexBuffer = device.CreateDynamicBuffer(sizeof(int) * IndexBufferSize, D3D11.BindFlags.IndexBuffer);
            //vertexBuffer = device.CreateDynamicBuffer(sizeof(Vertex) * VertexBufferSize, D3D11.BindFlags.VertexBuffer);
            matrixBuffer = device.CreateConstantBuffer(sizeof(MatrixBuffer));
            brushBuffer = device.CreateConstantBuffer(sizeof(Brush.BrushBuffer));

            deviceContext.InputAssembler.SetIndexBuffer(indexBuffer, DXGI.Format.R32_UInt, 0);
            deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, sizeof(Vertex), 0));
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            blendState = device.CreateBlendState();
            deviceContext.OutputMerger.SetBlendState(blendState);

            currentWrapMode = WrapMode.Clamp;
            currentInterpolationMode = InterpolationMode.Linear;
            samplerState = device.CreateSamplerState(WrapMode.Clamp, InterpolationMode.Linear);
            deviceContext.PixelShader.SetSampler(0, samplerState);

            sampleDescription = device.GetMultisamplingLevel(antiAliasingMode);

            defaultDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Always,
                D3D11.StencilOperation.Keep,
                D3D11.StencilOperation.Keep);
            clipDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Never,
                D3D11.StencilOperation.Replace,
                D3D11.StencilOperation.Keep);
            clippingDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Equal,
                D3D11.StencilOperation.Keep,
                D3D11.StencilOperation.Keep);
            deviceContext.OutputMerger.SetDepthStencilState(defaultDepthStencilState);
        }
예제 #33
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                    return;

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                    return;

                _width = Form.ClientSize.Width;
                _height = Form.ClientSize.Height;
                _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 11 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,
            };
            _immediateContext.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);

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

            CreateBuffers();
            LibraryManager.LibraryStarted();
        }
예제 #34
0
        public FrustumShader(Device device)
        {
            // create single vertex buffer
            var stream = new DataStream(24 * VertexPosition.SizeInBytes, true, true);
            stream.Write(new Vector4(-1, -1, 0, 1));
            stream.Write(new Vector4( 1, -1, 0, 1));
            stream.Write(new Vector4( 1, -1, 0, 1));
            stream.Write(new Vector4( 1,  1, 0, 1));
            stream.Write(new Vector4( 1,  1, 0, 1));
            stream.Write(new Vector4(-1,  1, 0, 1));
            stream.Write(new Vector4(-1,  1, 0, 1));
            stream.Write(new Vector4(-1, -1, 0, 1));

            stream.Write(new Vector4(-1, -1, maxZ, 1));
            stream.Write(new Vector4( 1, -1, maxZ, 1));
            stream.Write(new Vector4( 1, -1, maxZ, 1));
            stream.Write(new Vector4( 1,  1, maxZ, 1));
            stream.Write(new Vector4( 1,  1, maxZ, 1));
            stream.Write(new Vector4(-1,  1, maxZ, 1));
            stream.Write(new Vector4(-1,  1, maxZ, 1));
            stream.Write(new Vector4(-1, -1, maxZ, 1));

            stream.Write(new Vector4(-1, -1, 0, 1));
            stream.Write(new Vector4(-1, -1, maxZ, 1));
            stream.Write(new Vector4( 1, -1, 0, 1));
            stream.Write(new Vector4( 1, -1, maxZ, 1));
            stream.Write(new Vector4( 1,  1, 0, 1));
            stream.Write(new Vector4( 1,  1, maxZ, 1));
            stream.Write(new Vector4(-1,  1, 0, 1));
            stream.Write(new Vector4(-1,  1, maxZ, 1));
            stream.Position = 0;

            var vertexBufferDesc = new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                Usage = ResourceUsage.Default,
                SizeInBytes = 24 * VertexPosition.SizeInBytes,
            };
            vertexBuffer = new SharpDX.Direct3D11.Buffer(device, stream, vertexBufferDesc);

            stream.Dispose();

            vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexPosition.SizeInBytes, 0);

            shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/frustumVS.cso"));
            frustumVS = new VertexShader(device, shaderByteCode);
            frustumPS = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/frustumPS.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.Wireframe,
                IsDepthClipEnabled = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = true,
            };
            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            // constant buffer
            var VSConstantBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                SizeInBytes = VSConstantBuffer.size,
                CpuAccessFlags = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags = 0,
            };
            vertexShaderConstantBuffer = new SharpDX.Direct3D11.Buffer(device, VSConstantBufferDesc);

            // Pixel shader constant buffer
            var PSConstantBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                SizeInBytes = PSConstantBuffer.size,
                CpuAccessFlags = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags = 0,
            };
            pixelShaderConstantBuffer = new SharpDX.Direct3D11.Buffer(device, PSConstantBufferDesc);

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });
        }
예제 #35
0
        unsafe void InitializeInner(AntiAliasingMode antiAliasingMode)
        {
            worldMatrix = Matrix.Identity;
            textMatrix  = Matrix.Identity;

            device = new D3D11.Device(DriverType.Hardware,
                                      D3D11.DeviceCreationFlags.None,
                                      new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 });
            tkDevice      = TK.GraphicsDevice.New(device);
            deviceContext = device.ImmediateContext;
            deviceContext.Rasterizer.State = device.CreateRasterizerState();

            //TODO: replace with precompiled bytecode
            const string   shaderFile           = @"..\..\..\GameUtils\Graphics\shaders.fx";
            ShaderBytecode vertexShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "VS", "vs_4_0", ShaderFlags.Debug);
            ShaderBytecode pixelShaderBytecode  = ShaderBytecode.CompileFromFile(shaderFile, "PS", "ps_4_0", ShaderFlags.Debug);

            InitializeShaders(vertexShaderBytecode, pixelShaderBytecode);

            indexBuffers  = new D3D11.Buffer[BufferCount];
            vertexBuffers = new D3D11.Buffer[BufferCount];
            for (int i = 0, indexBufferSize = IndexBufferStartSize, vertexBufferSize = VertexBufferStartSize;
                 i < BufferCount;
                 i++, indexBufferSize <<= BufferSizeStep, vertexBufferSize <<= BufferSizeStep)
            {
                indexBuffers[i]  = device.CreateDynamicBuffer(sizeof(int) * indexBufferSize, D3D11.BindFlags.IndexBuffer);
                vertexBuffers[i] = device.CreateDynamicBuffer(sizeof(Vertex) * vertexBufferSize, D3D11.BindFlags.VertexBuffer);
            }
            currentBufferIndex = 0;
            indexBuffer        = indexBuffers[0];
            vertexBuffer       = vertexBuffers[0];

            //indexBuffer = device.CreateDynamicBuffer(sizeof(int) * IndexBufferSize, D3D11.BindFlags.IndexBuffer);
            //vertexBuffer = device.CreateDynamicBuffer(sizeof(Vertex) * VertexBufferSize, D3D11.BindFlags.VertexBuffer);
            matrixBuffer = device.CreateConstantBuffer(sizeof(MatrixBuffer));
            brushBuffer  = device.CreateConstantBuffer(sizeof(Brush.BrushBuffer));

            deviceContext.InputAssembler.SetIndexBuffer(indexBuffer, DXGI.Format.R32_UInt, 0);
            deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, sizeof(Vertex), 0));
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            blendState = device.CreateBlendState();
            deviceContext.OutputMerger.SetBlendState(blendState);

            currentWrapMode          = WrapMode.Clamp;
            currentInterpolationMode = InterpolationMode.Linear;
            samplerState             = device.CreateSamplerState(WrapMode.Clamp, InterpolationMode.Linear);
            deviceContext.PixelShader.SetSampler(0, samplerState);

            sampleDescription = device.GetMultisamplingLevel(antiAliasingMode);

            defaultDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Always,
                                                                      D3D11.StencilOperation.Keep,
                                                                      D3D11.StencilOperation.Keep);
            clipDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Never,
                                                                   D3D11.StencilOperation.Replace,
                                                                   D3D11.StencilOperation.Keep);
            clippingDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Equal,
                                                                       D3D11.StencilOperation.Keep,
                                                                       D3D11.StencilOperation.Keep);
            deviceContext.OutputMerger.SetDepthStencilState(defaultDepthStencilState);
        }
예제 #36
0
        private void InitializeDeviceResources(DXGI.SwapChain swapChain)
        {
            backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0);
            backbufferRTV     = new D3D11.RenderTargetView(device, backbufferTexture);

            width  = backbufferTexture.Description.Width;
            height = backbufferTexture.Description.Height;

            D3D11.Texture2DDescription sceneTextureDesc = new D3D11.Texture2DDescription
            {
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource,
                Format            = DXGI.Format.R8G8B8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = D3D11.ResourceUsage.Default
            };

            sceneTexture = new D3D11.Texture2D(device, sceneTextureDesc);
            sceneRTV     = new D3D11.RenderTargetView(device, sceneTexture);
            sceneSRV     = new D3D11.ShaderResourceView(device, sceneTexture);

            var depthBufferDesc = new D3D11.Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = DXGI.Format.R32_Typeless,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.DepthStencil | D3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            };

            using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc))
            {
                var depthStencilViewDesc = new D3D11.DepthStencilViewDescription()
                {
                    Format    = DXGI.Format.D32_Float,
                    Dimension = D3D11.DepthStencilViewDimension.Texture2D,
                    Texture2D = { MipSlice = 0 }
                };

                depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc);

                var shaderResourceViewDesc = new D3D11.ShaderResourceViewDescription()
                {
                    Format    = DXGI.Format.R32_Float,
                    Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                    Texture2D = { MipLevels = 1, MostDetailedMip = 0 }
                };

                depthSRV = new D3D11.ShaderResourceView(device, depthStencilBufferTexture, shaderResourceViewDesc);
            }

            var depthStencilDesc = new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = D3D11.DepthWriteMask.All,
                DepthComparison  = D3D11.Comparison.Less,
                IsStencilEnabled = false,
                StencilReadMask  = 0xFF,
                StencilWriteMask = 0xFF,

                FrontFace = new D3D11.DepthStencilOperationDescription()
                {
                    FailOperation      = D3D11.StencilOperation.Keep,
                    DepthFailOperation = D3D11.StencilOperation.Keep,
                    PassOperation      = D3D11.StencilOperation.Keep,
                    Comparison         = D3D11.Comparison.Always
                },

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

            depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc);

            var rasterDesc = new D3D11.RasterizerStateDescription()
            {
                IsAntialiasedLineEnabled = false,
                CullMode                = D3D11.CullMode.Back,
                DepthBias               = 0,
                DepthBiasClamp          = 0.0f,
                IsDepthClipEnabled      = true,
                FillMode                = D3D11.FillMode.Solid,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled    = false,
                IsScissorEnabled        = false,
                SlopeScaledDepthBias    = 0.0f
            };

            rasterizerState = new D3D11.RasterizerState(device, rasterDesc);
        }
예제 #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DepthStencilState" /> class.
 /// </summary>
 /// <param name="device">The device local.</param>
 /// <param name="description">The description.</param>
 private DepthStencilState(DirectXDevice device, DepthStencilStateDescription description)
     : base(device)
 {
     Description = description;
     Resource    = new SharpDX.Direct3D11.DepthStencilState(device, Description);
 }
예제 #38
0
파일: Scene.cs 프로젝트: TomCrypto/Insight
        /// <summary>
        /// Initializes the depth buffer, depth stencil
        /// state, rasterizer state, for rendering.
        /// </summary>
        private void InitializeResources(Size resolution)
        {
            if (depthStencilState != null) depthStencilState.Dispose();
            if ( depthStencilView != null) depthStencilView.Dispose();
            if (  rasterizerState != null) rasterizerState.Dispose();
            if (     cameraBuffer != null) cameraBuffer.Dispose();
            if (      depthBuffer != null) depthBuffer.Dispose();

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

            depthBuffer = new Texture2D(Device, new Texture2DDescription
            {
                MipLevels = 1,
                ArraySize = 1,
                Width = resolution.Width,
                Height = resolution.Height,

                Format = Format.D32_Float,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = Settings.MultisamplingOptions,
            });

            depthStencilView = new DepthStencilView(Device, depthBuffer);

            rasterizerState = new RasterizerState(Device, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
            });

            cameraBuffer = new Buffer(Device, new BufferDescription()
            {
                SizeInBytes = Camera.Size(),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
            });
        }
예제 #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DepthStencilState" /> class.
 /// </summary>
 /// <param name="device">The device local.</param>
 /// <param name="nativeState">State of the native.</param>
 private DepthStencilState(DirectXDevice device, SharpDX.Direct3D11.DepthStencilState nativeState)
     : base(device)
 {
     Description = nativeState.Description;
     Resource    = nativeState;
 }
예제 #40
0
        /// <summary>
        /// Initializes a new engine, sets view , tex manager
        /// camera , mesh manager , texture manager , line manager
        /// volume manager
        /// </summary>
        /// <param name="width">The width of the Render target</param>
        /// <param name="height">The height of the Render target</param>
        public Engine(int Width, int Height, Form form)
        {
            // pass the settings of resolution
            Settings.Resolution = new System.Drawing.Size(Width, Height);

            /// set the handles for full screen or windows
            this.form = form;
            this.FormHandle = form.Handle;

            /// Create the factory which manages general graphics resources
            g_factory = new Factory();
            g_factory.MakeWindowAssociation(this.FormHandle, WindowAssociationFlags.IgnoreAll);

            // find correct adapter
            int adapterCount = g_factory.GetAdapterCount();
            //MessageBox.Show(adapterCount.ToString());

            // we try to select the PerfHUD adapter
            for (int i = 0; i < adapterCount; i++)
            {
                Adapter adapt = g_factory.GetAdapter(i);
                //MessageBox.Show(adapt.Description.Description);

                if (adapt.Description.Description == "NVIDIA PerfHUD")
                {
                    g_device = new Device(
                        adapt,
                        DeviceCreationFlags.Debug);
                }

                Console.WriteLine(i.ToString() + adapt.Description.Description);
            }

            if (g_device == null)
            {

            #if true
                /// Create the DirectX Device
                g_device = new Device(g_factory.GetAdapter(1),
                                      (Settings.Debug) ? DeviceCreationFlags.Debug : DeviceCreationFlags.None,
                                      new FeatureLevel[] { FeatureLevel.Level_11_0 });

            #else
                g_device = new Device(DriverType.Warp,
                                        (Settings.Debug) ? DeviceCreationFlags.Debug : DeviceCreationFlags.None,
                                        new FeatureLevel[] { FeatureLevel.Level_11_0 });
            #endif

                // check if we have one device to our system
                if (!(((g_device.FeatureLevel & FeatureLevel.Level_10_0) != 0) || ((g_device.FeatureLevel & FeatureLevel.Level_10_1) != 0) || ((g_device.FeatureLevel & FeatureLevel.Level_11_0) != 0)))
                {
                    // if we don't have we just simulate
                    #region Create the device base on swapChain
                    /// Create a description of the display mode
                    g_modeDesc = new ModeDescription();
                    /// Standard 32-bit RGBA
                    g_modeDesc.Format = Format.R8G8B8A8_UNorm;
                    /// Refresh rate of 60Hz (60 / 1 = 60)
                    g_modeDesc.RefreshRate = new Rational(60, 1);
                    /// Default
                    g_modeDesc.Scaling = DisplayModeScaling.Unspecified;
                    g_modeDesc.ScanlineOrdering = DisplayModeScanlineOrder.Progressive;

                    /// ClientSize is the size of the
                    /// form without the title and borders
                    g_modeDesc.Width = Width;
                    g_modeDesc.Height = Height;

                    /// Create a description of the samping
                    /// for multisampling or antialiasing
                    g_sampleDesc = new SampleDescription();
                    /// No multisampling
                    g_sampleDesc.Count = 1;
                    g_sampleDesc.Quality = 0;

                    /// Create a description of the swap
                    /// chain or front and back buffers
                    g_swapDesc = new SwapChainDescription();
                    /// link the ModeDescription
                    g_swapDesc.ModeDescription = g_modeDesc;
                    /// link the SampleDescription
                    g_swapDesc.SampleDescription = g_sampleDesc;
                    /// Number of buffers (including the front buffer)
                    g_swapDesc.BufferCount = 1;
                    g_swapDesc.Flags = SwapChainFlags.AllowModeSwitch;
                    g_swapDesc.IsWindowed = true;
                    /// The output window (the windows being rendered to)
                    g_swapDesc.OutputHandle = this.FormHandle;
                    /// Scrap the contents of the buffer every frame
                    g_swapDesc.SwapEffect = SwapEffect.Discard;
                    /// Indicate that this SwapChain
                    /// is going to be a Render target
                    g_swapDesc.Usage = Usage.RenderTargetOutput;

                    //g_swapChain = new SwapChain(g_factory, g_device, g_swapDesc);

                    try
                    {
                        /// Create the actual swap chain
                        /// Here we set and the device type
                        Device.CreateWithSwapChain(DriverType.Warp, (Settings.Debug) ? DeviceCreationFlags.Debug : DeviceCreationFlags.None, new FeatureLevel[] { Settings.FeatureLevel }, g_swapDesc, out g_device, out g_swapChain);
                    }
                    catch (Exception ex)
                    {
                        /// Create the actual swap chain
                        /// Here we set and the device type
                        Device.CreateWithSwapChain(DriverType.Reference, (Settings.Debug) ? DeviceCreationFlags.Debug : DeviceCreationFlags.None, new FeatureLevel[] { Settings.FeatureLevel }, g_swapDesc, out g_device, out g_swapChain);
                    }

                    /// Create the factory which manages general graphics resources
                    g_factory = g_swapChain.GetParent<Factory>();

                    g_factory.MakeWindowAssociation(this.FormHandle, WindowAssociationFlags.IgnoreAll);
                    #endregion
                }
                else
                {
            #if false

                    #region Create the device base on swapChain
                    /// Create a description of the display mode
                    g_modeDesc = new ModeDescription();
                    /// Standard 32-bit RGBA
                    g_modeDesc.Format = Format.R8G8B8A8_UNorm;
                    /// Refresh rate of 60Hz (60 / 1 = 60)
                    g_modeDesc.RefreshRate = new Rational(60, 1);
                    /// Default
                    g_modeDesc.Scaling = DisplayModeScaling.Unspecified;
                    g_modeDesc.ScanlineOrdering = DisplayModeScanlineOrdering.Progressive;

                    /// ClientSize is the size of the
                    /// form without the title and borders
                    g_modeDesc.Width = Width;
                    g_modeDesc.Height = Height;

                    /// Create a description of the samping
                    /// for multisampling or antialiasing
                    g_sampleDesc = new SampleDescription();
                    /// No multisampling
                    g_sampleDesc.Count = 1;
                    g_sampleDesc.Quality = 0;

                    /// Create a description of the swap
                    /// chain or front and back buffers
                    g_swapDesc = new SwapChainDescription();
                    /// link the ModeDescription
                    g_swapDesc.ModeDescription = g_modeDesc;
                    /// link the SampleDescription
                    g_swapDesc.SampleDescription = g_sampleDesc;
                    /// Number of buffers (including the front buffer)
                    g_swapDesc.BufferCount = 1;
                    g_swapDesc.Flags = SwapChainFlags.None;
                    g_swapDesc.IsWindowed = true;
                    /// The output window (the windows being rendered to)
                    g_swapDesc.OutputHandle = FormHandle;
                    /// Scrap the contents of the buffer every frame
                    g_swapDesc.SwapEffect = SwapEffect.Discard;
                    /// Indicate that this SwapChain
                    /// is going to be a Render target
                    g_swapDesc.Usage = Usage.RenderTargetOutput;

                    g_swapChain = new SwapChain(g_factory, g_device, g_swapDesc);

                    #endregion
            #endif
                }

                // set the feature level
                Settings.FeatureLevel = g_device.FeatureLevel;
            }

            /// init mesh manager
            g_MeshManager = new Object3DManager();

            /// init deferred device
            //DeferredDev1 = new DeviceContext( Engine.g_device );
            //DeferredDev2 = new DeviceContext( Engine.g_device );

            // init the image factory...
            g_image_factory = new ImagingFactory();

            /// Set flag to indicate that engine is running
            g_Running = true;

            Logger.WriteLine("The Graphing Engine have be start ");

            // set the event handler
            RenderLoopHandler = new EventHandler(RenderLoop);

            var rtb = new RenderTargetBlendDescription()
            {
                IsBlendEnabled = true,
                BlendOperation = BlendOperation.Add,
                AlphaBlendOperation = BlendOperation.Add,
                DestinationBlend = BlendOption.One,
                DestinationAlphaBlend = BlendOption.Zero,
                SourceBlend = BlendOption.One,
                SourceAlphaBlend = BlendOption.One,
                RenderTargetWriteMask = ColorWriteMaskFlags.All
            };

            BlendStateDescription blendDesc = new BlendStateDescription();
            blendDesc.AlphaToCoverageEnable = false;
            blendDesc.IndependentBlendEnable = false;
            blendDesc.RenderTarget[0] = rtb;

            g_blendState = new BlendState(g_device, blendDesc);

            DepthStencilStateDescription dssd = new DepthStencilStateDescription();
            dssd.DepthComparison = Comparison.Less;
            dssd.IsDepthEnabled = true;
            g_depthStencilState = new DepthStencilState(g_device, new DepthStencilStateDescription());
        }
예제 #41
0
        private void SetDepthBufferState()
        {
            DepthStencilStateDescription description = DepthStencilStateDescription.Default();
            description.DepthComparison = Comparison.LessEqual;
            description.IsDepthEnabled = true;

            depthState = new DepthStencilState(device, description);
        }
예제 #42
0
		/// <summary>
		/// 
		/// </summary>
		void SetupDepthStencilState ()
		{
			var dss	=	new DepthStencilStateDescription();

			dss.DepthComparison		=	Converter.Convert( DepthStencilState.DepthComparison );
			dss.DepthWriteMask		=	DepthStencilState.DepthWriteEnabled ? DepthWriteMask.All : DepthWriteMask.Zero;
			dss.IsDepthEnabled		=	DepthStencilState.DepthEnabled;
			dss.IsStencilEnabled	=	DepthStencilState.StencilEnabled;
			dss.StencilReadMask		=	DepthStencilState.StencilReadMask;
			dss.StencilWriteMask	=	DepthStencilState.StencilWriteMask;

			dss.BackFace.Comparison				=	Converter.Convert( DepthStencilState.BackFaceStencilComparison	);
			dss.BackFace.FailOperation			=	Converter.Convert( DepthStencilState.BackFaceFailOp				);
			dss.BackFace.DepthFailOperation		=	Converter.Convert( DepthStencilState.BackFaceDepthFailOp		);
			dss.BackFace.PassOperation			=	Converter.Convert( DepthStencilState.BackFacePassOp				);

			dss.FrontFace.Comparison			=	Converter.Convert( DepthStencilState.FrontFaceStencilComparison	);
			dss.FrontFace.FailOperation			=	Converter.Convert( DepthStencilState.FrontFaceFailOp				);
			dss.FrontFace.DepthFailOperation	=	Converter.Convert( DepthStencilState.FrontFaceDepthFailOp		);
			dss.FrontFace.PassOperation			=	Converter.Convert( DepthStencilState.FrontFacePassOp				);

			depthStencilRef		=	DepthStencilState.StencilReference;
			depthStencilState	=	new D3DDepthStencilState( device.Device, dss );
		}
예제 #43
0
        internal void Clear()
        {
            if (m_VBs == null)
            {
                m_VBs = new Buffer[8];
                m_strides = new int[8];
                m_CBs = new Buffer[8];

                m_bindings = new SortedDictionary<int, MyBinding>();
                m_srvBindings = new SortedSet<Tuple<int, int>>();

                m_RTVs = new RenderTargetView[8];
                m_SRVs = new ShaderResourceView[8];

                m_constantsVersion = new Dictionary<Buffer, int>();
                m_constantBindings = new Dictionary<MyStageBinding, Buffer>();
                m_srvTableBindings = new Dictionary<MyStageSrvBinding, int>();
                m_srvBindings1 = new List<MyStageSrvBinding>();
            }

            m_IB = null;

            m_inputLayout = null;
            m_ps = null;
            m_vs = null;
            m_gs = null;

            m_RS = null;
            m_BS = null;
            m_DS = null;
            m_stencilRef = 0;

            Array.Clear(m_VBs, 0, m_VBs.Length);
            Array.Clear(m_CBs, 0, m_CBs.Length);

            m_bindings.Clear();
            m_srvBindings.Clear();

            m_constantsVersion.Clear();
            m_constantBindings.Clear();
            m_srvTableBindings.Clear();
            m_srvBindings1.Clear();
        }
        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),
            });
        }
예제 #45
0
 internal void SetDS(DepthStencilState ds, int stencilRef = 0)
 {
     if ((State.m_DS != ds) || (State.m_stencilRef != stencilRef))
     {
         State.m_DS = ds;
         State.m_stencilRef = stencilRef;
         Context.OutputMerger.SetDepthStencilState(ds, stencilRef);
     }
 }
예제 #46
0
        public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle)
        {
            try
            {
                #region Environment Configuration
                // Store the vsync setting.
                VerticalSyncEnabled = SystemConfiguration.VerticalSyncEnabled;

                // Create a DirectX graphics interface factory.
                var factory = new Factory();
                // Use the factory to create an adapter for the primary graphics interface (video card).
                var adapter = factory.GetAdapter(0);
                // Get the primary adapter output (monitor).
                var monitor = adapter.GetOutput(0);
                // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
                var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                // Now go through all the display modes and find the one that matches the screen width and height.
                // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled.
                // Otherwise we use maximum refresh rate.
                var rational = new Rational(0, 1);
                if (VerticalSyncEnabled)
                {
                    foreach (var mode in modes)
                    {
                        if (mode.Width == configuration.Width && mode.Height == configuration.Height)
                        {
                            rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                            break;
                        }
                    }
                }

                // Get the adapter (video card) description.
                var adapterDescription = adapter.Description;

                // Store the dedicated video card memory in megabytes.
                VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10;

                // Convert the name of the video card to a character array and store it.
                VideoCardDescription = adapterDescription.Description;

                // Release the adapter output.
                monitor.Dispose();

                // Release the adapter.
                adapter.Dispose();

                // Release the factory.
                factory.Dispose();
                #endregion

                #region Initialize swap chain and d3d device
                // Initialize the swap chain description.
                var swapChainDesc = new SwapChainDescription()
                {
                    // Set to a single back buffer.
                    BufferCount = 1,
                    // Set the width and height of the back buffer.
                    ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm),
                    // Set the usage of the back buffer.
                    Usage = Usage.RenderTargetOutput,
                    // Set the handle for the window to render to.
                    OutputHandle = windowHandle,
                    // Turn multisampling off.
                    SampleDescription = new SampleDescription(1, 0),
                    // Set to full screen or windowed mode.
                    IsWindowed = !SystemConfiguration.FullScreen,
                    // Don't set the advanced flags.
                    Flags = SwapChainFlags.None,
                    // Discard the back buffer content after presenting.
                    SwapEffect = SwapEffect.Discard
                };

                // Create the swap chain, Direct3D device, and Direct3D device context.
                Device device;
                SwapChain swapChain;
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain);

                Device = device;
                SwapChain = swapChain;
                DeviceContext = device.ImmediateContext;
                #endregion

                #region Initialize buffers
                // Get the pointer to the back buffer.
                var backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0);

                // Create the render target view with the back buffer pointer.
                RenderTargetView = new RenderTargetView(device, backBuffer);

                // Release pointer to the back buffer as we no longer need it.
                backBuffer.Dispose();

                // Initialize and set up the description of the depth buffer.
                var depthBufferDesc = new Texture2DDescription()
                {
                    Width = configuration.Width,
                    Height = configuration.Height,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                };

                // Create the texture for the depth buffer using the filled out description.
                DepthStencilBuffer = new Texture2D(device, depthBufferDesc);
                #endregion

                #region Initialize Depth Enabled Stencil
                // Initialize and set up the description of the stencil state.
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthStencilState = new DepthStencilState(Device, depthStencilDesc);
                #endregion

                #region Initialize Output Merger
                // Set the depth stencil state.
                DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);

                // Initialize and set up the depth stencil view.
                var depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };

                // Create the depth stencil view.
                DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

                // Bind the render target view and depth stencil buffer to the output render pipeline.
                DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
                #endregion

                #region Initialize Raster State
                // Setup the raster description which will determine how and what polygon will be drawn.
                var rasterDesc = new RasterizerStateDescription()
                {
                    IsAntialiasedLineEnabled = false,
                    CullMode = CullMode.Back,
                    DepthBias = 0,
                    DepthBiasClamp = .0f,
                    IsDepthClipEnabled = true,
                    FillMode = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled = false,
                    IsScissorEnabled = false,
                    SlopeScaledDepthBias = .0f
                };

                // Create the rasterizer state from the description we just filled out.
                RasterState = new RasterizerState(Device, rasterDesc);
                #endregion

                #region Initialize Rasterizer
                // Now set the rasterizer state.
                DeviceContext.Rasterizer.State = RasterState;

                // Setup and create the viewport for rendering.
                DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1);
                #endregion

                #region Initialize matrices
                // Setup and create the projection matrix.
                ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4f), ((float)configuration.Width / configuration.Height), SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth);

                // Initialize the world matrix to the identity matrix.
                WorldMatrix = Matrix.Identity;

                // Create an orthographic projection matrix for 2D rendering.
                OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth);
                #endregion

                #region Initialize Depth Disabled Stencil
                // Now create a second depth stencil state which turns off the Z buffer for 2D rendering.
                // The difference is that DepthEnable is set to false.
                // All other parameters are the same as the other depth stencil state.
                var depthDisabledStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);
                #endregion

                #region Initialize Blend States
                // Create an alpha enabled blend state description.
                var blendStateDesc = new BlendStateDescription();
                blendStateDesc.RenderTarget[0].IsBlendEnabled = true;
                blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
                blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
                blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                // Create the blend state using the description.
                AlphaEnableBlendingState = new BlendState(device, blendStateDesc);

                // Modify the description to create an disabled blend state description.
                blendStateDesc.RenderTarget[0].IsBlendEnabled = false;
                // Create the blend state using the description.
                AlphaDisableBlendingState = new BlendState(device, blendStateDesc);
                #endregion

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
예제 #47
0
        private void InitializeDeviceResources(DXGI.SwapChain swapChain)
        {
            backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0);
            backbufferRTV     = new D3D11.RenderTargetView(device, backbufferTexture);

            width  = backbufferTexture.Description.Width;
            height = backbufferTexture.Description.Height;

            var depthBufferDesc = new D3D11.Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = DXGI.Format.D24_UNorm_S8_UInt,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.DepthStencil,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            };

            using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc))
            {
                var depthStencilViewDesc = new D3D11.DepthStencilViewDescription()
                {
                    Format    = DXGI.Format.D24_UNorm_S8_UInt,
                    Dimension = D3D11.DepthStencilViewDimension.Texture2D,
                    Texture2D = new D3D11.DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };

                depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc);
            }



            var depthStencilDesc = new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = D3D11.DepthWriteMask.All,
                DepthComparison  = D3D11.Comparison.Less,
                IsStencilEnabled = false,
                StencilReadMask  = 0xFF,
                StencilWriteMask = 0xFF,

                FrontFace = new D3D11.DepthStencilOperationDescription()
                {
                    FailOperation      = D3D11.StencilOperation.Keep,
                    DepthFailOperation = D3D11.StencilOperation.Keep,
                    PassOperation      = D3D11.StencilOperation.Keep,
                    Comparison         = D3D11.Comparison.Always
                },

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

            depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc);

            var rasterDesc = new D3D11.RasterizerStateDescription()
            {
                IsAntialiasedLineEnabled = false,
                CullMode                = D3D11.CullMode.Back,
                DepthBias               = 0,
                DepthBiasClamp          = 0.0f,
                IsDepthClipEnabled      = false,
                FillMode                = D3D11.FillMode.Solid,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled    = false,
                IsScissorEnabled        = false,
                SlopeScaledDepthBias    = 0.0f
            };

            /*var blendDesc = new D3D11.BlendStateDescription();
             * blendDesc.RenderTarget[0].IsBlendEnabled = true;
             * blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha;
             * blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha;
             * blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add;
             * blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.Zero;
             * blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero;
             * blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add;
             * blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;*/

#if ALPHABLENDING
            var blendDesc = new D3D11.BlendStateDescription();
            blendDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            blendDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.InverseSourceAlpha;
            blendDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            blendDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.Zero;
            blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One;
            blendDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
#endif

#if ADDITIVEBLENDING
            var blendDesc = new D3D11.BlendStateDescription();
            blendDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            blendDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.DestinationAlpha;
            blendDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            blendDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
            blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One;
            blendDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
#endif



            //     RenderTarget[0].BlendOpSharpDX.Direct3D11.BlendOperation.Add RenderTarget[0].SrcBlendAlphaSharpDX.Direct3D11.BlendOption.One
            //     RenderTarget[0].DestBlendAlphaSharpDX.Direct3D11.BlendOption.Zero RenderTarget[0].BlendOpAlphaSharpDX.Direct3D11.BlendOperation.Add
            //     RenderTarget[0].RenderTargetWriteMaskSharpDX.Direct3D11.ColorWriteMaskFlags.All


            blendState      = new D3D11.BlendState(device, blendDesc);
            rasterizerState = new D3D11.RasterizerState(device, rasterDesc);
        }