Пример #1
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);
        }
Пример #2
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);

        }
Пример #3
0
        public DepthState(GxContext context)
        {
            mContext = context;

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

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

                DepthComparison = Comparison.LessEqual,
                DepthWriteMask = DepthWriteMask.All,
                IsDepthEnabled = true,
                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF
            };

            mChanged = true;
        }
Пример #4
0
        /// <summary>
        /// Function to build the Direct3D 11 depth/stencil state.
        /// </summary>
        /// <param name="device">The device object used to create the state.</param>
        /// <returns>The D3D11 depth/stencil state.</returns>
        internal D3D11.DepthStencilState GetD3D11DepthStencilState(D3D11.Device5 device)
        {
            var desc = new D3D11.DepthStencilStateDescription
            {
                BackFace = new D3D11.DepthStencilOperationDescription
                {
                    DepthFailOperation = (D3D11.StencilOperation)BackFaceStencilOp.DepthFailOperation,
                    Comparison         = (D3D11.Comparison)BackFaceStencilOp.Comparison,
                    PassOperation      = (D3D11.StencilOperation)BackFaceStencilOp.PassOperation,
                    FailOperation      = (D3D11.StencilOperation)BackFaceStencilOp.FailOperation
                },
                FrontFace = new D3D11.DepthStencilOperationDescription
                {
                    DepthFailOperation = (D3D11.StencilOperation)FrontFaceStencilOp.DepthFailOperation,
                    Comparison         = (D3D11.Comparison)FrontFaceStencilOp.Comparison,
                    PassOperation      = (D3D11.StencilOperation)FrontFaceStencilOp.PassOperation,
                    FailOperation      = (D3D11.StencilOperation)FrontFaceStencilOp.FailOperation
                },
                DepthComparison  = (D3D11.Comparison)DepthComparison,
                DepthWriteMask   = IsDepthWriteEnabled ? D3D11.DepthWriteMask.All : D3D11.DepthWriteMask.Zero,
                IsDepthEnabled   = IsDepthEnabled,
                IsStencilEnabled = IsStencilEnabled,
                StencilReadMask  = StencilReadMask,
                StencilWriteMask = StencilWriteMask
            };

            return(new D3D11.DepthStencilState(device, desc)
            {
                DebugName = nameof(GorgonDepthStencilState)
            });
        }
Пример #5
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);
            }
        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),
            });

        }
Пример #7
0
        private DepthStencilState CreateNewDepthStencilState(ref DepthStencilStateDescription description)
        {
            SharpDX.Direct3D11.DepthStencilStateDescription dssDesc = new SharpDX.Direct3D11.DepthStencilStateDescription
            {
                DepthComparison = D3D11Formats.VdToD3D11DepthComparison(description.ComparisonKind),
                IsDepthEnabled  = description.DepthTestEnabled,
                DepthWriteMask  = description.DepthWriteEnabled ? DepthWriteMask.All : DepthWriteMask.Zero
            };

            return(new DepthStencilState(_device, dssDesc));
        }
Пример #8
0
        private DepthStencilState CreateNewDepthStencilState(ref DepthStencilStateDescription description)
        {
            SharpDX.Direct3D11.DepthStencilStateDescription dssDesc = new SharpDX.Direct3D11.DepthStencilStateDescription
            {
                DepthComparison  = D3D11Formats.VdToD3D11Comparison(description.DepthComparison),
                IsDepthEnabled   = description.DepthTestEnabled,
                DepthWriteMask   = description.DepthWriteEnabled ? DepthWriteMask.All : DepthWriteMask.Zero,
                IsStencilEnabled = description.StencilTestEnabled,
                FrontFace        = ToD3D11StencilOpDesc(description.StencilFront),
                BackFace         = ToD3D11StencilOpDesc(description.StencilBack),
                StencilReadMask  = description.StencilReadMask,
                StencilWriteMask = description.StencilWriteMask
            };

            return(new DepthStencilState(_device, dssDesc));
        }
