Example #1
0
        private void InitializeDeviceResources()
        {
            SharpDX.DXGI.ModeDescription      backBufferDesc = new SharpDX.DXGI.ModeDescription(Width, Height, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm);
            SharpDX.DXGI.SwapChainDescription swapChainDesc  = new SharpDX.DXGI.SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = renderForm.Handle,
                IsWindowed        = true
            };
            SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            var factory = swapChain.GetParent <SharpDX.DXGI.Factory>();

            factory.MakeWindowAssociation(renderForm.Handle, SharpDX.DXGI.WindowAssociationFlags.IgnoreAll);
            d3dDeviceContext = d3dDevice.ImmediateContext;
            using (SharpDX.Direct3D11.Texture2D backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
            {
                renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            // Set viewport
            viewport = new SharpDX.Viewport(0, 0, Width, Height);
            d3dDeviceContext.Rasterizer.SetViewport(viewport);
        }
Example #2
0
        static Vector3 CalculateProjectedPosition()
        {
            Vector3 directionFromSunNormalized = MyRender.Sun.Direction;

            // Tell the lensflare component where our camera is positioned.
            m_view       = MyRenderCamera.ViewMatrix;
            m_projection = MyRenderCamera.ProjectionMatrix;

            // The sun is infinitely distant, so it should not be affected by the
            // position of the camera. Floating point math doesn't support infinitely
            // distant vectors, but we can get the same result by making a copy of our
            // view matrix, then resetting the view translation to zero. Pretending the
            // camera has not moved position gives the same result as if the camera
            // was moving, but the light was infinitely far away. If our flares came
            // from a local object rather than the sun, we would use the original view
            // matrix here.
            var infiniteView = (Matrix)m_view;

            infiniteView.Translation = Vector3.Zero;

            // Project the light position into 2D screen space.
            SharpDX.Viewport viewport = MyRender.GraphicsDevice.Viewport;

            Vector3 projectedPosition = SharpDXHelper.ToXNA(
                viewport.Project(SharpDXHelper.ToSharpDX(-directionFromSunNormalized), SharpDXHelper.ToSharpDX(m_projection), SharpDXHelper.ToSharpDX(infiniteView), SharpDXHelper.ToSharpDX(Matrix.Identity)));

            return(projectedPosition);
        }
        /// <summary>	
        /// Get the array of {{viewports}} bound  to the {{rasterizer stage}} 	
        /// </summary>	
        /// <returns>An array of viewports (see <see cref="SharpDX.Viewport"/>).</returns>
        /// <unmanaged>void RSGetViewports([InOut] int* NumViewports,[Out, Buffer, Optional] D3D10_VIEWPORT* pViewports)</unmanaged>
        public SharpDX.Viewport[] GetViewports()
        {
            int numViewports = 0;

            GetViewports(ref numViewports, null);

            SharpDX.Viewport[] viewports = new SharpDX.Viewport[numViewports];
            GetViewports(ref numViewports, viewports);

            return viewports;
        }
Example #4
0
        /// <summary>
        /// Get the array of {{viewports}} bound  to the {{rasterizer stage}}
        /// </summary>
        /// <returns>An array of viewports (see <see cref="SharpDX.Viewport"/>).</returns>
        /// <unmanaged>void RSGetViewports([InOut] int* NumViewports,[Out, Buffer, Optional] D3D10_VIEWPORT* pViewports)</unmanaged>
        public SharpDX.Viewport[] GetViewports()
        {
            int numViewports = 0;

            GetViewports(ref numViewports, null);

            SharpDX.Viewport[] viewports = new SharpDX.Viewport[numViewports];
            GetViewports(ref numViewports, viewports);

            return(viewports);
        }
Example #5
0
        void CreateBuffers(int width, int height)
        {
            using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) {
                renderTargetView = new RenderTargetView(D3DDevice, backBuffer);
            }

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

            using (var zBufferTexture = new Texture2D(D3DDevice, zBufferTextureDescription)) {
                depthStencilView = new DepthStencilView(D3DDevice, zBufferTexture);
            }

            var depthEnabledStencilState = new DepthStencilState(D3DDevice, D3DDepthStencilStateDescriptions.DepthEnabled);

            var viewport = new SharpDX.Viewport(0, 0, width, height);

            ImmediateContext.Rasterizer.SetViewport(viewport);
            ImmediateContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);

            //no zbuffer and DepthStencil
            //ImmediateContext.OutputMerger.SetRenderTargets(renderTargetView);

            //with zbuffer / DepthStencil
            ImmediateContext.OutputMerger.SetDepthStencilState(depthEnabledStencilState, 0);

            //var blendStateDesc = new BlendStateDescription();
            //blendStateDesc.RenderTarget[0].IsBlendEnabled = true;
            //blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            //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;
            //var blend = new BlendState(Device, blendStateDesc);

            //var blendFactor = new Color4(0, 0, 0, 0);
            //Device.ImmediateContext.OutputMerger.SetBlendState(blend, blendFactor, -1);
        }
