static void Main()
        {
            #region Direct3D Initialization
            // Create the window to render to
            Form1 form = new Form1();
            form.Text = "D3DRendering - Initialize D3D 11.1";
            form.Width = 640;
            form.Height = 480;

            // Create the device and swapchain
            Device1 device;
            SwapChain1 swapChain;

            // First create a regular D3D11 device
            using (
                var device11 = new Device(
                    SharpDX.Direct3D.DriverType.Hardware,
                    DeviceCreationFlags.None,
                    new [] {
                        SharpDX.Direct3D.FeatureLevel.Level_11_1,
                        SharpDX.Direct3D.FeatureLevel.Level_11_0,
                    }))
            {
                // Query device for the Device1 interface (ID3D11Device1)
                device = device11.QueryInterfaceOrNull<Device1>();

                if (device == null)
                    throw new NotSupportedException("SharpDX.Direct3D11.Device1 is not supported");
            }

            // Rather than create a new DXGI Factory we should reuse
            // the one that has been used internally to create the device
            using (var dxgi = device.QueryInterface<SharpDX.DXGI.Device2>())
            using (var adapter = dxgi.Adapter)
            using (var factory = adapter.GetParent<Factory2>())
            {
                var desc1 = new SwapChainDescription1()
                {
                    Width = form.ClientSize.Width,
                    Height = form.ClientSize.Height,
                    Format = Format.R8G8B8A8_UNorm,
                    Stereo = false,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                    BufferCount = 1,
                    Scaling = Scaling.Stretch,
                    SwapEffect = SwapEffect.Discard,
                };

                swapChain = new SwapChain1(factory,
                    device,
                    form.Handle,
                    ref desc1,
                    new SwapChainFullScreenDescription()
                    {
                        RefreshRate = new Rational(60, 1),
                        Scaling = DisplayModeScaling.Centered,
                        Windowed = true
                    },
                    // Restrict output to specific Output (monitor)
                    null);
            }

            // Create references to backBuffer and renderTargetView
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderTargetView = new RenderTargetView(device, backBuffer);

            #endregion

            #region Render loop

            // Create Clock and FPS counters
            var clock = new System.Diagnostics.Stopwatch();
            var clockFrequency = (double)System.Diagnostics.Stopwatch.Frequency;
            clock.Start();
            var deltaTime = 0.0;
            var fpsTimer = new System.Diagnostics.Stopwatch();
            fpsTimer.Start();
            var fps = 0.0;
            int fpsFrames = 0;

            // Create and run the render loop
            RenderLoop.Run(form, () =>
            {
                // Time in seconds
                var totalSeconds = clock.ElapsedTicks / clockFrequency;

                #region FPS and title update
                fpsFrames++;
                if (fpsTimer.ElapsedMilliseconds > 1000)
                {
                    fps = 1000.0 * fpsFrames / fpsTimer.ElapsedMilliseconds;

                    // Update window title with FPS once every second
                    form.Text = string.Format("D3DRendering D3D11.1 - FPS: {0:F2} ({1:F2}ms/frame)", fps, (float)fpsTimer.ElapsedMilliseconds / fpsFrames);

                    // Restart the FPS counter
                    fpsTimer.Reset();
                    fpsTimer.Start();
                    fpsFrames = 0;
                }
                #endregion

                // Execute rendering commands here...
                device.ImmediateContext.ClearRenderTargetView(
                    renderTargetView,
                    Color.LightBlue);

                // Present the frame
                swapChain.Present(0, PresentFlags.None, new PresentParameters());

                // Determine the time it took to render the frame
                deltaTime = (clock.ElapsedTicks / clockFrequency) - totalSeconds;
            });
            #endregion

            #region Direct3D Cleanup

            // Release the device and any other resources created
            renderTargetView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();

            #endregion
        }
        /// <summary>
        /// Present the results to the swap chain.
        /// </summary>
        public virtual void Present()
        {
            // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
            // in certain scenarios.  In this sample, however, we do not utilize those features.
            var parameters = new SharpDX.DXGI.PresentParameters();

            try
            {
                // The first argument instructs DXGI to block until VSync, putting the application
                // to sleep until the next VSync. This ensures we don't waste any cycles rendering
                // frames that will never be displayed to the screen.
                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None, parameters);
            }
            catch (SharpDX.SharpDXException ex)
            {
                // TODO PLUG CODE HERE TO REINITIALIZE

                // If the device was removed either by a disconnect or a driver upgrade, we
                // must completely reinitialize the renderer.
                if (ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceRemoved ||
                    ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceReset)
                {
                    deviceManager.InitializeDeviceDependentResources();
                }
                else
                {
                    throw;
                }
            }
        }