Пример #9
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);
        }
Пример #10
0
        public static D3D.DepthStencilState CreateDepthStencilState(this D3D.Device device, D3D.Comparison comparison, D3D.StencilOperation failOperation, D3D.StencilOperation passOperation)
        {
            var operationDesc = new D3D.DepthStencilOperationDescription()
            {
                Comparison         = comparison,
                DepthFailOperation = D3D.StencilOperation.Keep,
                FailOperation      = failOperation,
                PassOperation      = passOperation,
            };
            var depthStencilDesc = new D3D.DepthStencilStateDescription()
            {
                IsDepthEnabled   = false,
                IsStencilEnabled = true,
                StencilReadMask  = byte.MaxValue,
                StencilWriteMask = byte.MaxValue,
                FrontFace        = operationDesc,
                BackFace         = operationDesc,
            };

            return(new D3D.DepthStencilState(device, depthStencilDesc));
        }
Пример #11
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;
        }
Пример #12
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();
        }
Пример #13
0
        /// <summary>
        /// Loads the resource.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="resources">Parent ResourceDictionary.</param>
        protected override void LoadResourceInternal(EngineDevice device, ResourceDictionary resources)
        {
            // Create default blend state
            m_defaultBlendState = new Lazy <D3D11.BlendState>(() =>
            {
                D3D11.BlendStateDescription blendDesc = D3D11.BlendStateDescription.Default();
                return(new D3D11.BlendState(device.DeviceD3D11_1, blendDesc));
            });

            // Create alpha blending blend state
            m_alphaBlendingBlendState = new Lazy <D3D11.BlendState>(() =>
            {
                //Define the blend state (based on http://www.rastertek.com/dx11tut26.html)
                D3D11.BlendStateDescription blendDesc           = D3D11.BlendStateDescription.Default();
                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].DestinationAlphaBlend = D3D11.BlendOption.One;
                blendDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
                blendDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Maximum;
                blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;

                //Create the blendstate object
                return(new D3D11.BlendState(device.DeviceD3D11_1, blendDesc));
            });

            // Create default depth stencil state
            m_depthStencilStateDefault = new Lazy <D3D11.DepthStencilState>(() =>
            {
                D3D11.DepthStencilStateDescription stateDesc = D3D11.DepthStencilStateDescription.Default();
                stateDesc.DepthComparison = D3D11.Comparison.LessEqual;
                return(new D3D11.DepthStencilState(device.DeviceD3D11_1, stateDesc));
            });

            // Create the depth stencil state for diabling z writes
            m_depthStencilStateDisableZWrites = new Lazy <D3D11.DepthStencilState>(() =>
            {
                D3D11.DepthStencilStateDescription stateDesc = D3D11.DepthStencilStateDescription.Default();
                stateDesc.DepthWriteMask  = D3D11.DepthWriteMask.Zero;
                stateDesc.DepthComparison = D3D11.Comparison.LessEqual;
                return(new D3D11.DepthStencilState(device.DeviceD3D11_1, stateDesc));
            });

            m_depthStencilStateAllwaysPass = new Lazy <D3D11.DepthStencilState>(() =>
            {
                D3D11.DepthStencilStateDescription stateDesc = D3D11.DepthStencilStateDescription.Default();
                stateDesc.DepthWriteMask  = D3D11.DepthWriteMask.Zero;
                stateDesc.DepthComparison = D3D11.Comparison.Always;
                stateDesc.IsDepthEnabled  = false;
                return(new D3D11.DepthStencilState(device.DeviceD3D11_1, stateDesc));
            });

            // Create the depth stencil state for inverting z logic
            m_depthStencilStateInvertedZTest = new Lazy <D3D11.DepthStencilState>(() =>
            {
                D3D11.DepthStencilStateDescription stateDesc = D3D11.DepthStencilStateDescription.Default();
                stateDesc.DepthComparison = D3D11.Comparison.Greater;
                stateDesc.DepthWriteMask  = D3D11.DepthWriteMask.Zero;
                return(new D3D11.DepthStencilState(device.DeviceD3D11_1, stateDesc));
            });

            // Create default rasterizer state
            m_rasterStateDefault = new Lazy <D3D11.RasterizerState>(() =>
            {
                return(new D3D11.RasterizerState(device.DeviceD3D11_1, D3D11.RasterizerStateDescription.Default()));
            });

            // Create a raster state with depth bias
            m_rasterStateBiased = new Lazy <D3D11.RasterizerState>(() =>
            {
                D3D11.RasterizerStateDescription rasterDesc = D3D11.RasterizerStateDescription.Default();
                rasterDesc.DepthBias = GraphicsHelper.GetDepthBiasValue(device, -0.00003f);
                return(new D3D11.RasterizerState(device.DeviceD3D11_1, rasterDesc));
            });

            // Create a raster state for wireframe rendering
            m_rasterStateWireframe = new Lazy <SharpDX.Direct3D11.RasterizerState>(() =>
            {
                D3D11.RasterizerStateDescription rasterDesc = D3D11.RasterizerStateDescription.Default();
                rasterDesc.FillMode = D3D11.FillMode.Wireframe;
                return(new D3D11.RasterizerState(device.DeviceD3D11_1, rasterDesc));
            });

            // Create the rasterizer state for line rendering
            m_rasterStateLines = new Lazy <D3D11.RasterizerState>(() =>
            {
                D3D11.RasterizerStateDescription stateDesc = D3D11.RasterizerStateDescription.Default();
                stateDesc.CullMode = D3D11.CullMode.None;
                stateDesc.IsAntialiasedLineEnabled = true;
                stateDesc.FillMode = D3D11.FillMode.Solid;
                return(new D3D11.RasterizerState(device.DeviceD3D11_1, stateDesc));
            });

            // Create sampler states
            m_samplerStateLow = new Lazy <D3D11.SamplerState>(() =>
            {
                return(GraphicsHelper.CreateDefaultTextureSampler(device, TextureSamplerQualityLevel.Low));
            });
            m_samplerStateMedium = new Lazy <D3D11.SamplerState>(() =>
            {
                return(GraphicsHelper.CreateDefaultTextureSampler(device, TextureSamplerQualityLevel.Medium));
            });
            m_samplerStateHigh = new Lazy <D3D11.SamplerState>(() =>
            {
                return(GraphicsHelper.CreateDefaultTextureSampler(device, TextureSamplerQualityLevel.High));
            });
        }
