Example #1
0
        private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
        {
            using (var frame = sender.TryGetNextFrame())
            {
                var needsReset     = false;
                var recreateDevice = false;

                if ((frame.ContentSize.Width != _lastSize.Width) || (frame.ContentSize.Height != _lastSize.Height))
                {
                    needsReset = true;
                    _lastSize  = frame.ContentSize;
                }

                try
                {
                    using (var backBuffer = _swapChain.GetBackBuffer <Texture2D>(0))
                    {
                        using (var bitmap = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface))
                        {
                            // copy current surface to backbuffer
                            _d3dDevice.ImmediateContext.CopyResource(bitmap, backBuffer);

                            // Create buffer for the resized copy
                            var width  = StreamWidth;
                            var height = StreamHeight;

                            using (var copy = new Texture2D(_d3dDevice, new Texture2DDescription {
                                Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = bitmap.Description.Format,
                                Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None
                            }))
                            {
                                // Copy region from captured bitmap to stream bitmap
                                _d3dDevice.ImmediateContext.CopySubresourceRegion(backBuffer, 0, ROI, copy, 0);

                                // access the copied data in a stream
                                _d3dDevice.ImmediateContext.MapSubresource(copy, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out DataStream stream);
                                _buf.Add(new BufferedFrame(stream, new SizeInt32 {
                                    Width = width, Height = height
                                }, bitmap.Description.Format));
                                _d3dDevice.ImmediateContext.UnmapSubresource(copy, 0);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    needsReset     = true;
                    recreateDevice = true;
                }

                if (needsReset)
                {
                    _swapChain.ResizeBuffers(_swapChain.Description1.BufferCount, _lastSize.Width, _lastSize.Height, _swapChain.Description1.Format, _swapChain.Description1.Flags);
                    ResetFramePool(_lastSize, recreateDevice);
                }
            }
        }
Example #2
0
        private void Resize()
        {
            _deviceContext?.Dispose();
            _deviceContext = null;

            _swapChain?.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);

            CreateDeviceContext();
        }
Example #3
0
        public ScreenGrabberWindowsCapture(MonitorInfo screen) : base(screen)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var device = WindowsCaptureHelper.CreateDirect3DDeviceFromSharpDXDevice(new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport));
                _d3dDevice = WindowsCaptureHelper.CreateSharpDXDevice(device);
                var item   = WindowsCaptureHelper.CreateItemForMonitor(Screen.HMon);

                var factory = new Factory2();

                var description = new SwapChainDescription1
                {
                    Width             = item.Size.Width,
                    Height            = item.Size.Height,
                    Format            = Format.B8G8R8A8_UNorm,
                    Stereo            = false,
                    SampleDescription = new SampleDescription
                    {
                        Count   = 1,
                        Quality = 0
                    },
                    Usage       = Usage.RenderTargetOutput,
                    BufferCount = 2,
                    Scaling     = Scaling.Stretch,
                    SwapEffect  = SwapEffect.FlipSequential,
                    AlphaMode   = AlphaMode.Premultiplied,
                    Flags       = SwapChainFlags.None
                };

                _swapChain = new SwapChain1(factory, _d3dDevice, ref description);
                _framePool = Direct3D11CaptureFramePool.Create(device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size);
                _session   = _framePool.CreateCaptureSession(item);
                _session.IsCursorCaptureEnabled = false;

                _swapChain.ResizeBuffers(2, item.Size.Width, item.Size.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);

                _screenTexture = new Texture2D(_d3dDevice, new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = item.Size.Width,
                    Height            = item.Size.Height,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                });

                _framePool.FrameArrived += OnFrameArrived;

                _session.StartCapture();
            });
        }
Example #4
0
        private void ResizeBuffers(object sender, EventArgs e)
        {
            if (device == null)
            {
                return;
            }

            lock (device)
            {
                Utilities.Dispose(ref rtv);
                Utilities.Dispose(ref backBuffer);

                swapChain.ResizeBuffers(0, player.Control.Width, player.Control.Height, Format.Unknown, SwapChainFlags.None);
                backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
                rtv        = new RenderTargetView(device, backBuffer);

                SetViewport();
                PresentFrame(null);
            }
        }