Example #3
0
        /// <summary>
        /// Present the back buffer of the swap chain.
        /// </summary>
        public virtual void Present()
        {
            // The application may optionally specify "dirty" or "scroll" rects to improve efficiency
            // in certain scenarios. In this sample we do not utilize those features.
            var parameters = new SharpDX.DXGI.PresentParameters();

            try
            {
                // If enabled the first argument instructs DXGI to block until VSync,
                // putting the application to sleep until the next VSync.
                // This ensures we don't waste any CPU/GPU cycles rendering frames that will never
                // be displayed to the screen.
                _swapChain.Present((VSync ? 1 : 0), SharpDX.DXGI.PresentFlags.None, parameters);
            }
            catch (SharpDX.SharpDXException ex)
            {
                // If the device was removed either by a disconnect or a driver upgrade, we
                // must completely reinitialize the renderer.
                if (ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceRemoved ||
                    ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceReset)
                {
                    DeviceManager.Initialize(DeviceManager.Dpi);
                }
                else
                {
                    throw;
                }
            }
        }
Example #4
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;

                    swapChain.ResizeBuffers(
                        2,
                        lastSize.Width,
                        lastSize.Height,
                        SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        SharpDX.DXGI.SwapChainFlags.None);
                }

                if (!isWait)
                {
                    if (isStartCapture)
                    {
                        using (var backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                            using (var bitmap = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface))
                            {
                                //d3dDevice.ImmediateContext.CopyResource(bitmap, backBuffer);
                                CopyBitmap(frame.Surface, bitmap, frame.ContentSize.Width, frame.ContentSize.Height);

                                Console.WriteLine("Capture");

                                bitmap.Dispose();
                            };

                        isStartCapture = false;
                    }
                }

                //using (var backBuffer = swapChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0))
            } // Retire the frame.

            swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);

            if (newSize)
            {
                framePool.Recreate(
                    device,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    2,
                    lastSize);
            }
        }
Example #5
0
        private void OnRender()
        {
            lock (_renderContextLock)
            {
                if (_renderTarget?.IsDisposed ?? true)
                {
                    return;
                }

                _renderTarget.BeginDraw();
                _renderTarget.Clear(_backgroundColor);

                if (_paradigmStarted) // Draw blocks
                {
                    foreach (var block in _blocks)
                    {
                        if (block.BorderWidth > 0)
                        {
                            _solidColorBrush.Color = _blockBorderColor;
                            _renderTarget.FillRectangle(block.BorderRect, _solidColorBrush);
                        }

                        if (_bitmap != null)
                        {
                            _solidColorBrush.Color = _blockNormalColor;
                            _renderTarget.FillRectangle(block.ContentRect, _solidColorBrush);
                            if (block.Actived)
                            {
                                _renderTarget.DrawBitmap(_bitmap, block.ContentRect, 1, D2D1.BitmapInterpolationMode.Linear);
                            }
                        }
                        else
                        {
                            _solidColorBrush.Color = block.Actived ? _blockActivedColor : _blockNormalColor;
                            _renderTarget.FillRectangle(block.ContentRect, _solidColorBrush);
                        }

                        if (block.Target)
                        {
                            _solidColorBrush.Color = _blockBorderColor;
                            _renderTarget.FillEllipse(block.CenterPointEllipse, _solidColorBrush);
                        }
                    }
                }
                else if (!(_displayText?.IsBlank() ?? true)) // Draw text
                {
                    _solidColorBrush.Color = _fontColor;
                    _renderTarget.DrawText(_displayText, _textFormat, new RawRectangleF(0, 0, Width, Height),
                                           _solidColorBrush, D2D1.DrawTextOptions.None);
                }

                _renderTarget.EndDraw();

                _swapChain.Present(1, DXGI.PresentFlags.None, _presentParameters);
            }
        }