Пример #14
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);
        }
Пример #15
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),
            });
        }
Пример #16
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="GraphicsDevice"/>.</param>
 /// <param name="description">A depth-stencil state description</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(GraphicsDevice device, DepthStencilStateDescription description)
 {
     return new DepthStencilState(device, description);
 }
Пример #17
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(GraphicsDevice device, DepthStencilStateDescription description) : base(device.MainDevice)
 {
     Description = description;
     Initialize(new Direct3D11.DepthStencilState(GraphicsDevice, Description));
 }
Пример #18
0
 public static D3D.DepthStencilState CreateDepthStencilState(this D3D.Device device, D3D.Comparison comparison, D3D.StencilOperation failOperation, D3D.StencilOperation passOperation)
 {
     var operationDesc = new D3D.DepthStencilOperationDescription()
     {
         Comparison = comparison,
         DepthFailOperation = D3D.StencilOperation.Keep,
         FailOperation = failOperation,
         PassOperation = passOperation,
     };
     var depthStencilDesc = new D3D.DepthStencilStateDescription()
     {
         IsDepthEnabled = false,
         IsStencilEnabled = true,
         StencilReadMask = byte.MaxValue,
         StencilWriteMask = byte.MaxValue,
         FrontFace = operationDesc,
         BackFace = operationDesc,
     };
     return new D3D.DepthStencilState(device, depthStencilDesc);
 }
        internal static void Init()
        {

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.All;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = false;
                DepthTestWrite = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = false;
                DepthTest = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = false;
                IgnoreDepthStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.All;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0xFF;
                desc.StencilWriteMask = 0xFF;
                desc.BackFace.Comparison = Comparison.Always;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Replace;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                WriteDepthAndStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0xFF;
                desc.StencilWriteMask = 0x80;
                desc.BackFace.Comparison = Comparison.Always;
                desc.BackFace.DepthFailOperation = StencilOperation.Replace;
                desc.BackFace.FailOperation = StencilOperation.Replace;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                MarkEdgeInStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = true;
                desc.DepthComparison = Comparison.Equal;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x00;
                desc.StencilWriteMask = 0x40;
                desc.BackFace.Comparison = Comparison.Always;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Replace;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                OutlineMesh = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x40;
                desc.StencilWriteMask = 0x0;
                desc.BackFace.Comparison = Comparison.NotEqual;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                TestOutlineMeshStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x40;
                desc.StencilWriteMask = 0x0;
                desc.BackFace.Comparison = Comparison.Equal;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                TestHighlightMeshStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0xFF;
                desc.StencilWriteMask = 0x0;
                desc.BackFace.Comparison = Comparison.NotEqual;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                DiscardTestStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x80;
                desc.StencilWriteMask = 0x00;
                desc.BackFace.Comparison = Comparison.Equal;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                TestEdgeStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x80;
                desc.StencilWriteMask = 0x00;
                desc.BackFace.Comparison = Comparison.Equal;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                TestDepthAndEdgeStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            MarkIfInsideCascade = new DepthStencilId[MyRender11.Settings.ShadowCascadeCount];

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = true;
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Less : Comparison.Greater;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x00;
                desc.BackFace.Comparison = Comparison.Always;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;

                for (int cascadeIndex = 0; cascadeIndex < MarkIfInsideCascade.Length; ++cascadeIndex)
                {
                    desc.StencilWriteMask = (byte) (0x01 << cascadeIndex);
                    MarkIfInsideCascade[cascadeIndex] = MyPipelineStates.CreateDepthStencil(desc);
                }
            }
        }
