Esempio n. 1
0
            public void PresentSurface(IDirect3DSurface surface)
            {
                using (var sourceTexture = Direct3D11Helpers.CreateSharpDXTexture2D(surface))
                {
                    if (!_isSwapChainSized)
                    {
                        var description = sourceTexture.Description;

                        _swapChain.ResizeBuffers(
                            2,
                            description.Width,
                            description.Height,
                            SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                            SharpDX.DXGI.SwapChainFlags.None);

                        _isSwapChainSized = true;
                    }

                    using (var backBuffer = _swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                        using (var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, backBuffer))
                        {
                            _d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
                            _d3dDevice.ImmediateContext.CopyResource(sourceTexture, backBuffer);
                        }
                }

                _swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            }
Esempio n. 2
0
        private void InitializeBlankTexture(SizeInt32 size)
        {
            var description = new SharpDX.Direct3D11.Texture2DDescription
            {
                Width             = size.Width,
                Height            = size.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage          = SharpDX.Direct3D11.ResourceUsage.Default,
                BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None
            };

            _blankTexture = new SharpDX.Direct3D11.Texture2D(_d3dDevice, description);

            using (var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, _blankTexture))
            {
                _d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
            }
        }
Esempio n. 3
0
            public EncoderPreview(SharpDX.Direct3D11.Device device)
            {
                _d3dDevice = device;

                var dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device>();
                var adapter    = dxgiDevice.GetParent <SharpDX.DXGI.Adapter>();
                var factory    = adapter.GetParent <SharpDX.DXGI.Factory2>();

                var description = new SharpDX.DXGI.SwapChainDescription1
                {
                    Width             = 1,
                    Height            = 1,
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                    SampleDescription = new SharpDX.DXGI.SampleDescription()
                    {
                        Count   = 1,
                        Quality = 0
                    },
                    BufferCount = 2,
                    Scaling     = SharpDX.DXGI.Scaling.Stretch,
                    SwapEffect  = SharpDX.DXGI.SwapEffect.FlipSequential,
                    AlphaMode   = SharpDX.DXGI.AlphaMode.Premultiplied
                };
                var swapChain = new SharpDX.DXGI.SwapChain1(factory, dxgiDevice, ref description);

                using (var backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                    using (var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, backBuffer))
                    {
                        _d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 0));
                    }

                _swapChain = swapChain;
            }
        public override void Dispose()
        {
#if DIRECTX
            if (_renderTargetView != null)
            {
                _renderTargetView.Dispose();
                _renderTargetView = null;
            }
            if (_depthStencilView != null)
            {
                _depthStencilView.Dispose();
                _depthStencilView = null;
            }
#elif OPENGL
            GL.DeleteRenderbuffers(1, ref this.glDepthStencilBuffer);
            GraphicsExtensions.CheckGLError();

            if (this.glFramebuffer > 0)
            {
                GL.DeleteFramebuffers(1, ref this.glFramebuffer);
                GraphicsExtensions.CheckGLError();
            }
#endif
            base.Dispose();
        }
Esempio n. 5
0
        protected override void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
#if DIRECTX
                if (disposing)
                {
                    if (_renderTargetView != null)
                    {
                        _renderTargetView.Dispose();
                        _renderTargetView = null;
                    }
                    if (_depthStencilView != null)
                    {
                        _depthStencilView.Dispose();
                        _depthStencilView = null;
                    }
                }
#elif OPENGL
                GraphicsDevice.AddDisposeAction(() =>
                {
                    GL.DeleteRenderbuffers(1, ref this.glDepthStencilBuffer);
                    GraphicsExtensions.CheckGLError();

                    if (this.glFramebuffer > 0)
                    {
                        GL.DeleteFramebuffers(1, ref this.glFramebuffer);
                        GraphicsExtensions.CheckGLError();
                    }
                });
#endif
            }
            base.Dispose(disposing);
        }
Esempio n. 6
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);
        }
Esempio n. 7
0
 void OnWindowSizeChanged(
     CoreWindow sender,
     WindowSizeChangedEventArgs args
     )
 {
     m_renderTargetView = null;
     CreateWindowSizeDependentResources();
 }
        private void InitializeDirectXResources()
        {
            var clientSize     = ClientSize;
            var backBufferDesc = new SharpDX.DXGI.ModeDescription(clientSize.Width, clientSize.Height,
                                                                  new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm);

            var swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = Handle,
                SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                IsWindowed        = false
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport,
                                                          new[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, swapChainDesc,
                                                          out _d3DDevice, out var swapChain);
            _d3DDeviceContext = _d3DDevice.ImmediateContext;

            _swapChain = new SharpDX.DXGI.SwapChain1(swapChain.NativePointer);

            _d2DFactory = new SharpDX.Direct2D1.Factory();

            using (var backBuffer = _swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
            {
                _renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3DDevice, backBuffer);
                _renderTarget     = new SharpDX.Direct2D1.RenderTarget(_d2DFactory, backBuffer.QueryInterface <SharpDX.DXGI.Surface>(),
                                                                       new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)))
                {
                    TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype
                };
            }

            _solidColorBrush = new SharpDX.Direct2D1.SolidColorBrush(_renderTarget, Color.White);

            _dwFactory  = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);
            _textFormat = new SharpDX.DirectWrite.TextFormat(_dwFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold,
                                                             SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 84 * (float)GraphicsUtils.Scale)
            {
                TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center,
                ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center
            };
            //                var rectangleGeometry = new D2D1.RoundedRectangleGeometry(_d2DFactory,
            //                    new D2D1.RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, Width - 128 * 2, Height - 128 * 2) });
        }
