public void Render()
 {
     PopulateCommandList();
     commandQueue.ExecuteCommandList(commandList);
     swapChain.Present(1, 0);
     WaitForPreviousFrame();
 }
Exemple #2
0
        public void Render()
        {
            // Record all the commands we need to render the scene into the command list.
            PopulateCommandList();

            // Execute the command list.
            _graphicsQueue.ExecuteCommandList(_commandList);

            // Present the frame.
            _swapChain.Present(0, 0);

            WaitForPreviousFrame();

            //Get FrameInterval and Framerate
            _frameInterval = _gametimer.Elapsed.TotalSeconds - _lastframe;
            _framerate     = 1 / (_gametimer.Elapsed.TotalSeconds - _lastframe);
            _lastframe     = _gametimer.Elapsed.TotalSeconds;
            if (_gametimer.Elapsed.TotalMilliseconds % 10 <= 5)
            {
                _frameLabel.ForeColor = System.Drawing.Color.White;
                _frameLabel.Text      = ((int)(_currentFence / _gametimer.Elapsed.TotalSeconds)).ToString();

                if (_frameLabel.Text == "0")
                {
                    _frameLabel.ForeColor = System.Drawing.Color.Red;
                    _frameLabel.Text      = ((int)(_gametimer.Elapsed.TotalSeconds / _currentFence)).ToString();
                }
            }
        }
        public bool DrawFrame(Action <int, int> draw, [CallerMemberName] string frameName = null)
        {
            if (!this.renderLoop.NextFrame())
            {
                return(false);
            }

            CommandAllocator.Reset();
            bundleAllocator.Reset();

            commandList.Reset(CommandAllocator, null);

            BeginFrame(commandList);

            commandList.SetViewport(viewport);
            commandList.SetScissorRectangles(scissorRect);

            var commandLists = commandListPool.ToArray();

            commandQueue.ExecuteCommandLists(commandLists.Length, commandLists);
            bundlePool.Reset();

            commandList.ResourceBarrierTransition(RenderTarget, ResourceStates.Present, ResourceStates.RenderTarget);

            CpuDescriptorHandle rtvHandle = rtvHeap.CPUDescriptorHandleForHeapStart;

            rtvHandle += CurrentFrameIndex * rtvDescriptorSize;
            commandList.SetRenderTargets(1, rtvHandle, null);

            var clearColor = new RawColor4(0, 0, 0, 0);

            commandList.ClearRenderTargetView(rtvHandle, clearColor, 0, null);

            draw(window.Width, window.Height);

            foreach (var bundle in bundlePool)
            {
                commandList.ExecuteBundle(bundle);
            }

            bundlePool.Reset();

            commandList.ResourceBarrierTransition(RenderTarget, ResourceStates.RenderTarget, ResourceStates.Present);

            commandList.Close();

            commandQueue.ExecuteCommandList(commandList);

            swapChain.Present(1, PresentFlags.None);

            WaitForPrevFrame();

            return(true);
        }
Exemple #4
0
        public SharpDX.Result PresentHook(IntPtr swapChainPtr, int syncInterval, PresentFlags flags)
        {
            if (!init)
            {
                swapChain = SwapChain3.FromPointer <SwapChain3>(swapChainPtr);
                device    = swapChain.GetDevice <D3D12.Device>();

                init = true;
            }

            return(swapChain.Present(syncInterval, flags));
        }
Exemple #5
0
        public void Render()
        {
            //将渲染场景所需的所有命令都记录到命令列表中
            PopulateCommandList();

            //执行命令列表
            commandQueue.ExecuteCommandList(commandList);

            //显示当前帧
            swapChain.Present(1, 0);

            //等待前一帧
            WaitForPreviousFrame();
        }