Example #6
0
        public void PropertyStasher_modifyCascadedProperty_isRestoredToInitialValue()
        {
            var context  = new OperatorPartContext();
            var viewport = new SharpDX.ViewportF(0, 0, 320, 200);

            context.Viewport = viewport;

            using (new PropertyStasher <OperatorPartContext>(context, "Viewport")) {
                var viewport2 = new SharpDX.Viewport(0, 0, 640, 480);
                context.Viewport = viewport2;
                using (new PropertyStasher <OperatorPartContext>(context, "Viewport")) {
                    context.Viewport = new SharpDX.Viewport(0, 0, 1024, 768);
                }
                Assert.AreEqual(viewport2, context.Viewport);
            }

            Assert.AreEqual(viewport, context.Viewport);
        }
Example #7
0
        protected override void Initialize()
        {
            Window.Title = title;

            base.Initialize();

            if (Initialised != null)
            {
                Initialised(this);
            }

            FearLog.Initialise();

            SharpDX.ViewportF viewport = new SharpDX.Viewport(0, 0, (int)DEFAULT_WIDTH, (int)DEFAULT_HEIGHT, 0.0f, 1.0f);
            graphicsDeviceManager.GraphicsDevice.SetViewport(viewport);

            game.Startup(this);
        }
Example #8
0
        private int mipLevels = 1; //Mips will screw with the readings from the depth texture.

        public ShadowMap(GraphicsDevice device, int width, int height)
        {
            viewport = new SharpDX.Viewport(0, 0, width, height, 0.0f, 1.0f);

            Texture2DDescription depthTexDesc = FillOutDepthTextureDescription();

            SharpDX.Direct3D11.Texture2D depthTexture = new SharpDX.Direct3D11.Texture2D(device, depthTexDesc);

            DepthStencilViewDescription dsvDesc = FillOutDSVDescription();

            depthMapDSV = new DepthStencilView(device, depthTexture, dsvDesc);

            ShaderResourceViewDescription srvDesc = FillOutSRVDescription();

            depthMapSRV = new ShaderResourceView(device, depthTexture, srvDesc);

            renderTarget = new RenderTarget("ShadowMap", null, depthMapDSV, viewport);

            depthTexture.Dispose();
        }
Example #9
0
        //  Draws the lensflare sprites, computing the position
        //  of each one based on the current angle of the sun.
        static void DrawFlares(float occlusionFactor, float visibilityRatio)
        {
            float screenScale = MyRender.ScreenSize.Y / 1000f;

            SharpDX.Viewport viewport = MyRender.GraphicsDevice.Viewport;

            // Lensflare sprites are positioned at intervals along a line that
            // runs from the 2D light position toward the center of the screen.
            Vector2 screenCenter = new Vector2(viewport.Width, viewport.Height) / 2;

            Vector2 flareVector = screenCenter - m_lightPosition;

            // Draw the flare sprites using additive blending.
            m_spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);

            foreach (MyFlare flare in m_flares)
            {
                // Compute the position of this flare sprite.
                Vector2 flarePosition = m_lightPosition + flareVector * flare.Position * screenScale;

                // Set the flare alpha based on the previous occlusion query result.
                Vector4 flareColor = flare.Color.ToVector4();

                flareColor.W *= occlusionFactor * visibilityRatio * visibilityRatio * (1 - MyRender.FogProperties.FogMultiplier * 0.7f);
                flareColor.W *= (1 - MyRender.FogProperties.FogMultiplier);

                // Center the sprite texture.
                Vector2 flareOrigin = new Vector2(flare.Texture.Width,
                                                  flare.Texture.Height) / 2;

                // Draw the flare.
                m_spriteBatch.Draw(flare.Texture, flarePosition, null,
                                   new Color(flareColor.X, flareColor.Y, flareColor.Z, flareColor.W),
                                   Vector2.UnitX,
                                   flareOrigin,
                                   flare.Scale * screenScale, SpriteEffects.None, 0);
            }

            m_spriteBatch.End();
        }