Example #5
0
        public void Resize(int width, int height)
        {
            if (m_swapChain == null)
            {
                return;
            }
            var desc = m_swapChain.Description;

            m_swapChain.ResizeBuffers(desc.BufferCount, width, height,
                                      desc.ModeDescription.Format, desc.Flags);
        }
Example #6
0
        void Resize()
        {
            d2dDeviceContext.Target = null;
            d2dSurface.Dispose();
            swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);
            Surface1 dxgiSurface = swapChain.GetBackBuffer <Surface1>(0);
            var      props       = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
                                                         d2dDeviceContext.DotsPerInch.Width,
                                                         d2dDeviceContext.DotsPerInch.Height,
                                                         BitmapOptions.Target | BitmapOptions.CannotDraw);

            d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props);
            dxgiSurface.Dispose();
            d2dDeviceContext.Target = d2dSurface;
        }
Example #7
0
 /// <summary>
 /// Called when [create render target and depth buffers].
 /// </summary>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <returns></returns>
 protected override ShaderResourceViewProxy OnCreateBackBuffer(int width, int height)
 {
     if (swapChain == null || swapChain.IsDisposed)
     {
         swapChain = CreateSwapChain(surfacePtr);
     }
     else
     {
         RemoveAndDispose(ref d2dTarget);
         RemoveAndDispose(ref backBuffer);
         swapChain.ResizeBuffers(swapChain.Description1.BufferCount, TargetWidth, TargetHeight, swapChain.Description.ModeDescription.Format, swapChain.Description.Flags);
     }
     backBuffer = new ShaderResourceViewProxy(Device, Texture2D.FromSwapChain <Texture2D>(swapChain, 0));
     d2dTarget  = new D2DTargetProxy();
     d2dTarget.Initialize(swapChain, DeviceContext2D);
     return(backBuffer);
 }
Example #8
0
        /// <summary>
        /// Called when [create render target and depth buffers].
        /// </summary>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <returns></returns>
        protected override ShaderResourceViewProxy OnCreateBackBuffer(int width, int height)
        {
            if (swapChain == null || swapChain.IsDisposed)
            {
                swapChain = CreateSwapChain(surfacePtr);
            }
            else
            {
                swapChain.ResizeBuffers(swapChain.Description1.BufferCount, TargetWidth, TargetHeight, swapChain.Description.ModeDescription.Format, swapChain.Description.Flags);
            }
            var backBuffer = Collect(new ShaderResourceViewProxy(Device, Texture2D.FromSwapChain <Texture2D>(swapChain, 0)));
            var sampleDesc = swapChain.Description1.SampleDescription;

            ColorBuffer.CreateRenderTargetView();
            d2dTarget = Collect(new D2DTargetProxy());
            d2dTarget.Initialize(swapChain, DeviceContext2D);
            return(backBuffer);
        }