Пример #20
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");
        }
Пример #21
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);
        }
Пример #22
0
 public void Import(ref DepthStencilStateDescription dss)
 {
     DepthComparison = dss.DepthComparison;
     DepthWriteMask = dss.DepthWriteMask;
     BackFace = DepthStencilOperation.Import(ref dss.BackFace);
     FrontFace = DepthStencilOperation.Import(ref dss.FrontFace);
     IsDepthEnabled = dss.IsDepthEnabled;
     IsStencilEnabled = dss.IsStencilEnabled;
     StencilReadMask = dss.StencilReadMask;
     StencilWriteMask = dss.StencilWriteMask;
 }
Пример #23
0
 /// <summary>
 ///   Constructs a new <see cref = "T:SharpDX.Direct3D11.DepthStencilState" /> based on the specified description.
 /// </summary>
 /// <param name = "device">The device with which to associate the state object.</param>
 /// <param name = "description">The state description.</param>
 /// <returns>The newly created object.</returns>
 /// <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 DepthStencilState(Device device, DepthStencilStateDescription description)
     : base(IntPtr.Zero)
 {
     device.CreateDepthStencilState(ref description, this);
 }
Пример #24
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="GraphicsDevice"/>.</param>
 /// <param name="name">Name of this depth stencil state.</param>
 /// <param name="description">A depth-stencil state description</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(GraphicsDevice device, string name, DepthStencilStateDescription description)
 {
     return new DepthStencilState(device, description) {Name = name};
 }
        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));
            }
        }