Esempio n. 9
0
        private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
        {
            var newSize = false;

            using (var frame = sender.TryGetNextFrame())
            {
                if (frame.ContentSize.Width != _lastSize.Width ||
                    frame.ContentSize.Height != _lastSize.Height)
                {
                    // The thing we have been capturing has changed size.
                    // We need to resize our swap chain first, then blit the pixels.
                    // After we do that, retire the frame and then recreate our frame pool.
                    newSize   = true;
                    _lastSize = frame.ContentSize;
                    _swapChain.ResizeBuffers(
                        2,
                        _lastSize.Width,
                        _lastSize.Height,
                        SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        SharpDX.DXGI.SwapChainFlags.None);
                }

                using (var sourceTexture = Direct3D11Helpers.CreateSharpDXTexture2D(frame.Surface))
                    using (var backBuffer = _swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                        using (var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, backBuffer))
                        {
                            _d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
                            _d3dDevice.ImmediateContext.CopyResource(sourceTexture, backBuffer);
                        }
            } // retire the frame

            _swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);

            if (newSize)
            {
                _framePool.Recreate(
                    _device,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    2,
                    _lastSize);
            }
        }
        private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
        {
            var newSize = false;

            using (var frame = sender.TryGetNextFrame())
            {
                if (frame.ContentSize.Width != _lastSize.Width ||
                    frame.ContentSize.Height != _lastSize.Height)
                {
                    // 源已改变,故需要变换抓取大小,首先改变swap chain,之后是Texture
                    newSize   = true;
                    _lastSize = frame.ContentSize;
                    _swapChain.ResizeBuffers(
                        2,
                        _lastSize.Width,
                        _lastSize.Height,
                        SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        SharpDX.DXGI.SwapChainFlags.None);
                }

                using (var sourceTexture = Direct3D11Helpers.CreateSharpDXTexture2D(frame.Surface))
                    using (var backBuffer = _swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                        using (var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, backBuffer))
                        {
                            _d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
                            _d3dDevice.ImmediateContext.CopyResource(sourceTexture, backBuffer);
                        }
            }

            _swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);

            if (newSize)//帧池重构
            {
                _framePool.Recreate(
                    _device,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    2,
                    _lastSize);
            }
        }
Esempio n. 11
0
        public BackBuffer(Dx10Device device10, Dx11ChainedDevice device11)
        {
            try
            {
                _device10 = device10;
                _device11 = device11;

                _backBuffer = Resource.FromSwapChain <Texture2D>(device11.SwapChain, 0);
                _renderView = new RenderTargetView(device11.Device, _backBuffer);

                Texture2DDescription descriptor = _backBuffer.Description;
                {
                    descriptor.MipLevels         = 1;
                    descriptor.ArraySize         = 1;
                    descriptor.Format            = Format.B8G8R8A8_UNorm;
                    descriptor.SampleDescription = new SampleDescription(1, 0);
                    descriptor.Usage             = SharpDX.Direct3D11.ResourceUsage.Default;
                    descriptor.BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource;
                    descriptor.CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None;
                    descriptor.OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.SharedKeyedmutex;
                };

                _textureD3D11 = new Texture2D(device11.Device, descriptor);

                _factory2D = new Factory(FactoryType.MultiThreaded);

                using (SharpDX.DXGI.Resource sharedResource = _textureD3D11.QueryInterface <SharpDX.DXGI.Resource>())
                    using (SharpDX.Direct3D10.Texture2D backBuffer10 = device10.Device.OpenSharedResource <SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle))
                    {
                        _surface        = backBuffer10.QueryInterface <Surface>();
                        _renderTarget2D = new RenderTarget(_factory2D, _surface, GetRenderTargetProperties());
                    }
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Esempio n. 12
0
 public RenderBuffer( IGraphicsDevice graphicsDevice, int width, int height )
     : base(graphicsDevice, width, height, 1, true)
 {
     targetView = new SharpDX.Direct3D11.RenderTargetView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         Handle as SharpDX.Direct3D11.Texture2D, new SharpDX.Direct3D11.RenderTargetViewDescription ()
         {
             Dimension = SharpDX.Direct3D11.RenderTargetViewDimension.Texture2D,
             Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
             Texture2D = new SharpDX.Direct3D11.RenderTargetViewDescription.Texture2DResource () { MipSlice = 0 }
         }
     );
     depthStencilBuffer = new SharpDX.Direct3D11.Texture2D ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         new SharpDX.Direct3D11.Texture2DDescription ()
         {
             ArraySize = 1,
             Width = width,
             Height = height,
             Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
             MipLevels = 0,
             BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
         }
     );
     depthStencil = new SharpDX.Direct3D11.DepthStencilView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         depthStencilBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription ()
         {
             Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D,
             Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
             Texture2D = new SharpDX.Direct3D11.DepthStencilViewDescription.Texture2DResource () { MipSlice = 0 }
         }
     );
     shaderView = new SharpDX.Direct3D11.ShaderResourceView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         Handle as SharpDX.Direct3D11.Texture2D, new SharpDX.Direct3D11.ShaderResourceViewDescription ()
         {
             Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
             Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
             Texture2D = new SharpDX.Direct3D11.ShaderResourceViewDescription.Texture2DResource () { MipLevels = 1, MostDetailedMip = 0 }
         }
     );
 }