Example #9
0
        public override void Resize()
        {
            _dev.ImmediateContext.OutputMerger.SetRenderTargets(null, (RenderTargetView)null);
            _renderTarget?.Dispose();
            _depthStencil?.Dispose();
            _swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);

            SwapChainDescription1 desc  = _swapChain.Description1;
            Texture2D             color = _swapChain.GetBackBuffer <Texture2D>(0);

            _renderTarget = new RenderTargetView(_dev, color);
            color.Dispose();

            Texture2DDescription textureDesc = new Texture2DDescription();

            textureDesc.Width             = desc.Width;
            textureDesc.Height            = desc.Height;
            textureDesc.MipLevels         = 1;
            textureDesc.ArraySize         = 1;
            textureDesc.SampleDescription = desc.SampleDescription;
            textureDesc.Usage             = ResourceUsage.Default;
            textureDesc.BindFlags         = BindFlags.DepthStencil;
            textureDesc.CpuAccessFlags    = CpuAccessFlags.None;
            textureDesc.OptionFlags       = ResourceOptionFlags.None;
            textureDesc.Format            = Format.D24_UNorm_S8_UInt;

            Texture2D depthStencil = new Texture2D(_dev, textureDesc);

            _depthStencil = new DepthStencilView(_dev, depthStencil);
            depthStencil.Dispose();

            _viewport.X        = 0.0f;
            _viewport.Y        = 0.0f;
            _viewport.Width    = (float)desc.Width;
            _viewport.Height   = (float)desc.Height;
            _viewport.MinDepth = 0.0f;
            _viewport.MaxDepth = 1.0f;
        }
        /// <summary>
        /// Called when [create render target and depth buffers].
        /// </summary>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="createDepthStencilBuffer"></param>
        /// <returns></returns>
        protected override Texture2D OnCreateRenderTargetAndDepthBuffers(int width, int height, bool createDepthStencilBuffer)
        {
            if (swapChain == null || swapChain.IsDisposed)
            {
                swapChain = CreateSwapChain(surfacePtr);
            }
            else
            {
                swapChain.ResizeBuffers(swapChain.Description1.BufferCount, TargetWidth, TargetHeight, swapChain.Description.ModeDescription.Format, swapChain.Description.Flags);
            }
            colorBuffer = Collect(Texture2D.FromSwapChain <Texture2D>(swapChain, 0));
            var sampleDesc = swapChain.Description1.SampleDescription;

            colorBufferView = Collect(new RenderTargetView(Device, colorBuffer));

            if (createDepthStencilBuffer)
            {
                var depthdesc = new Texture2DDescription
                {
                    BindFlags = BindFlags.DepthStencil,
                    //Format = Format.D24_UNorm_S8_UInt,
                    Format            = Format.D32_Float_S8X24_UInt,
                    Width             = width,
                    Height            = height,
                    MipLevels         = 1,
                    SampleDescription = sampleDesc,
                    Usage             = ResourceUsage.Default,
                    OptionFlags       = ResourceOptionFlags.None,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    ArraySize         = 1,
                };
                depthStencilBuffer     = Collect(new Texture2D(Device, depthdesc));
                depthStencilBufferView = Collect(new DepthStencilView(Device, depthStencilBuffer));
            }
            d2dTarget = Collect(new D2DTargetProxy());
            d2dTarget.Initialize(swapChain, DeviceContext2D);
            return(colorBuffer);
        }