Пример #26
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(GraphicsDevice device, Direct3D11.DepthStencilState nativeState) : base(device.MainDevice)
 {
     Description = nativeState.Description;
     Initialize(nativeState);
 }
Пример #27
0
 public void Export(ref DepthStencilStateDescription dss)
 {
     dss.DepthComparison = DepthComparison;
     dss.DepthWriteMask = DepthWriteMask;
     dss.BackFace = DepthStencilOperation.Export(BackFace);
     dss.FrontFace = DepthStencilOperation.Export(FrontFace);
     dss.IsDepthEnabled = IsDepthEnabled;
     dss.IsStencilEnabled = IsStencilEnabled;
     dss.StencilReadMask = StencilReadMask;
     dss.StencilWriteMask = StencilWriteMask;
 }
Пример #28
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();
        }
Пример #29
0
        private void initializeDepthStencilStates()
        {
            standardDepthStencilStates = new SharpDX.Direct3D11.DepthStencilState[4];

            DepthStencilStateDescription templateDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled = false,
                DepthComparison = Comparison.Never,
                DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.Zero,
                IsStencilEnabled = false
            };

            standardDepthStencilStates[(int)DepthStencilMode.Off] = new DepthStencilState(device, templateDesc);
            templateDesc.DepthComparison = Comparison.LessEqual;
            templateDesc.IsDepthEnabled = true;
            standardDepthStencilStates[(int)DepthStencilMode.ZReadOnly] = new DepthStencilState(device, templateDesc);

            templateDesc.IsDepthEnabled = false;
            templateDesc.DepthWriteMask = DepthWriteMask.All;
            standardDepthStencilStates[(int)DepthStencilMode.ZWriteOnly] = new DepthStencilState(device, templateDesc);

            templateDesc.IsDepthEnabled = true;
            templateDesc.DepthWriteMask = DepthWriteMask.All;
            standardDepthStencilStates[(int)DepthStencilMode.ZReadWrite] = new DepthStencilState(device, templateDesc);
        }
        internal static void Init()
        {
            // Bits in stencil buffer: 76543210
            // bits 3-0 used in CSM
            // bit 4 used for stereo rendering mask
            // bit 6 used for outlines

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.All;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = false;
                DepthTestWrite = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = false;
                DepthTest = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = false;
                IgnoreDepthStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.All;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0xFF;
                desc.StencilWriteMask = 0xFF;
                desc.BackFace.Comparison = Comparison.Always;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Replace;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                WriteDepthAndStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0xFF;
                desc.StencilWriteMask = 0x80;
                desc.BackFace.Comparison = Comparison.Always;
                desc.BackFace.DepthFailOperation = StencilOperation.Replace;
                desc.BackFace.FailOperation = StencilOperation.Replace;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                MarkEdgeInStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = true;
                desc.DepthComparison = Comparison.Equal;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x00;
                desc.StencilWriteMask = 0x40;
                desc.BackFace.Comparison = Comparison.Always;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Replace;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                OutlineMesh = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x40;
                desc.StencilWriteMask = 0x0;
                desc.BackFace.Comparison = Comparison.NotEqual;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                TestOutlineMeshStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x40;
                desc.StencilWriteMask = 0x0;
                desc.BackFace.Comparison = Comparison.Equal;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                TestHighlightMeshStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x80;
                desc.StencilWriteMask = 0x00;
                desc.BackFace.Comparison = Comparison.Equal;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                TestEdgeStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = true;
                desc.StencilReadMask = 0x80;
                desc.StencilWriteMask = 0x00;
                desc.BackFace.Comparison = Comparison.Equal;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Keep;
                desc.FrontFace = desc.BackFace;
                TestDepthAndEdgeStencil = MyPipelineStates.CreateDepthStencil(desc);
            }

            MarkIfInsideCascade = new DepthStencilId[8];

            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.IsDepthEnabled = true;
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Less : Comparison.Greater;
                desc.DepthWriteMask = DepthWriteMask.Zero;

                for (int cascadeIndex = 0; cascadeIndex < MarkIfInsideCascade.Length; ++cascadeIndex)
                {
                    desc.IsStencilEnabled = true;
                    desc.StencilReadMask = 0xF;
                    desc.StencilWriteMask = 0xF;
                    desc.BackFace.Comparison = cascadeIndex == 0 ? Comparison.Always : Comparison.Greater;
                    desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                    desc.BackFace.FailOperation = StencilOperation.Keep;
                    desc.BackFace.PassOperation = StencilOperation.Replace;
                    desc.FrontFace = desc.BackFace;
                    MarkIfInsideCascade[cascadeIndex] = MyPipelineStates.CreateDepthStencil(desc);
                }
            }


            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.All;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = true;
                desc.StencilWriteMask = GetStereoMask();
                desc.StencilReadMask = GetStereoMask();
                desc.BackFace.Comparison = Comparison.GreaterEqual;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                StereoDefaultDepthState = MyPipelineStates.CreateDepthStencil(desc);
            }
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilWriteMask = GetStereoMask();
                desc.StencilReadMask = GetStereoMask();
                desc.BackFace.Comparison = Comparison.Always;
                desc.BackFace.DepthFailOperation = StencilOperation.Replace; 
                desc.BackFace.FailOperation = StencilOperation.Replace;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                StereoStereoStencilMask = MyPipelineStates.CreateDepthStencil(desc);
            }
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.All;
                desc.IsDepthEnabled = true;
                desc.IsStencilEnabled = true;
                desc.StencilWriteMask = GetStereoMask();
                desc.StencilReadMask = GetStereoMask();
                desc.BackFace.Comparison = Comparison.GreaterEqual;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                StereoDepthTestWrite = MyPipelineStates.CreateDepthStencil(desc);
            }
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription();
                desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
                desc.DepthWriteMask = DepthWriteMask.Zero;
                desc.IsDepthEnabled = false;
                desc.IsStencilEnabled = true;
                desc.StencilWriteMask = GetStereoMask();
                desc.StencilReadMask = GetStereoMask();
                desc.BackFace.Comparison = Comparison.GreaterEqual;
                desc.BackFace.DepthFailOperation = StencilOperation.Keep;
                desc.BackFace.FailOperation = StencilOperation.Keep;
                desc.BackFace.PassOperation = StencilOperation.Replace;
                desc.FrontFace = desc.BackFace;
                StereoIgnoreDepthStencil = MyPipelineStates.CreateDepthStencil(desc);
            }
        }