Example #10
0
        private bool DoBeginDraw()
        {
            if (this.HasDrawBegun)
                throw new InvalidOperationException("Already within BeginDraw / EndDraw pair.");

            this.EnsureDeviceCreated();

            SharpDX.Result result = this.InternalDevice.TestCooperativeLevel();

            if (!result.Success)
            {
                if (result.Code == D3D.ResultCode.DeviceLost.Result.Code && !this.IsDeviceLost)
                {
                    this.IsDeviceLost = true;
                }
                else if (result.Code == D3D.ResultCode.DriverInternalError.Result.Code)
                {
                    // TODO: Should this be handled?
                }
            }

            if (this.IsDeviceLost && !this.ResetDevice())
                return false;

            SharpDX.Viewport viewport = new SharpDX.Viewport(0, 0, this.BackBufferWidth, this.BackBufferHeight, 0, 1);

            if (this.RenderTarget != null)
            {
                this.backBuffer = this.InternalDevice.GetRenderTarget(0);
                this.InternalDevice.SetRenderTarget(0, this.RenderTarget.InternalTexture.GetSurfaceLevel(0));

                viewport.Width = this.RenderTarget.Width;
                viewport.Height = this.RenderTarget.Height;
            }

            this.InternalDevice.Viewport = viewport;

            this.InternalDevice.BeginScene();

            this.HasDrawBegun = true;

            return true;
        }