Esempio n. 13
0
        private void InitializeComposeTexture(SizeInt32 size)
        {
            var description = new SharpDX.Direct3D11.Texture2DDescription
            {
                Width             = size.Width,
                Height            = size.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage          = SharpDX.Direct3D11.ResourceUsage.Default,
                BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None
            };

            _composeTexture          = new SharpDX.Direct3D11.Texture2D(_d3dDevice, description);
            _composeRenderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, _composeTexture);
        }
Esempio n. 14
0
		protected override void Dispose(bool disposing)
		{
            if (!IsDisposed)
            {
#if DIRECTX
                if (disposing)
                {
                    if (_renderTargetView != null)
                    {
                        _renderTargetView.Dispose();
                        _renderTargetView = null;
                    }
                    if (_depthStencilView != null)
                    {
                        _depthStencilView.Dispose();
                        _depthStencilView = null;
                    }
                }
#elif OPENGL
                GraphicsDevice.AddDisposeAction(() =>
                    {
                        GL.DeleteRenderbuffers(1, ref this.glDepthStencilBuffer);
                        GraphicsExtensions.CheckGLError();

                        if (this.glFramebuffer > 0)
                        {
                            GL.DeleteFramebuffers(1, ref this.glFramebuffer);
                            GraphicsExtensions.CheckGLError();
                        }
                    });
#endif
            }
            base.Dispose(disposing);
		}
Esempio n. 15
0
		public RenderTarget2D (GraphicsDevice graphicsDevice, int width, int height, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage)
			:base (graphicsDevice, width, height, mipMap, preferredFormat, true)
		{
			DepthStencilFormat = preferredDepthFormat;
			MultiSampleCount = preferredMultiSampleCount;
			RenderTargetUsage = usage;

#if DIRECTX
            // Create a view interface on the rendertarget to use on bind.
            _renderTargetView = new SharpDX.Direct3D11.RenderTargetView(graphicsDevice._d3dDevice, _texture);
#endif

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
                return;

#if DIRECTX

            // Setup the multisampling description.
            var multisampleDesc = new SharpDX.DXGI.SampleDescription(1, 0);
            if ( preferredMultiSampleCount > 1 )
            {
                multisampleDesc.Count = preferredMultiSampleCount;
                multisampleDesc.Quality = (int)SharpDX.Direct3D11.StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                ArraySize = 1,
                MipLevels = 1,
                Width = width,
                Height = height,
                SampleDescription = multisampleDesc,
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))

            // Create the view for binding to the device.
            _depthStencilView = new SharpDX.Direct3D11.DepthStencilView(graphicsDevice._d3dDevice, depthBuffer,
                new SharpDX.Direct3D11.DepthStencilViewDescription() 
                { 
                    Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                    Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D 
                });

#elif OPENGL

#if GLES
			GL.GenRenderbuffers(1, ref glDepthStencilBuffer);
#else
			GL.GenRenderbuffers(1, out glDepthStencilBuffer);
#endif
            GraphicsExtensions.CheckGLError();
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, this.glDepthStencilBuffer);
            GraphicsExtensions.CheckGLError();
            var glDepthStencilFormat = GLDepthComponent16;
			switch (preferredDepthFormat)
			{
			case DepthFormat.Depth16: glDepthStencilFormat = GLDepthComponent16; break;
			case DepthFormat.Depth24: glDepthStencilFormat = GLDepthComponent24; break;
			case DepthFormat.Depth24Stencil8: glDepthStencilFormat = GLDepth24Stencil8; break;
			}
			GL.RenderbufferStorage(GLRenderbuffer, glDepthStencilFormat, this.width, this.height);
            GraphicsExtensions.CheckGLError();
#endif
        }
Esempio n. 16
0
        public RenderTarget2D(GraphicsDevice graphicsDevice, int width, int height, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage)
            : base(graphicsDevice, width, height, mipMap, preferredFormat, true)
        {
            DepthStencilFormat = preferredDepthFormat;
            MultiSampleCount   = preferredMultiSampleCount;
            RenderTargetUsage  = usage;

#if DIRECTX
            // Create a view interface on the rendertarget to use on bind.
            _renderTargetView = new SharpDX.Direct3D11.RenderTargetView(graphicsDevice._d3dDevice, _texture);
#endif

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
            {
                return;
            }

#if DIRECTX
            // Setup the multisampling description.
            var multisampleDesc = new SharpDX.DXGI.SampleDescription(1, 0);
            if (preferredMultiSampleCount > 1)
            {
                multisampleDesc.Count   = preferredMultiSampleCount;
                multisampleDesc.Quality = (int)SharpDX.Direct3D11.StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                ArraySize = 1,
                MipLevels = 1,
                Width = width,
                Height = height,
                SampleDescription = multisampleDesc,
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))

                // Create the view for binding to the device.
                _depthStencilView = new SharpDX.Direct3D11.DepthStencilView(graphicsDevice._d3dDevice, depthBuffer,
                                                                            new SharpDX.Direct3D11.DepthStencilViewDescription()
                {
                    Format    = SharpDXHelper.ToFormat(preferredDepthFormat),
                    Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D
                });
#elif OPENGL
#if GLES
            GL.GenRenderbuffers(1, ref glDepthStencilBuffer);
#else
            GL.GenRenderbuffers(1, out glDepthStencilBuffer);