Пример #31
0
 public static DepthStencilId CreateDepthStencil(DepthStencilStateDescription description)
 {
     DepthStencilId id = new DepthStencilId();
     CreateDepthStencil(ref id, description);
     return id;
 }
Пример #32
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;
		}
        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),
            });
        }
Пример #34
0
        internal static DepthStencilId CreateDepthStencil(DepthStencilStateDescription description)
        {
            var id = new DepthStencilId { Index = DepthStencilStates.Allocate() };
            MyArrayHelpers.Reserve(ref DepthStencilObjects, id.Index + 1);

            DepthStencilStates.Data[id.Index] = description;

            InitDepthStencilState(id);
            DepthStencilIndices.Add(id);

            return id;
        }
Пример #35
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);
        }
Пример #36
0
        public static void CreateDepthStencil(ref DepthStencilId id, DepthStencilStateDescription description)
        {
            if (id == DepthStencilId.NULL)
            {
                id = new DepthStencilId(DepthStencilStates.Allocate());
                MyArrayHelpers.Reserve(ref DepthStencilObjects, id.Index + 1);
                DepthStencilIndices.Add(id);
            }
            else
            {
                DepthStencilObjects[id.Index].Dispose();
            }

            DepthStencilStates.Data[id.Index] = description;
            InitDepthStencilState(id);
        }