Exemple #6
0
        /// <summary>
        /// Render scene
        /// </summary>
        public void Render()
        {
            // record all the commands we need to render the scene into the command list
            PopulateCommandLists();

            // execute the command list
            commandQueue.ExecuteCommandList(commandList);

            // swap the back and front buffers
            swapChain.Present(1, 0);

            // wait and reset EVERYTHING
            WaitForPrevFrame();

            RemoveAndDispose(ref renderTarget);
            if (width != newWidth || height != newHeight)
            {
                width  = newWidth;
                height = newHeight;
                swapChain.ResizeBuffers(SwapBufferCount, width, height, Format.Unknown, SwapChainFlags.None);
#if USE_DEPTH
                RemoveAndDispose(ref depthBuffer);
                depthBuffer = Collect(device.CreateCommittedResource(
                                          new HeapProperties(HeapType.Default),
                                          HeapFlags.None,
                                          new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 1, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil),
                                          ResourceStates.Common,
                                          new ClearValue
                {
                    Format       = Format.D32_Float,
                    DepthStencil = new DepthStencilValue
                    {
                        Depth   = 1,
                        Stencil = 0,
                    }
                }));
                device.CreateDepthStencilView(depthBuffer, null, descriptorHeapDS.CPUDescriptorHandleForHeapStart);
#endif
                // Create the viewport
                viewPort = new ViewportF(0, 0, width, height);

                // Create the scissor
                scissorRectangle = new Rectangle(0, 0, width, height);
            }
            renderTarget = Collect(swapChain.GetBackBuffer <Resource>(swapChain.CurrentBackBufferIndex));
            device.CreateRenderTargetView(renderTarget, null, descriptorHeapRT.CPUDescriptorHandleForHeapStart);
        }
        /// <summary>
        /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling (anti-aliasing)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="syncInterval"></param>
        /// <param name="flags"></param>
        /// <returns>The HRESULT of the original method</returns>
        int PresentHook(IntPtr swapChainPtr, int syncInterval, SharpDX.DXGI.PresentFlags flags)
        {
            this.Frame();
            SwapChain3 swapChain = (SharpDX.DXGI.SwapChain3)swapChainPtr;

            //if (!init)
            //{
            //    InitText(swapChain);
            //}

            try
            {
                #region Screenshot Request
                //if (this.Request != null)
                //{
                //    this.DebugMessage("PresentHook: Request Start");
                //    DateTime startTime = DateTime.Now;
                //    using (Texture2D texture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0))
                //    {
                //        #region Determine region to capture
                //        System.Drawing.Rectangle regionToCapture = new System.Drawing.Rectangle(0, 0, texture.Description.Width, texture.Description.Height);

                //        if (this.Request.RegionToCapture.Width > 0)
                //        {
                //            regionToCapture = this.Request.RegionToCapture;
                //        }
                //        #endregion

                //        var theTexture = texture;

                //        // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture
                //        Texture2D textureResolved = null;
                //        if (texture.Description.SampleDescription.Count > 1)
                //        {
                //            this.DebugMessage("PresentHook: resolving multi-sampled texture");
                //            // texture is multi-sampled, lets resolve it down to single sample
                //            textureResolved = new Texture2D(texture.Device, new Texture2DDescription()
                //            {
                //                CpuAccessFlags = CpuAccessFlags.None,
                //                Format = texture.Description.Format,
                //                Height = texture.Description.Height,
                //                Usage = ResourceUsage.Default,
                //                Width = texture.Description.Width,
                //                ArraySize = 1,
                //                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Ensure single sample
                //                BindFlags = BindFlags.None,
                //                MipLevels = 1,
                //                OptionFlags = texture.Description.OptionFlags
                //            });
                //            // Resolve into textureResolved
                //            texture.Device.ImmediateContext.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format);

                //            // Make "theTexture" be the resolved texture
                //            theTexture = textureResolved;
                //        }

                //        // Create destination texture
                //        Texture2D textureDest = new Texture2D(texture.Device, new Texture2DDescription()
                //        {
                //            CpuAccessFlags = CpuAccessFlags.None,// CpuAccessFlags.Write | CpuAccessFlags.Read,
                //            Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG
                //            Height = regionToCapture.Height,
                //            Usage = ResourceUsage.Default,// ResourceUsage.Staging,
                //            Width = regionToCapture.Width,
                //            ArraySize = 1,//texture.Description.ArraySize,
                //            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),// texture.Description.SampleDescription,
                //            BindFlags = BindFlags.None,
                //            MipLevels = 1,//texture.Description.MipLevels,
                //            OptionFlags = texture.Description.OptionFlags
                //        });

                //        // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index
                //        theTexture.Device.ImmediateContext.CopySubresourceRegion(theTexture, 0, new ResourceRegion()
                //        {
                //            Top = regionToCapture.Top,
                //            Bottom = regionToCapture.Bottom,
                //            Left = regionToCapture.Left,
                //            Right = regionToCapture.Right,
                //            Front = 0,
                //            Back = 1 // Must be 1 or only black will be copied
                //        }, textureDest, 0, 0, 0, 0);

                //        // Note: it would be possible to capture multiple frames and process them in a background thread

                //        // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline
                //        Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread
                //        ThreadPool.QueueUserWorkItem(delegate
                //        {
                //            //FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create);
                //            //Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs);

                //            DateTime startCopyToSystemMemory = DateTime.Now;
                //            using (MemoryStream ms = new MemoryStream())
                //            {
                //                Texture2D.ToStream(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Bmp, ms);
                //                ms.Position = 0;
                //                this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString());

                //                DateTime startSendResponse = DateTime.Now;
                //                ProcessCapture(ms, requestId);
                //                this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString());
                //            }

                //            // Free the textureDest as we no longer need it.
                //            textureDest.Dispose();
                //            textureDest = null;
                //            this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString());
                //        });

                //        // Prevent the request from being processed a second time
                //        this.Request = null;

                //        // Make sure we free up the resolved texture if it was created
                //        if (textureResolved != null)
                //        {
                //            textureResolved.Dispose();
                //            textureResolved = null;
                //        }
                //    }
                //    this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString());
                //    this.DebugMessage("PresentHook: Request End");
                //}
                #endregion

                #region Draw overlay (after screenshot so we don't capture overlay as well)
                if (this.Config.ShowOverlay)
                {
                    // Initialise Overlay Engine
                    if (_swapChainPointer != swapChain.NativePointer || _overlayEngine == null)
                    {
                        if (_overlayEngine != null)
                        {
                            _overlayEngine.Dispose();
                        }

                        _overlayEngine = new DX11.DXOverlayEngine();
                        _overlayEngine.Overlays.Add(new Common.Overlay
                        {
                            Elements =
                            {
                                //new Common.TextElement(new System.Drawing.Font("Times New Roman", 22)) { Text = "Test", Location = new System.Drawing.Point(200, 200), Color = System.Drawing.Color.Yellow, AntiAliased = false},
                                new Common.FramesPerSecond(new System.Drawing.Font("Arial",                  12))
                                {
                                    Location = new System.Drawing.Point(5, 5), Color = System.Drawing.Color.Red, AntiAliased = true
                                },
                                //new Common.ProcessLoad(new System.Drawing.Font("Arial", 12)){ Location = new System.Drawing.Point(5,20), Color = System.Drawing.Color.Red, AntiAliased = true },
                                ProcessLoad
                            }
                        });
                        _overlayEngine.Initialise(swapChain);

                        _swapChainPointer = swapChain.NativePointer;
                    }
                    // Draw Overlay(s)
                    else if (_overlayEngine != null)
                    {
                        foreach (var overlay in _overlayEngine.Overlays)
                        {
                            overlay.Frame();
                        }
                        _overlayEngine.Draw();
                    }

                    //direct2DRenderTarget[frameIndex].BeginDraw();
                    //int time = Environment.TickCount % 10000;
                    //int t = time / 2000;
                    //float f = (time - (t * 2000)) / 2000.0F;
                    //textBrush.Color = Color4.Lerp(colors[t], colors[t + 1], f);
                    //direct2DRenderTarget[frameIndex].DrawText("Hello Text", textFormat, new SharpDX.Mathematics.Interop.RawRectangleF((float)Math.Sin(Environment.TickCount / 1000.0F) * 200 + 400, 10, 2000, 500), textBrush);
                    //direct2DRenderTarget[frameIndex].EndDraw();
                }
                #endregion
            }
            catch (Exception e)
            {
                // If there is an error we do not want to crash the hooked application, so swallow the exception
                this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.ToString());
                //return unchecked((int)0x8000FFFF); //E_UNEXPECTED
            }

            // As always we need to call the original method, note that EasyHook has already repatched the original method
            // so calling it here will not cause an endless recursion to this function
            swapChain.Present(syncInterval, flags);
            return(SharpDX.Result.Ok.Code);
        }