#endif
            GraphicsExtensions.CheckGLError();
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, this.glDepthStencilBuffer);
            GraphicsExtensions.CheckGLError();
            var glDepthStencilFormat = GLDepthComponent16;
            switch (preferredDepthFormat)
            {
            case DepthFormat.Depth16: glDepthStencilFormat = GLDepthComponent16; break;

            case DepthFormat.Depth24: glDepthStencilFormat = GLDepthComponent24; break;

            case DepthFormat.Depth24Stencil8: glDepthStencilFormat = GLDepth24Stencil8; break;
            }
            GL.RenderbufferStorage(GLRenderbuffer, glDepthStencilFormat, this.width, this.height);
            GraphicsExtensions.CheckGLError();
#endif
        }
Esempio n. 17
0
        private void _Direct3Dを初期化する()
        {
            // D3D11デバイスと SwapChain を生成します。

            SharpDX.Direct3D11.Device.CreateWithSwapChain(
                SharpDX.Direct3D.DriverType.Hardware,
                SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport,
                new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_11_1 },   // 機能レベル 11.1
                new SharpDX.DXGI.SwapChainDescription {
                BufferCount     = 1,
                Flags           = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch,
                IsWindowed      = true,
                ModeDescription = new SharpDX.DXGI.ModeDescription {
                    Format  = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Width   = this.ClientSize.Width,
                    Height  = this.ClientSize.Height,
                    Scaling = SharpDX.DXGI.DisplayModeScaling.Stretched,
                },
                OutputHandle      = this.Handle,
                SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),       // MSAA x4
                SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
            },
                out this._D3D11Device,
                out this._DXGISwapChain);


            // 既定のRenderTarget と 既定のDepthStencil ならびにそのビューを作成します。

            this._既定のD3D11RenderTarget = this._DXGISwapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0);

            this._既定のD3D11DepthStencil = new SharpDX.Direct3D11.Texture2D(
                this._D3D11Device,
                new SharpDX.Direct3D11.Texture2DDescription {
                Width             = this._既定のD3D11RenderTarget.Description.Width,
                Height            = this._既定のD3D11RenderTarget.Description.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                SampleDescription = this._既定のD3D11RenderTarget.Description.SampleDescription,
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default,
                BindFlags         = SharpDX.Direct3D11.BindFlags.DepthStencil,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
            });

            this._既定のD3D11RenderTargetView = new SharpDX.Direct3D11.RenderTargetView(this._D3D11Device, this._既定のD3D11RenderTarget);

            this._既定のD3D11DepthStencilView = new SharpDX.Direct3D11.DepthStencilView(this._D3D11Device, this._既定のD3D11DepthStencil);



            // 加算合成用のブレンドステートを作成します。

            var BlendStateAdd = new SharpDX.Direct3D11.BlendStateDescription()
            {
                AlphaToCoverageEnable  = false, // アルファマスクで透過する(するならZバッファ必須)
                IndependentBlendEnable = false, // 個別設定。false なら BendStateDescription.RenderTarget[0] だけが有効で、[1~7] は無視される。
            };

            BlendStateAdd.RenderTarget[0].IsBlendEnabled        = true;                                       // true ならブレンディングが有効。
            BlendStateAdd.RenderTarget[0].RenderTargetWriteMask = SharpDX.Direct3D11.ColorWriteMaskFlags.All; // RGBA の書き込みマスク。
            // アルファ値のブレンディング設定 ... 特になし
            BlendStateAdd.RenderTarget[0].SourceAlphaBlend      = SharpDX.Direct3D11.BlendOption.One;
            BlendStateAdd.RenderTarget[0].DestinationAlphaBlend = SharpDX.Direct3D11.BlendOption.Zero;
            BlendStateAdd.RenderTarget[0].AlphaBlendOperation   = SharpDX.Direct3D11.BlendOperation.Add;
            // 色値のブレンディング設定 ... 加算合成
            BlendStateAdd.RenderTarget[0].SourceBlend      = SharpDX.Direct3D11.BlendOption.SourceAlpha;
            BlendStateAdd.RenderTarget[0].DestinationBlend = SharpDX.Direct3D11.BlendOption.One;
            BlendStateAdd.RenderTarget[0].BlendOperation   = SharpDX.Direct3D11.BlendOperation.Add;
            // ブレンドステートを作成する。
            this._BlendState加算合成 = new SharpDX.Direct3D11.BlendState(this._D3D11Device, BlendStateAdd);


            // ブレンドステートと深度ステンシルステートを OM に設定します。

            this._D3D11Device.ImmediateContext.OutputMerger.BlendState        = this._BlendState加算合成;
            this._D3D11Device.ImmediateContext.OutputMerger.DepthStencilState = null;


            // ラスタライザステートを作成します。

            this._RasterizerState = new SharpDX.Direct3D11.RasterizerState(
                this._D3D11Device,
                new SharpDX.Direct3D11.RasterizerStateDescription {
                CullMode = SharpDX.Direct3D11.CullMode.Back,
                FillMode = SharpDX.Direct3D11.FillMode.Solid,
            });
        }