Пример #37
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;
            }
        }
Пример #38
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);
        }
Пример #39
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();
        }
        static MyDepthStencilState()
        {
            DepthStencilStateDescription desc = new DepthStencilStateDescription();

            desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
            desc.DepthWriteMask = DepthWriteMask.All;
            desc.IsDepthEnabled = true;
            desc.IsStencilEnabled = false;
            DepthTestWrite = MyPipelineStates.CreateDepthStencil(desc);

            desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Greater : Comparison.Less;
            desc.DepthWriteMask = DepthWriteMask.Zero;
            desc.IsDepthEnabled = true;
            desc.IsStencilEnabled = false;
            DepthTest = MyPipelineStates.CreateDepthStencil(desc);

            desc.IsDepthEnabled = false;
            desc.IsStencilEnabled = false;
            IgnoreDepthStencil = MyPipelineStates.CreateDepthStencil(desc);

            desc.IsDepthEnabled = false;
            desc.IsStencilEnabled = true;
            desc.StencilReadMask = 0xFF;
            desc.StencilWriteMask = 0x80;
            desc.BackFace.Comparison = Comparison.Always;
            desc.BackFace.DepthFailOperation = StencilOperation.Replace;
            desc.BackFace.FailOperation = StencilOperation.Replace;
            desc.BackFace.PassOperation = StencilOperation.Replace;
            desc.FrontFace = desc.BackFace;
            MarkAAEdge = MyPipelineStates.CreateDepthStencil(desc);

            desc.IsDepthEnabled = false;
            desc.IsStencilEnabled = true;
            desc.StencilReadMask = 0x80;
            desc.StencilWriteMask = 0x00;
            desc.BackFace.Comparison = Comparison.Equal;
            desc.BackFace.DepthFailOperation = StencilOperation.Keep;
            desc.BackFace.FailOperation = StencilOperation.Keep;
            desc.BackFace.PassOperation = StencilOperation.Keep;
            desc.FrontFace = desc.BackFace;
            TestAAEdge = MyPipelineStates.CreateDepthStencil(desc);

            MarkIfInside = new DepthStencilId[4];

            desc.IsDepthEnabled = true;
            desc.DepthComparison = MyRender11.UseComplementaryDepthBuffer ? Comparison.Less : Comparison.Greater;
            desc.DepthWriteMask = DepthWriteMask.Zero;
            desc.IsStencilEnabled = true;
            desc.StencilReadMask = 0x00;
            desc.StencilWriteMask = 0x01;
            desc.BackFace.Comparison = Comparison.Always;
            desc.BackFace.DepthFailOperation = StencilOperation.Keep;
            desc.BackFace.FailOperation = StencilOperation.Keep;
            desc.BackFace.PassOperation = StencilOperation.Replace;
            desc.FrontFace = desc.BackFace;
            MarkIfInside[0] = MyPipelineStates.CreateDepthStencil(desc);

            desc.StencilWriteMask = 0x02;
            MarkIfInside[1] = MyPipelineStates.CreateDepthStencil(desc);
            desc.StencilWriteMask = 0x04;
            MarkIfInside[2] = MyPipelineStates.CreateDepthStencil(desc);
            desc.StencilWriteMask = 0x08;
            MarkIfInside[3] = MyPipelineStates.CreateDepthStencil(desc);
        }
Пример #41
0
 /// <summary>
 ///   Constructs a new <see cref = "T:SharpDX.Direct3D11.DepthStencilState" /> based on the specified description.
 /// </summary>
 /// <param name = "device">The device with which to associate the state object.</param>
 /// <param name = "description">The state description.</param>
 /// <returns>The newly created object.</returns>
 /// <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 DepthStencilState(Device device, DepthStencilStateDescription description)
     : base(IntPtr.Zero)
 {
     device.CreateDepthStencilState(ref description, this);
 }
Пример #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
        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);
        }