Example #11
0
        public void Resize(int width, int height)
        {
            if (width != _width || height != _height)
            {
                if (_rtv != null)
                {
                    _rtv.Dispose();
                    _rtv = null;
                }

                if (_swap != null)
                {
                    _swap.ResizeBuffers(2, width, height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
                    _width  = width;
                    _height = height;
                }
                else
                {
                    InitSwapChain(width, height);
                    SetChainToPanel();
                }
                RetrieveSetBuffers();
            }
        }
Example #12
0
        public void Resize(object sender, WindowEventArgs pE)
        {
            try
            {
                Device.ImmediateContext.ClearState();

                _backBuffer.Dispose();
                _renderTarget.Dispose();
                Context.Dispose();

                _swapChain.ResizeBuffers(BUFFER_COUNT, (int)pE.Size.Width, (int)pE.Size.Height, Format.Unknown, SwapChainFlags.AllowModeSwitch);

                Context = new SharpDX.Direct2D1.DeviceContext(_2dDevice, DeviceContextOptions.None);
                var dpi  = Factory2D.DesktopDpi;
                var prop = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), dpi.Height, dpi.Width, BitmapOptions.CannotDraw | BitmapOptions.Target);
                _backBuffer    = _swapChain.GetBackBuffer <Surface>(0);
                _renderTarget  = new Bitmap1(Context, _backBuffer, prop);
                Context.Target = _renderTarget;
            }
            catch (System.Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error creating render target: " + e.Message);
            }
        }
        protected virtual void CreateSizeDependentResources()
        {
            // Ensure dependent objects have been released.
            d2dContext.Target = null;
            if (d2dTargetBitmap != null)
            {
                RemoveAndDispose(ref d2dTargetBitmap);
            }
            d3dContext.OutputMerger.SetRenderTargets((RenderTargetView)null);
            d3dContext.Flush();

            /*d3dContext.FinishCommandList(false);
             * d3dContext.li*/

            // Set render target size to the rendered size of the panel including the composition scale,
            // defaulting to the minimum of 1px if no size was specified.
            var scale              = Dpi / 96;
            var renderTargetWidth  = (int)(panel.ActualWidth * scale);
            var renderTargetHeight = (int)(panel.ActualHeight * scale);

            if (renderTargetWidth == 0 || renderTargetHeight == 0)
            {
                return;
            }

            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, renderTargetWidth, renderTargetHeight, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
            }
            else
            {
                var swapChainDesc = new SwapChainDescription1();
                swapChainDesc.Width  = renderTargetWidth;
                swapChainDesc.Height = renderTargetHeight;
                swapChainDesc.Format = Format.B8G8R8A8_UNorm;
                swapChainDesc.Stereo = new RawBool(false);
                swapChainDesc.SampleDescription.Count   = 1;
                swapChainDesc.SampleDescription.Quality = 0;
                swapChainDesc.Usage       = Usage.RenderTargetOutput;
                swapChainDesc.BufferCount = 2;
                swapChainDesc.SwapEffect  = SwapEffect.FlipSequential;
                swapChainDesc.Flags       = SwapChainFlags.None;
                swapChainDesc.AlphaMode   = AlphaMode.Unspecified; // Todo... May need to change
                //swapChainDesc.Scaling = Scaling.None;

                using (var dxgiDevice = d3dDevice.QueryInterface <global::SharpDX.DXGI.Device1>())
                {
                    var dxgiAdapter = dxgiDevice.Adapter;
                    var dxgiFactory = dxgiAdapter.GetParent <global::SharpDX.DXGI.Factory2>();

                    swapChain = Collect(new SwapChain1(dxgiFactory, d3dDevice, ref swapChainDesc, null));

                    // Counter act the composition scale of the render target as
                    // we already handle this in the platform window code.
                    using (var swapChain2 = swapChain.QueryInterface <SwapChain2>())
                    {
                        var inverseScale = new RawMatrix3x2();
                        inverseScale.M11           = 1.0f / scale;
                        inverseScale.M22           = 1.0f / scale;
                        swapChain2.MatrixTransform = inverseScale;
                    }

                    dxgiDevice.MaximumFrameLatency = 1;
                }

                // Associate the SwapChainBackgroundPanel with the swap chain
                using (var panelNative = ComObject.As <ISwapChainPanelNative>(panel))
                {
                    panelNative.SwapChain = swapChain;
                }
            }

            var bitmapProperties = new BitmapProperties1(
                new PixelFormat(Format.B8G8R8A8_UNorm, global::SharpDX.Direct2D1.AlphaMode.Premultiplied),
                Dpi,
                Dpi,
                BitmapOptions.Target | BitmapOptions.CannotDraw);

            using (var dxgiBackBuffer = swapChain.GetBackBuffer <Surface>(0))
            {
                d2dTargetBitmap   = Collect(new Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));
                d2dContext.Target = d2dTargetBitmap;
            }
        }
Example #14
0
 public void Resize(Size2 size)
 {
     SwapChain?.ResizeBuffers(0, size.Width, size.Height, Format.Unknown, SwapChainFlags.None);
 }