Esempio n. 18
0
        private async void MainToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            // Select what we want to capture
            var picker = new GraphicsCapturePicker();
            var item   = await picker.PickSingleItemAsync();

            if (item != null)
            {
                // Get a temporary file to save our gif to
                var file = await GetTempFileAsync();

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // Get the various d3d objects we'll need
                    var d3dDevice = Direct3D11Helpers.CreateSharpDXDevice(_device);

                    // Create our encoder
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, stream);

                    // Write the application block
                    // http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension
                    var containerProperties = encoder.BitmapContainerProperties;
                    await containerProperties.SetPropertiesAsync(new[]
                    {
                        new KeyValuePair <string, BitmapTypedValue>("/appext/application", new BitmapTypedValue(PropertyValue.CreateUInt8Array(Encoding.ASCII.GetBytes("NETSCAPE2.0")), PropertyType.UInt8Array)),
                        // The first value is the size of the block, which is the fixed value 3.
                        // The second value is the looping extension, which is the fixed value 1.
                        // The third and fourth values comprise an unsigned 2-byte integer (little endian).
                        //     The value of 0 means to loop infinitely.
                        // The final value is the block terminator, which is the fixed value 0.
                        new KeyValuePair <string, BitmapTypedValue>("/appext/data", new BitmapTypedValue(PropertyValue.CreateUInt8Array(new byte[] { 3, 1, 0, 0, 0 }), PropertyType.UInt8Array)),
                    });

                    // Setup Windows.Graphics.Capture
                    var itemSize  = item.Size;
                    var framePool = Direct3D11CaptureFramePool.CreateFreeThreaded(
                        _device,
                        DirectXPixelFormat.B8G8R8A8UIntNormalized,
                        1,
                        itemSize);
                    var session = framePool.CreateCaptureSession(item);

                    // We need a blank texture (background) and a texture that will hold the frame we'll be encoding
                    var description = new SharpDX.Direct3D11.Texture2DDescription
                    {
                        Width             = itemSize.Width,
                        Height            = itemSize.Height,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        SampleDescription = new SharpDX.DXGI.SampleDescription()
                        {
                            Count   = 1,
                            Quality = 0
                        },
                        Usage          = SharpDX.Direct3D11.ResourceUsage.Default,
                        BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                        CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                        OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None
                    };
                    var gifTexture       = new SharpDX.Direct3D11.Texture2D(d3dDevice, description);
                    var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, gifTexture);

                    // Encode frames as they arrive. Because we created our frame pool using
                    // Direct3D11CaptureFramePool::CreateFreeThreaded, this lambda will fire on a different thread
                    // than our current one. If you'd like the callback to fire on your thread, create the frame pool
                    // using Direct3D11CaptureFramePool::Create and make sure your thread has a DispatcherQueue and you
                    // are pumping messages.
                    TimeSpan lastTimeStamp = TimeSpan.MinValue;
                    var      frameCount    = 0;
                    framePool.FrameArrived += async(s, a) =>
                    {
                        using (var frame = s.TryGetNextFrame())
                        {
                            var contentSize = frame.ContentSize;
                            var timeStamp   = frame.SystemRelativeTime;
                            using (var sourceTexture = Direct3D11Helpers.CreateSharpDXTexture2D(frame.Surface))
                            {
                                var width  = Math.Clamp(contentSize.Width, 0, itemSize.Width);
                                var height = Math.Clamp(contentSize.Height, 0, itemSize.Height);

                                var region = new SharpDX.Direct3D11.ResourceRegion(0, 0, 0, width, height, 1);

                                d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
                                d3dDevice.ImmediateContext.CopySubresourceRegion(sourceTexture, 0, region, gifTexture, 0);
                            }

                            if (lastTimeStamp == TimeSpan.MinValue)
                            {
                                lastTimeStamp = timeStamp;
                            }
                            var timeStampDelta = timeStamp - lastTimeStamp;
                            lastTimeStamp = timeStamp;
                            var milliseconds = timeStampDelta.TotalMilliseconds;
                            // Use 10ms units
                            var frameDelay = milliseconds / 10;

                            if (frameCount > 0)
                            {
                                await encoder.GoToNextFrameAsync();
                            }

                            // Write our frame delay
                            await encoder.BitmapProperties.SetPropertiesAsync(new[]
                            {
                                new KeyValuePair <string, BitmapTypedValue>("/grctlext/Delay", new BitmapTypedValue(PropertyValue.CreateUInt16((ushort)frameDelay), PropertyType.UInt16)),
                            });

                            // Write the frame to our image
                            var gifSurface = Direct3D11Helpers.CreateDirect3DSurfaceFromSharpDXTexture(gifTexture);
                            var copy       = await SoftwareBitmap.CreateCopyFromSurfaceAsync(gifSurface);

                            encoder.SetSoftwareBitmap(copy);
                            frameCount++;
                        }
                    };

                    session.StartCapture();

                    await _semaphore.WaitAsync();

                    session.Dispose();
                    framePool.Dispose();
                    await Task.Delay(1000);

                    await encoder.FlushAsync();

                    var newFile = await PickGifAsync();

                    if (newFile == null)
                    {
                        await file.DeleteAsync();

                        return;
                    }
                    await file.MoveAndReplaceAsync(newFile);

                    await Launcher.LaunchFileAsync(newFile);
                }
            }
        }