Example #6
0
        internal void EndRender()
        {
            if (SyncInterval > 0 || sw.Elapsed.TotalMilliseconds >= 1000.0 / refreshRate)
            {
                D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0);
                deviceContext.ResolveSubresource(surfaceTexture, 0, backBuffer, 0, DXGI.Format.R8G8B8A8_UNorm);
                backBuffer.Dispose();

                swapChain.Present(SyncInterval, DXGI.PresentFlags.None);
                sw.Restart();
            }
        }
        /// <summary>
        /// Called when RenderLoop wants to present its results.
        /// </summary>
        void IRenderLoopHost.OnRenderLoop_Present(EngineDevice engineDevice)
        {
            // Copy contents of the backbuffer if in multisampling mode
            if (m_backBufferMultisampled != null)
            {
                engineDevice.DeviceImmediateContextD3D11.ResolveSubresource(m_backBufferMultisampled, 0, m_backBuffer, 0, GraphicsHelper.DEFAULT_TEXTURE_FORMAT);
            }

            // Present all rendered stuff on screen
            // First parameter indicates synchronization with vertical blank
            //  see http://msdn.microsoft.com/en-us/library/windows/desktop/bb174576(v=vs.85).aspx
            //  see example http://msdn.microsoft.com/en-us/library/windows/apps/hh825871.aspx
            m_swapChain.Present(1, DXGI.PresentFlags.None);
        }
Example #8
0
        private void OnRender()
        {
            lock (_renderContextLock)
            {
                if (RenderTarget?.IsDisposed ?? true)
                {
                    return;
                }

                RenderTarget.BeginDraw();
                OnDraw();
                RenderTarget.EndDraw();

                SwapChain.Present(1, DXGI.PresentFlags.None, _presentParameters);
            }
        }
Example #9
0
        public void RenderFrame()
        {
            if (!_isDisposed)
            {
                _deviceContext.BeginDraw();
                _deviceContext.Clear(SharpDX.Color.White);

                foreach (var visual in _visuals)
                {
                    visual.Render(this);
                }

                _deviceContext.EndDraw();
                _swapChain.Present(1, PresentFlags.None);
            }
        }
Example #10
0
        private void OnRender()
        {
            lock (_renderContextLock)
            {
                if (_renderTarget?.IsDisposed ?? true)
                {
                    return;
                }

                _renderTarget.BeginDraw();
                _renderTarget.Clear(_backgroundColor);

                if (_paradigmStarted && _trialStarted) // Draw blocks
                {
                    var borderRect  = SharpDXUtils.CenteredRect(Width / 2f, Height / 2f, _paradigm.Config.Gui.ButtonSize);
                    var buttonRect  = borderRect.Shrink(Math.Max((float)_paradigm.Config.Gui.ButtonBorder.Width, 0));
                    var paddings    = _paradigm.Config.Gui.ButtonPaddings;
                    var contentRect = buttonRect.Shrink((float)paddings.Left, (float)paddings.Top, (float)paddings.Right, (float)paddings.Bottom);

                    if (_paradigm.Config.Gui.ButtonBorder.Width > 0)
                    {
                        _solidColorBrush.Color = _blockBorderColor;
                        _renderTarget.FillRectangle(borderRect, _solidColorBrush);
                    }

                    _solidColorBrush.Color = _blockNormalColor;
                    _renderTarget.FillRectangle(buttonRect, _solidColorBrush);

                    _solidColorBrush.Color = _foregroundColor;
                    _renderTarget.DrawText(_displayText, _textFormat, contentRect, _solidColorBrush, D2D1.DrawTextOptions.None);
                }
                else if (_displayText?.IsNotBlank() ?? false) // Draw text
                {
                    _solidColorBrush.Color = _foregroundColor;
                    _renderTarget.DrawText(_displayText, _textFormat, new RawRectangleF(0, 0, Width, Height),
                                           _solidColorBrush, D2D1.DrawTextOptions.None);
                }

                _renderTarget.EndDraw();

                _swapChain.Present(1, DXGI.PresentFlags.None, _presentParameters);
            }
        }
 public void Present()
 {
     swapChain.Present(0, PresentFlags.None);
 }
Example #12
0
 /// <summary>
 /// Called when RenderLoop wants to present its results.
 /// </summary>
 void IRenderLoopHost.OnRenderLoop_Present(EngineDevice device)
 {
     //Present all rendered stuff on screen
     m_swapChain.Present(0, DXGI.PresentFlags.DoNotWait, new DXGI.PresentParameters());
 }