Example #11
0
        public void InitializeD3D11(IntPtr wndHandle, int width, int height)
        {
            CloseD3D11();

            _dxgiFactory = new Factory1();

            _dxiAdapter = _dxgiFactory.Adapters[0];

            _d3d11Device = new Device(_dxiAdapter, DeviceCreationFlags.BgraSupport, FeatureLevel.Level_11_0);

            _dxgiDevice = _d3d11Device.QueryInterface <DXGIDevice>();

            _dxgiDevice.MaximumFrameLatency = 1;

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("VSShader.fx", "main", "vs_4_0", ShaderFlags.None, EffectFlags.None);

            _vertexShader = new VertexShader(_d3d11Device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("PSShader.fx", "main", "ps_4_0", ShaderFlags.None, EffectFlags.None);

            _pixelShader = new PixelShader(_d3d11Device, pixelShaderByteCode);

            InputElement[] inputElements = new InputElement[3];

            inputElements[0] = new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0);
            inputElements[1] = new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0);
            inputElements[2] = new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0);

            _inputLayout = new InputLayout(_d3d11Device, vertexShaderByteCode, inputElements);

            BufferDescription vertexShaderDesc = new BufferDescription(Matrix.SizeInBytes * 2, BindFlags.ConstantBuffer, ResourceUsage.Default);

            _vertexShaderConstans = new Buffer(_d3d11Device, vertexShaderDesc);

            SamplerStateDescription samplerStateDescription = new SamplerStateDescription();

            samplerStateDescription.Filter             = Filter.MinMagMipLinear;
            samplerStateDescription.AddressU           = TextureAddressMode.Clamp;
            samplerStateDescription.AddressV           = TextureAddressMode.Clamp;
            samplerStateDescription.AddressW           = TextureAddressMode.Clamp;
            samplerStateDescription.MipLodBias         = 0.0f;
            samplerStateDescription.MaximumAnisotropy  = 1;
            samplerStateDescription.ComparisonFunction = Comparison.Always;
            samplerStateDescription.MinimumLod         = 0.0f;
            samplerStateDescription.MaximumLod         = float.MaxValue;

            _samplerState = new SamplerState(_d3d11Device, samplerStateDescription);

            RasterizerStateDescription rasterizerStateDescription = new RasterizerStateDescription();

            rasterizerStateDescription.IsAntialiasedLineEnabled = false;
            rasterizerStateDescription.CullMode                = CullMode.None;
            rasterizerStateDescription.DepthBias               = 0;
            rasterizerStateDescription.DepthBiasClamp          = 0.0f;
            rasterizerStateDescription.IsDepthClipEnabled      = true;
            rasterizerStateDescription.FillMode                = FillMode.Solid;
            rasterizerStateDescription.IsFrontCounterClockwise = false;
            rasterizerStateDescription.IsMultisampleEnabled    = false;
            rasterizerStateDescription.IsScissorEnabled        = false;
            rasterizerStateDescription.SlopeScaledDepthBias    = 0.0f;

            _rasterizerState = new RasterizerState(_d3d11Device, rasterizerStateDescription);

            _d3d11Device.ImmediateContext.InputAssembler.InputLayout = _inputLayout;
            _d3d11Device.ImmediateContext.VertexShader.SetShader(_vertexShader, null, 0);
            _d3d11Device.ImmediateContext.VertexShader.SetConstantBuffers(0, 1, _vertexShaderConstans);

            SwapChainDescription swapChainDescription = new SwapChainDescription();

            swapChainDescription.ModeDescription.Width  = width;
            swapChainDescription.ModeDescription.Height = height;
            swapChainDescription.ModeDescription.Format = Format.B8G8R8A8_UNorm;
            swapChainDescription.ModeDescription.RefreshRate.Numerator = 1;

            //pretty ugly
            //its better to autodetect screen refresh rate
            swapChainDescription.ModeDescription.RefreshRate.Denominator = 60;

            swapChainDescription.SampleDescription.Count   = 1;
            swapChainDescription.SampleDescription.Quality = 0;
            swapChainDescription.Usage                   = Usage.RenderTargetOutput;
            swapChainDescription.BufferCount             = 2;
            swapChainDescription.ModeDescription.Scaling = DisplayModeScaling.Unspecified;
            swapChainDescription.SwapEffect              = SwapEffect.FlipSequential;
            swapChainDescription.Flags                   = 0;
            swapChainDescription.IsWindowed              = true;
            swapChainDescription.OutputHandle            = wndHandle;

            _swapChain = new SwapChain(_dxgiFactory, _d3d11Device, swapChainDescription);

            _dxgiFactory.MakeWindowAssociation(wndHandle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = _swapChain.GetBackBuffer <Texture2D>(0);

            _mainRenderTargerView = new RenderTargetView(_d3d11Device, backBuffer);

            backBuffer.Dispose();
            backBuffer = null;

            Matrix projection = Matrix.Identity;

            Matrix view = new Matrix();

            /* Update the view matrix */
            view[0, 0] = 2.0f / (float)width;
            view[0, 1] = 0.0f;
            view[0, 2] = 0.0f;
            view[0, 3] = 0.0f;
            view[1, 0] = 0.0f;
            view[1, 1] = -2.0f / (float)height;
            view[1, 2] = 0.0f;
            view[1, 3] = 0.0f;
            view[2, 0] = 0.0f;
            view[2, 1] = 0.0f;
            view[2, 2] = 1.0f;
            view[2, 3] = 0.0f;
            view[3, 0] = -1.0f;
            view[3, 1] = 1.0f;
            view[3, 2] = 0.0f;
            view[3, 3] = 1.0f;

            VertexShaderConstants vertexShaderConstansData = new VertexShaderConstants();

            vertexShaderConstansData.projectionAndView = Matrix.Multiply(view, projection);
            vertexShaderConstansData.model             = Matrix.Identity;

            _vertexShaderConstansData = Marshal.AllocHGlobal(Marshal.SizeOf(vertexShaderConstansData));

            Marshal.StructureToPtr(vertexShaderConstansData, _vertexShaderConstansData, false);

            _d3d11Device.ImmediateContext.UpdateSubresource(ref vertexShaderConstansData, _vertexShaderConstans);


            ViewPort viewPort = new ViewPort();

            viewPort.X        = 0;
            viewPort.Y        = 0;
            viewPort.Width    = width;
            viewPort.Height   = height;
            viewPort.MinDepth = 0.0f;
            viewPort.MaxDepth = 1.0f;

            _d3d11Device.ImmediateContext.Rasterizer.SetViewport(viewPort);


            float minu, maxu, minv, maxv;

            minu = 0.0f;
            maxu = 1.0f;
            minv = 0.0f;
            maxv = 1.0f;


            // Instantiate Vertex buiffer from vertex data
            var vertices = Buffer.Create(_d3d11Device, BindFlags.VertexBuffer, new[]
            {
                //ul
                0.0f, 0.0f, 0.0f, minu, minv, 1.0f, 1.0f, 1.0f, 1.0f,
                //dl
                0.0f, (float)height, 0.0f, minu, maxv, 1.0f, 1.0f, 1.0f, 1.0f,
                //ur
                (float)width, 0.0f, 0.0f, maxu, minv, 1.0f, 1.0f, 1.0f, 1.0f,
                //dr
                (float)width, (float)height, 0.0f, maxu, maxv, 1.0f, 1.0f, 1.0f, 1.0f
            });

            _d3d11Device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 36, 0));
            _d3d11Device.ImmediateContext.Rasterizer.State = _rasterizerState;
            _d3d11Device.ImmediateContext.PixelShader.SetShader(_pixelShader, null, 0);
            _d3d11Device.ImmediateContext.PixelShader.SetSamplers(0, 1, _samplerState);
            _d3d11Device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
        }