Esempio n. 19
0
            // This method creates all application resources that depend on
            // the application window size.  It is called at app initialization,
            // and whenever the application window size changes.
            void CreateWindowSizeDependentResources()
            {
                if (m_swapChain != null)
                {
                    // If the swap chain already exists, resize it.
                    m_swapChain.ResizeBuffers(
                        2,
                        0,
                        0,
                        SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        0
                        );
                }
                else
                {
                    // If the swap chain does not exist, create it.
                    var swapChainDesc = new SharpDX.DXGI.SwapChainDescription1
                    {
                        Stereo  = false,
                        Usage   = SharpDX.DXGI.Usage.RenderTargetOutput,
                        Scaling = SharpDX.DXGI.Scaling.None,
                        Flags   = 0,
                    };

                    // Use automatic sizing.
                    swapChainDesc.Width  = 0;
                    swapChainDesc.Height = 0;

                    // This is the most common swap chain format.
                    swapChainDesc.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;

                    // Don't use multi-sampling.
                    swapChainDesc.SampleDescription.Count   = 1;
                    swapChainDesc.SampleDescription.Quality = 0;

                    // Use two buffers to enable flip effect.
                    swapChainDesc.BufferCount = 2;

                    // We recommend using this swap effect for all applications.
                    swapChainDesc.SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential;

                    // Once the swap chain description is configured, it must be
                    // created on the same adapter as the existing D3D Device.

                    // First, retrieve the underlying DXGI Device from the D3D Device.
                    using (var dxgiDevice = m_d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    {
                        // Ensure that DXGI does not queue more than one frame at a time. This both reduces
                        // latency and ensures that the application will only render after each VSync, minimizing
                        // power consumption.
                        dxgiDevice.MaximumFrameLatency = 1;

                        // Next, get the parent factory from the DXGI Device.
                        using (var dxgiAdapter = dxgiDevice.Adapter)
                            using (var dxgiFactory = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                                // Finally, create the swap chain.
                                using (var coreWindow = new SharpDX.ComObject(m_window))
                                {
                                    m_swapChain = new SharpDX.DXGI.SwapChain1(dxgiFactory
                                                                              , m_d3dDevice, coreWindow, ref swapChainDesc);
                                }
                    }
                }

                // Once the swap chain is created, create a render target view.  This will
                // allow Direct3D to render graphics to the window.
                using (var backBuffer = m_swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                {
                    m_renderTargetView = new SharpDX.Direct3D11.RenderTargetView(m_d3dDevice, backBuffer);

                    // After the render target view is created, specify that the viewport,
                    // which describes what portion of the window to draw to, should cover
                    // the entire window.

                    var backBufferDesc = backBuffer.Description;

                    var viewport = new SharpDX.ViewportF
                    {
                        X        = 0.0f,
                        Y        = 0.0f,
                        Width    = backBufferDesc.Width,
                        Height   = backBufferDesc.Height,
                        MinDepth = 0,
                        MaxDepth = 1,
                    };

                    m_d3dDeviceContext.Rasterizer.SetViewport(viewport);
                }
            }
        protected virtual void CreateSizeDependentResources(TargetBase renderBase)
        {
            var d3dDevice  = DeviceManager.DeviceDirect3D;
            var d3dContext = DeviceManager.ContextDirect3D;
            var d2dContext = DeviceManager.ContextDirect2D;

            d2dContext.Target = null;
            Utilities.Dispose(ref renderTargetView);
            Utilities.Dispose(ref depthStencilView);
            Utilities.Dispose(ref bitmapTarget);
            Utilities.Dispose(ref backBuffer);

            // If the swap chain already exists, resize it.
            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, Width, Height, SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.DXGI.SwapChainFlags.None);
            }
            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // Creates the swap chain
                using (var dxgiDevice2 = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                        {
                            swapChain = CreateSwapChain(dxgiFactory2, d3dDevice, desc);

                            // Ensure that DXGI does not queue more than one frame at a time. This both reduces
                            // latency and ensures that the application will only render after each VSync, minimizing
                            // power consumption.
                            dxgiDevice2.MaximumFrameLatency = 1;
                        }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            backBuffer = SharpDX.Direct3D11.Texture2D.FromSwapChain <SharpDX.Direct3D11.Texture2D>(swapChain, 0);
            {
                // Create a view interface on the rendertarget to use on bind.
                renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, BackBuffer);

                // Cache the rendertarget dimensions in our helper class for convenient use.
                var backBufferDesc = BackBuffer.Description;
                RenderTargetBounds = new Windows.Foundation.Rect(0, 0, backBufferDesc.Width, backBufferDesc.Height);
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)RenderTargetSize.Width,
                Height = (int)RenderTargetSize.Height,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))
                depthStencilView = new SharpDX.Direct3D11.DepthStencilView(d3dDevice, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription()
                {
                    Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D
                });

            // Create a viewport descriptor of the full window size.
            var viewport = new SharpDX.Mathematics.ViewportF((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            // Set the current viewport using the descriptor.
            d3dContext.Rasterizer.SetViewport(viewport);

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DeviceManager.Dpi,
                DeviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            using (var dxgiBackBuffer = swapChain.GetBackBuffer <SharpDX.DXGI.Surface>(0))
                bitmapTarget = new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties);

            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget2D;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
        protected virtual void CreateSizeDependentResources(TargetBase renderBase)
        {
            var d3dDevice = DeviceManager.DeviceDirect3D;
            var d3dContext = DeviceManager.ContextDirect3D;
            var d2dContext = DeviceManager.ContextDirect2D;

            d2dContext.Target = null;
            Utilities.Dispose(ref renderTargetView);
            Utilities.Dispose(ref depthStencilView);
            Utilities.Dispose(ref bitmapTarget);
            Utilities.Dispose(ref backBuffer);

            // If the swap chain already exists, resize it.
            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, Width, Height, SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.DXGI.SwapChainFlags.None);
            }
            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // Creates the swap chain 
                using (var dxgiDevice2 = d3dDevice.QueryInterface<SharpDX.DXGI.Device2>())
                using (var dxgiAdapter = dxgiDevice2.Adapter)
                using (var dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
                {
                    swapChain = CreateSwapChain(dxgiFactory2, d3dDevice, desc);

                    // Ensure that DXGI does not queue more than one frame at a time. This both reduces 
                    // latency and ensures that the application will only render after each VSync, minimizing 
                    // power consumption.
                    dxgiDevice2.MaximumFrameLatency = 1;
                }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            backBuffer = SharpDX.Direct3D11.Texture2D.FromSwapChain<SharpDX.Direct3D11.Texture2D>(swapChain, 0);
            {
                // Create a view interface on the rendertarget to use on bind.
                renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, BackBuffer);

                // Cache the rendertarget dimensions in our helper class for convenient use.
                var backBufferDesc = BackBuffer.Description;
                RenderTargetBounds = new Windows.Foundation.Rect(0, 0, backBufferDesc.Width, backBufferDesc.Height);
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)RenderTargetSize.Width,
                Height = (int)RenderTargetSize.Height,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))
                depthStencilView = new SharpDX.Direct3D11.DepthStencilView(d3dDevice, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D });

            // Create a viewport descriptor of the full window size.
            var viewport = new SharpDX.Mathematics.ViewportF((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            // Set the current viewport using the descriptor.
            d3dContext.Rasterizer.SetViewport(viewport);

            // Now we set up the Direct2D render target bitmap linked to the swapchain. 
            // Whenever we render to this bitmap, it will be directly rendered to the 
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DeviceManager.Dpi,
                DeviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            using (var dxgiBackBuffer = swapChain.GetBackBuffer<SharpDX.DXGI.Surface>(0))
                bitmapTarget = new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties);

            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget2D;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;            
        }