Example #15
0
        protected void InitialiseResources()
        {
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _surface);
            RemoveAndDispose(ref _target);
            _d2dContext.Target = null;

            var desc = CreateSwapChainDescription();

            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(
                    _swapChain.Description.BufferCount,
                    WindowSize.Width,
                    WindowSize.Height,
                    _swapChain.Description.ModeDescription.Format,
                    _swapChain.Description.Flags);
            }
            else
            {
                using (var dxgiDevice2 = _d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                        {
                            _swapChain = ToDispose(new SwapChain1(dxgiFactory2, _d3dDevice, _outputHandle, ref desc));
                            //_swapChain = ToDispose(new SwapChain1(dxgiFactory2, _d3dDevice, _outputHandle, ref desc));
                        }
            }

            _backBuffer = ToDispose(Resource.FromSwapChain <Texture2D>(_swapChain, 0));
            {
                // Create a view interface on the rendertarget to use on bind.
                _renderTargetView = new RenderTargetView(_d3dDevice, _backBuffer);

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

            using (var depthBuffer = new Texture2D(_d3dDevice,
                                                   new Texture2DDescription()
            {
                Format = Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)WindowSize.Width,
                Height = (int)WindowSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags = BindFlags.DepthStencil,
            }))
                _depthStencilView = new DepthStencilView(_d3dDevice, depthBuffer, new DepthStencilViewDescription()
                {
                    Dimension = DepthStencilViewDimension.Texture2D
                });

            var viewport = new ViewportF((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            _d3dContext.Rasterizer.SetViewport(viewport);

            var bitmapProperties = new BitmapProperties1(
                new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied),
                _d2dFactory.DesktopDpi.Width,
                _d2dFactory.DesktopDpi.Height,
                BitmapOptions.Target | BitmapOptions.CannotDraw);


            using (var dxgiBackBuffer = _swapChain.GetBackBuffer <Surface>(0))
                _target = new Bitmap1(_d2dContext, dxgiBackBuffer, bitmapProperties);

            _d2dContext.Target            = _target;
            _d2dContext.TextAntialiasMode = TextAntialiasMode.Grayscale;

            /*_backBuffer = ToDispose(Resource.FromSwapChain<Texture2D>(_swapChain, 0));
             * _renderTargetView = ToDispose(new RenderTargetView(_d3dDevice, _backBuffer));
             * _surface = ToDispose(_backBuffer.QueryInterface<Surface>());
             *
             * using (var dxgiBackBuffer = _swapChain.GetBackBuffer<Surface>(0))
             *  _target = ToDispose(new RenderTarget(_d2dFactory, dxgiBackBuffer, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))));
             */
            OnInitialize?.Invoke(this);
        }
Example #16
0
        /// <summary>
        /// Creates the size dependent drawing resources.
        /// </summary>
        private void CreateSizeDependentResources()
        {
            _d2dContext.Target = null;

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

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

            // Generate a swap chain for our window based on the specified description.
            if (_swapChain == null)
            {
                // Query for the adapter and more advanced DXGI objects.
                using (var dxgiDevice2 = _device.QueryInterface <SharpDX.DXGI.Device2>())
                {
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                    {
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                        {
                            // Description for our swap chain settings.
                            SwapChainDescription1 description = new SwapChainDescription1()
                            {
                                Width             = _width * (int)_scale,
                                Height            = _height * (int)_scale,
                                Format            = Format.B8G8R8A8_UNorm,
                                Stereo            = false,
                                SampleDescription = new SampleDescription(1, 0),
                                Usage             = Usage.RenderTargetOutput,
                                BufferCount       = 2,
                                Scaling           = Scaling.Stretch,
                                SwapEffect        = SwapEffect.FlipSequential,
                                Flags             = SwapChainFlags.AllowModeSwitch
                            };

                            _swapChain = new SwapChain1(dxgiFactory2, _device, _form.Handle, ref description);
                        }
                    }
                }
            }
            else
            {
                _swapChain.ResizeBuffers(0, _width * (int)_scale, _height * (int)_scale, Format.B8G8R8A8_UNorm, SwapChainFlags.AllowModeSwitch);
            }

            Size2F dpi = _d2dFactory.DesktopDpi;

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                dpi.Height,
                dpi.Width,
                BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            _backBuffer = Surface.FromSwapChain(_swapChain, 0);
            _d2dTarget  = new Bitmap1(_d2dContext, _backBuffer, properties);

            _d2dContext.Target = _d2dTarget;
        }
Example #17
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 the swap chain first, then blit the pixels.
                    // After we do that, retire the frame and then recreate the frame pool.
                    newSize         = true;
                    lastSize        = frame.ContentSize;
                    lastSize.Width  = lastSize.Width / 8 * 8;
                    lastSize.Height = lastSize.Height / 8 * 8;
                    swapChain.ResizeBuffers(
                        2,
                        lastSize.Width,
                        lastSize.Height,
                        Format.B8G8R8A8_UNorm,
                        SwapChainFlags.None);
                }

                using (var backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                    using (var bitmap = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface))
                    {
                        d3dDevice.ImmediateContext.CopyResource(bitmap, backBuffer);

                        if (lastFrame != null)
                        {
                            d3dDevice.ImmediateContext.UnmapSubresource(lastFrame, 0);
                            lastFrame.Dispose();
                        }

                        // Create texture copy
                        lastFrame = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription
                        {
                            Width             = bitmap.Description.Width,
                            Height            = bitmap.Description.Height,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            Format            = Format.B8G8R8A8_UNorm,
                            Usage             = ResourceUsage.Staging,
                            SampleDescription = new SampleDescription(1, 0),
                            BindFlags         = BindFlags.None,
                            CpuAccessFlags    = CpuAccessFlags.Read,
                            OptionFlags       = ResourceOptionFlags.None
                        });
                        d3dDevice.ImmediateContext.CopyResource(bitmap, lastFrame);

                        var dataBox = d3dDevice.ImmediateContext.MapSubresource(lastFrame, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out DataStream stream);
                        var rect    = new DataRectangle
                        {
                            DataPointer = stream.DataPointer,
                            Pitch       = dataBox.RowPitch
                        };
                        lastMat = new Mat(lastFrame.Description.Height, lastFrame.Description.Width, MatType.CV_8UC4, stream.DataPointer); // width % 4 != 0

                        OnFrameReady(EventArgs.Empty);
                    }
            } // Retire the frame.

            // swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);
            if (newSize)
            {
                framePool.Recreate(
                    device,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    2,
                    lastSize);
            }
        }