Esempio n. 22
0
        public void Render(RenderFrame frame)
        {
            if (SwapChain == null) return;

            /////////////////////////////////////////////////
            // update
            /////////////////////////////////////////////////
            foreach (var resource in frame.Resources)
            {
                switch (resource.RenderResourceType)
                {
                    case RenderResourceType.Texture:
                        //TextureManager.Ensure(device, resource as TextureResource);
                        break;

                    case RenderResourceType.Sampler:
                        //SamplerManager.Ensure(device, resource as SamplerResource);
                        break;

                    case RenderResourceType.Shader:
                        m_shaderManager.Ensure(D3DDevice, resource as ShaderResource);
                        break;

                    case RenderResourceType.VertexBuffer:
                        m_vertexBufferManager.Ensure(D3DDevice, resource as VertexBufferResource);
                        break;

                    case RenderResourceType.BlendState:
                        //BlendStateManager.Ensure(device, resource as BlendStateResource);
                        break;

                    case RenderResourceType.DepthStencilState:
                        //DepthStencilStateManager.Ensure(device, resource as DepthStencilStateResource);
                        break;

                    default:
                        throw new NotImplementedException(resource.ToString());
                }
            }

            /////////////////////////////////////////////////
            // render
            /////////////////////////////////////////////////
            m_pass = new ShaderPass();
            using (Backbuffer = SwapChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0))
            using (RTV = new SharpDX.Direct3D11.RenderTargetView(D3DDevice, Backbuffer))
            {
                var context = D3DDevice.ImmediateContext;
                foreach (var c in frame.Commands)
                {
                    switch (c.RenderCommandType)
                    {
                        /*
                        case RenderCommandType.RenderTargets_Set:
                            {
                                var command = c as RenderTargetsSetCommand;
                                var depthStencil = m_resources.TextureManager.Get(command.DepthStencil);
                                var renderTargets = m_resources.TextureManager.Get(command.RenderTargets);
                                context.OutputMerger.SetTargets(
                                    depthStencil != null ? depthStencil.DepthStencilView : null
                                    , renderTargets.Select(r => r.RenderTargetView).ToArray());

                            }
                            break;

                        case RenderCommandType.Viewport_Set:
                            {
                                var command = c as ViewportSetCommand;
                                context.Rasterizer.SetViewports(new SharpDX.ViewportF[] { command.Viewport });
                            }
                            break;
                            */

                        case RenderCommandType.Clear_Backbuffer:
                            {
                                var command = c as BackbufferClearCommand;
                                context.ClearRenderTargetView(RTV, command.Color.ToSharpDX());
                                context.OutputMerger.SetTargets((SharpDX.Direct3D11.DepthStencilView)null, new SharpDX.Direct3D11.RenderTargetView[] { RTV });
                                context.Rasterizer.SetViewports(new [] {
                                    new SharpDX.Mathematics.Interop.RawViewportF
                                    {
                                        X=0,
                                        Y=0,
                                        Width=Backbuffer.Description.Width,
                                        Height=Backbuffer.Description.Height,
                                    }
                                });
                            }
                            break;

                        /*
                    case RenderCommandType.Clear_Color:
                        {
                            var command = c as RenderTargetClearCommand;
                            var renderTarget = m_resources.TextureManager.Get(command.ResourceID);
                            if (renderTarget != null)
                            {
                                context.ClearRenderTargetView(renderTarget.RenderTargetView, command.Color);
                            }
                        }
                        break;

                    case RenderCommandType.Clear_Depth:
                        {
                            var command = c as DepthStencilClearCommand;
                            var depthStencil = m_resources.TextureManager.Get(command.ResourceID);
                            if (depthStencil != null)
                            {
                                context.ClearDepthStencilView(depthStencil.DepthStencilView
                                    , SharpDX.Direct3D11.DepthStencilClearFlags.Depth
                                    , command.Depth, command.Stencil);
                            }
                        }
                        break;
                        */

                        case RenderCommandType.VertexBuffer_Update:
                        {
                            var command = c as VertexBufferUpdateCommand;
                            var vertexBuffer = m_vertexBufferManager.Get(command.ResourceID);
                            if (vertexBuffer != null)
                            {
                                if (command.Ptr != IntPtr.Zero)
                                {
                                    var data = new SharpDX.DataBox(command.Ptr);
                                    context.UpdateSubresource(data, vertexBuffer.Vertices);
                                }
                            }
                        }
                        break;

                        case RenderCommandType.VertexBuffer_Set:
                            {
                                var command = c as VertexBufferSetCommand;
                                var vertexBuffer = m_vertexBufferManager.Get(command.ResourceID);
                                if (vertexBuffer != null)
                                {
                                    context.InputAssembler.PrimitiveTopology = vertexBuffer.Topology;

                                    context.InputAssembler.SetVertexBuffers(0,
                                        new SharpDX.Direct3D11.VertexBufferBinding(vertexBuffer.Vertices
                                            , vertexBuffer.Stride, 0));
                                    if (vertexBuffer.Indices != null)
                                    {
                                        context.InputAssembler.SetIndexBuffer(vertexBuffer.Indices, SharpDX.DXGI.Format.R32_UInt, 0);
                                    }

                                    m_vertexBuffer = vertexBuffer;
                                }
                            }
                            break;

                        case RenderCommandType.ShaderVriable_Set:
                            {
                                var command = c as ShaderVariableSetCommand;
                                m_pass.SetConstantVariable(command);
                            }
                            break;

                        /*
                    case RenderCommandType.ShaderTexture_Set:
                        {
                            var command = c as ShaderTextureSetCommand;
                            var texture = m_resources.TextureManager.Get(command.ResourceID);
                            if (texture != null)
                            {
                                m_pass.SetSRV(context, command.Key, texture.ShaderResourceView);
                            }
                        }
                        break;

                    case RenderCommandType.ShaderSampler_Set:
                        {
                            var command = c as ShaderSamplerSetCommand;
                            Pass.SetSampler(command);
                        }
                        break;
                        */

                        case RenderCommandType.Shader_Set:
                            {
                                var command = c as ShaderSetCommand;
                                switch (command.ShaderStage)
                                {
                                    case ShaderStage.Vertex:
                                        {
                                            var vertexShader = m_shaderManager.Get(command.ResourceID) as VertexShaderStage;
                                            if (vertexShader != null)
                                            {
                                                context.VertexShader.Set(vertexShader.Shader);
                                                //context.InputAssembler.InputLayout = vertexShader.VertexLayout;
                                                m_pass.VertexShader = vertexShader;
                                            }
                                        }
                                        break;

                                    case ShaderStage.Geometry:
                                        {
                                            var geometryShader = m_shaderManager.Get(command.ResourceID) as GeometryShaderStage;
                                            if (geometryShader != null)
                                            {
                                                context.GeometryShader.Set(geometryShader.Shader);
                                                m_pass.GeometryShader = geometryShader;
                                            }
                                        }
                                        break;

                                    case ShaderStage.Pixel:
                                        {
                                            var pixelShader = m_shaderManager.Get(command.ResourceID) as PixelShaderStage;
                                            if (pixelShader != null)
                                            {
                                                context.PixelShader.Set(pixelShader.Shader);
                                                m_pass.PixelShader = pixelShader;
                                            }
                                        }
                                        break;

                                    default:
                                        throw new NotImplementedException();
                                }
                            }
                            break;

                        case RenderCommandType.Shader_DrawSubMesh:
                            {
                                var command = c as ShaderDrawSubMeshCommand;
                                if (m_pass.VertexShader != null)
                                {
                                    context.InputAssembler.InputLayout = m_pass.VertexShader.VertexLayout;
                                    // 定数バッファの適用
                                    m_pass.Apply(context);

                                    if (m_vertexBuffer != null)
                                    {
                                        if (m_vertexBuffer.Indices != null)
                                        {
                                            context.DrawIndexed(command.Count, command.Offset, 0);
                                        }
                                        else
                                        {
                                            context.Draw(command.Count, command.Offset);
                                        }
                                    }
                                }
                            }
                            break;

                            /*
                        case RenderCommandType.BlendState_Set:
                            {
                                var command = c as BlendStateSetCommand;
                                var blendState = m_resources.BlendStateManager.Get(command.ResourceID);
                                if (blendState == null)
                                {
                                    return;
                                }
                                context.OutputMerger.SetBlendState(blendState.State, SharpDX.Color4.White);
                            }
                            break;

                        case RenderCommandType.DepthStencilState_Set:
                            {
                                var command = c as DepthStencilStateSetCommand;
                                var depthStencilState = m_resources.DepthStencilStateManager.Get(command.ResourceID);
                                if (depthStencilState == null)
                                {
                                    return;
                                }
                                context.OutputMerger.SetDepthStencilState(depthStencilState.State);
                            }
                            break;
                            */
                    }
                }
                context.Flush();
            }
            Backbuffer = null;
            RTV = null;

            /////////////////////////////////////////////////
            // flip
            /////////////////////////////////////////////////
            var flags = SharpDX.DXGI.PresentFlags.None;
            flags|=SharpDX.DXGI.PresentFlags.DoNotWait;
            SwapChain.Present(0, flags, new SharpDX.DXGI.PresentParameters());
        }