Example #18
0
            private void SetupScreenBuffers()
            {
                width  = (int)window.Bounds.Width;
                height = (int)window.Bounds.Height;

                // If the swap chain already exists, resize it.
                if (swapChain != null)
                {
                    swapChain.ResizeBuffers(2, width, height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
                }
                // Otherwise, create a new one.
                else
                {
                    // SwapChain description
                    var desc = new SwapChainDescription1
                    {
                        // Automatic sizing
                        Width             = width,
                        Height            = height,
                        Format            = Format.B8G8R8A8_UNorm,
                        Stereo            = false,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                        // Use two buffers to enable flip effect.
                        BufferCount = 2,
                        Scaling     = Scaling.None,
                        SwapEffect  = SwapEffect.FlipSequential,
                    };

                    // 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 = graphicsDevice.QueryInterface <Device2>())
                        using (Adapter dxgiAdapter = dxgiDevice2.Adapter)
                            using (var dxgiFactory2 = dxgiAdapter.GetParent <Factory2>())
                            {
                                // Creates a SwapChain from a CoreWindow pointer
                                using (var comWindow = new ComObject(window))
                                    swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(graphicsDevice, comWindow, ref desc, null);

                                // 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 = ToDispose(Resource.FromSwapChain <Texture2D>(swapChain, 0));
                {
                    // Create a view interface on the rendertarget to use on bind.
                    renderTargetView = ToDispose(new RenderTargetView(graphicsDevice, backBuffer));
                }

                // Create a viewport descriptor of the full window size.
                var viewport = new Viewport(0, 0, width, height, 0.0f, 1.0f);

                // Set the current viewport using the descriptor.
                graphicsDevice.ImmediateContext.Rasterizer.SetViewport(viewport);
            }
Example #19
0
        /// <summary>
        /// Resizes the GBuffer.
        /// </summary>
        internal void Resize(Device device)
        {
            UpdateProjectionMatrix();
            RebuildFrustum(_frustumCulling);

            CanRender = false;

            var newWidth  = Math.Max(1, (int)_viewportSize.x);
            var newHeight = Math.Max(1, (int)_viewportSize.y);

            RenderTarget2D?.Dispose();
            RenderTarget2D = null;

            Renderer.Context2D.Target = null;

            _surface?.Dispose();
            BackBuffer?.Dispose();
            Buffer0?.Dispose();
            Buffer1?.Dispose();
            Buffer2?.Dispose();
            Buffer3?.Dispose();
            DepthStencilBuffer?.Dispose();

            Viewport = new ViewportF(0, 0, ViewportSize.x, ViewportSize.y);

            try
            {
                SwapChain.ResizeBuffers(RenderConstants.FrameCount, newWidth, newHeight,
                                        RenderConstants.BackBufferFormat, SwapChainFlags.None);
            }
            catch (SharpDXException e)
            {
                Logger.Error(e);
                throw;
            }

            var backBufferTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0);

            BackBuffer = new Texture(backBufferTexture);

            Buffer0 = CreateCameraBuffer("Buffer0", 1f, RenderConstants.BackBufferFormat);
            Buffer1 = CreateCameraBuffer("Buffer1", 1f, Format.R8G8B8A8_UNorm);
            Buffer2 = CreateCameraBuffer("Buffer2", 1f, Format.R16G16B16A16_Float);
            Buffer3 = CreateCameraBuffer("Buffer3", 1f, Format.R8G8B8A8_UNorm);
            BufferDownscaleHalf0    = CreateCameraBuffer("BufferDownsampleHalf0", 1 / 2f, Format.R8G8B8A8_UNorm);
            BufferDownscaleHalf1    = CreateCameraBuffer("BufferDownsampleHalf1", 1 / 2f, Format.R8G8B8A8_UNorm);
            BufferDownscaleQuarter0 = CreateCameraBuffer("BufferDownsampleQuarter0", 1 / 4f, Format.R8G8B8A8_UNorm);
            BufferDownscaleQuarter1 = CreateCameraBuffer("BufferDownsampleQuarter1", 1 / 4f, Format.R8G8B8A8_UNorm);

            var depthStencilBuffer = new Texture2D(Renderer.Device, new Texture2DDescription
            {
                Format            = Format.R24G8_Typeless,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = newWidth,
                Height            = newHeight,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            DepthStencilBuffer = new Texture(depthStencilBuffer, new DepthStencilViewDescription
            {
                Format    = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D
            }, new ShaderResourceViewDescription
            {
                Format    = Format.R24_UNorm_X8_Typeless,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip = 0,
                    MipLevels       = -1
                }
            });

            _surface           = BackBuffer.QueryInterface <Surface>();
            _surface.DebugName = "BackBufferSurface";

            try
            {
                RenderTarget2D = new Bitmap1(Renderer.Context2D, _surface,
                                             new BitmapProperties1(new PixelFormat(_surface.Description.Format, AlphaMode.Premultiplied), 96,
                                                                   96, BitmapOptions.Target | BitmapOptions.CannotDraw));
            }
            catch (Exception)
            {
                _surface.Dispose();
                RenderTarget2D?.Dispose();
                Logger.Info("An exception occured while creating the GUI surface render target.");
                throw;
            }

            lock (Locker)
            {
                foreach (var collector in LayerCollectors)
                {
                    collector.Target = RenderTarget2D;
                }
            }

            lock (PostEffectsLocker)
            {
                foreach (var effect in PostEffects)
                {
                    effect.UpdateSize(this);
                }
            }

            var cb = Constants;

            cb.Data.ScreenParams.X = newWidth;
            cb.Data.ScreenParams.Y = newHeight;
            cb.Data.ScreenParams.Z = AspectRatio;
            cb.Data.ScreenParams.W = FieldOfView * 0.5f / newHeight;

            NeedsResize = false;
            CanRender   = true;
            //Logger.Trace("Camera resized.");
        }