Ejemplo n.º 1
0
        protected override void CreateImpl()
        {
            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount       = (int)Desc.BufferCount,
                ModeDescription   = new ModeDescription((int)Desc.Width, (int)Desc.Height, new Rational(0, 0), Memory.Enums.ToDXGIFormat[(int)Desc.Format]),
                Usage             = Usage.RenderTargetOutput,
                SwapEffect        = SwapEffect.FlipDiscard,
                OutputHandle      = Desc.WindowHandle,
                SampleDescription = new SampleDescription
                {
                    Count   = (int)Desc.SampleCount,
                    Quality = (int)Desc.SampleQuality
                },
                IsWindowed = !Desc.Fullscreen
            };

            using (var factory = new Factory4())
            {
                var tempSwapChain = new SharpDX.DXGI.SwapChain(factory, ((CommandQueue)Desc.AssociatedGraphicsQueue).CommandQueueD3D12, swapChainDesc);
                SwapChainDXGI = tempSwapChain.QueryInterface <SwapChain3>();
                tempSwapChain.Dispose();
                CurrentBackBufferIndex = (uint)SwapChainDXGI.CurrentBackBufferIndex;
            }

            SwapChainDXGI.DebugName = Label;

            Log.Info("Created SwapChain");
        }
Ejemplo n.º 2
0
        protected override void CreateImpl()
        {
            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount = (int)Desc.BufferCount,
                ModeDescription = new ModeDescription((int) Desc.Width, (int)Desc.Height, new Rational(0,0), Memory.Enums.ToDXGIFormat[(int)Desc.Format]),
                Usage = Usage.RenderTargetOutput,
                SwapEffect = SwapEffect.FlipDiscard,
                OutputHandle = Desc.WindowHandle,
                SampleDescription = new SampleDescription
                {
                    Count = (int) Desc.SampleCount,
                    Quality = (int) Desc.SampleQuality
                },
                IsWindowed = !Desc.Fullscreen
            };
            using (var factory = new Factory4())
            {
                var tempSwapChain = new SharpDX.DXGI.SwapChain(factory, ((CommandQueue)Desc.AssociatedGraphicsQueue).CommandQueueD3D12, swapChainDesc);
                SwapChainDXGI = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                CurrentBackBufferIndex = (uint)SwapChainDXGI.CurrentBackBufferIndex;
            }

            SwapChainDXGI.DebugName = Label;

            Log.Info("Created SwapChain");
        }
Ejemplo n.º 3
0
        public D3DApp(IntPtr handleIntPtr)
        {
            this.handleIntPtr = handleIntPtr;

            this.m4XMsaaState     = false;
            this.swapChainBuffers = new Resource[SwapChainBufferCount];
            this.frameResources   = new List <FrameResource>(NumFrameResources);
            this.fenceEvents      = new List <AutoResetEvent>(NumFrameResources);
            this.mainPassCb       = PassConstants.Default;
            this.meshes           = new List <Mesh>();

            this.InitDirect3D();

            this.commandObjects        = new CommandObjects(device);
            this.swapChain             = SwapChainObject.New(this.handleIntPtr, this.factory, this.commandObjects.GetCommandQueue, BackBufferFormat, SwapChainBufferCount, MsaaCount, MsaaQuality);
            this.descriptorHeapObjects = new DescriptorHeapObjects(device, SwapChainBufferCount, 1);
            this.rootSignature         = RootSignatureObject.New(device);

            this.BuildMesh();
            this.BuildFrameResources();
            this.BuildConstantBuffers();
            this.pso = PipelinesStateObject.New(device, rootSignature, MsaaCount, MsaaQuality, DepthStencilFormat, BackBufferFormat);

            this.FlushCommandQueue();

            this.camera = new OrbitCamera();
        }
Ejemplo n.º 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));
        }
 public static DescriptorHeap CreateRenderTargetViewHeap(Config config, SwapChain3 swapchain, out Resource[] renderTargets)
 {
     var Heap = Engine.Instance.Core.Device.CreateDescriptorHeap(new DescriptorHeapDescription()
     {
         DescriptorCount = config.FrameCount,
         Flags = DescriptorHeapFlags.None,
         Type = DescriptorHeapType.RenderTargetView
     });
     renderTargets = new Resource[config.FrameCount];
     int Step = Engine.Instance.Core.Device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
     for (int n = 0; n < config.FrameCount; n++)
     {
         renderTargets[n] = swapchain.GetBackBuffer<Resource>(n);
         Engine.Instance.Core.Device.CreateRenderTargetView(renderTargets[n], null, Heap.CPUDescriptorHandleForHeapStart + n* Step);
     }
     return Heap;
 }
        public static DescriptorHeap CreateRenderTargetViewHeap(Config config, SwapChain3 swapchain, out Resource[] renderTargets)
        {
            var Heap = Engine.Instance.Core.Device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = config.FrameCount,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            });

            renderTargets = new Resource[config.FrameCount];
            int Step = Engine.Instance.Core.Device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            for (int n = 0; n < config.FrameCount; n++)
            {
                renderTargets[n] = swapchain.GetBackBuffer <Resource>(n);
                Engine.Instance.Core.Device.CreateRenderTargetView(renderTargets[n], null, Heap.CPUDescriptorHandleForHeapStart + n * Step);
            }
            return(Heap);
        }
Ejemplo n.º 7
0
        public void Resize(System.Drawing.Size size)
        {
            Size = size;
            foreach (var renderTarget in RenderTargets)
            {
                renderTarget.Dispose();
            }
            SwapChain3.ResizeBuffers(FrameCount, size.Width, size.Height, SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.DXGI.SwapChainFlags.AllowModeSwitch);
            FrameIndex = SwapChain3.CurrentBackBufferIndex;
            var rtvHandle = RenderTargetViewHeap.CPUDescriptorHandleForHeapStart;

            for (int i = 0; i < FrameCount; i++)
            {
                RenderTargets[i] = SwapChain3.GetBackBuffer <SharpDX.Direct3D12.Resource>(i);
                D3D12Device.CreateRenderTargetView(RenderTargets[i], null, rtvHandle);
                rtvHandle     += RtvDescriptorSize;
                FenceValues[i] = FenceValues[FrameIndex];
            }
        }
Ejemplo n.º 8
0
        public DX12SwapChain(DX12GraphicsDevice graphicsDevice, SwapChainInfo swapChainInfo)
        {
            _factory = new DXGIFactory();

            var swapChainDescription = new SwapChainDescription
            {
                SwapEffect        = swapChainInfo.SwapEffect.ToSharpDX(),
                BufferCount       = 2,
                Flags             = SwapChainFlags.None,
                IsWindowed        = swapChainInfo.IsWindowed,
                ModeDescription   = new ModeDescription(swapChainInfo.Width, swapChainInfo.Height, new Rational(60, 1), Format.R8G8B8A8UNorm.ToSharpDX()),
                OutputHandle      = swapChainInfo.WindowHandle,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput
            };

            using var tempSwapChain = new SwapChain(_factory, graphicsDevice, swapChainDescription);
            _swapChain = tempSwapChain.QueryInterface <SwapChain3>();

            TextureView = new D3D12TextureView(graphicsDevice, 1, DescriptorHeapFlags.ShaderVisible, DescriptorHeapType.RenderTargetView);
        }
Ejemplo n.º 9
0
        public SwapChain(
            GraphicsDevice graphicsDevice,
            IntPtr windowHandle,
            int backBufferCount,
            int width,
            int height)
        {
            _graphicsDevice  = graphicsDevice;
            _backBufferCount = backBufferCount;

            DeviceSwapChain = AddDisposable(CreateSwapChain(
                                                windowHandle,
                                                _graphicsDevice.CommandQueue.DeviceCommandQueue,
                                                _graphicsDevice.BackBufferFormat,
                                                backBufferCount,
                                                width,
                                                height));

            _renderTargets = new D3D12.Resource[backBufferCount];

            _descriptorHeap = AddDisposable(_graphicsDevice.Device.CreateDescriptorHeap(new DescriptorHeapDescription
            {
                DescriptorCount = backBufferCount,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            }));

            _descriptorSize = _graphicsDevice.Device.GetDescriptorHandleIncrementSize(
                DescriptorHeapType.RenderTargetView);

            _fence = AddDisposable(_graphicsDevice.Device.CreateFence(0, FenceFlags.None));

            _fenceValues = new int[backBufferCount];
            _fenceValues[_frameIndex]++;

            _fenceEvent = AddDisposable(new AutoResetEvent(false));

            Resize(width, height);
        }
Ejemplo n.º 10
0
        void InitText(SwapChain3 tempSwapChain)
        {
            init       = true;
            device     = tempSwapChain.GetDevice <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();
            var texture2d = tempSwapChain.GetBackBuffer <Texture2D>(0);

            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            SharpDX.Direct2D1.BitmapProperties1 properties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                                  SharpDX.Direct2D1.AlphaMode.Premultiplied),
                96, 96, SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            Surface backBuffer = tempSwapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new SharpDX.Direct2D1.Bitmap1(d2dContext, new Size2(800, 600), properties);

            solidBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.Coral);

            // Create a linear gradient brush.
            // Note that the StartPoint and EndPoint values are set as absolute coordinates of the surface you are drawing to,
            // NOT the geometry we will apply the brush.
            linearGradientBrush = new SharpDX.Direct2D1.LinearGradientBrush(d2dContext, new SharpDX.Direct2D1.LinearGradientBrushProperties()
            {
                StartPoint = new Vector2(50, 0),
                EndPoint   = new Vector2(450, 0),
            },
                                                                            new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[]
            {
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Blue,
                    Position = 0,
                },
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Green,
                    Position = 1,
                }
            }));

            SharpDX.Direct2D1.RadialGradientBrushProperties rgb = new SharpDX.Direct2D1.RadialGradientBrushProperties()
            {
                Center  = new Vector2(250, 525),
                RadiusX = 100,
                RadiusY = 100,
            };
            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new SharpDX.Direct2D1.RadialGradientBrush(d2dContext, ref rgb
                                                                            ,
                                                                            new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[]
            {
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Yellow,
                    Position = 0,
                },
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Red,
                    Position = 1,
                }
            }));
        }
Ejemplo n.º 11
0
        private void CreateWindowResources()
        {
            // Wait until all previous GPU work is complete.
            WaitForGPU();

            // Clear the previous window size specific content.
            for (int i = 0; i < FrameCount; i++)
            {
                renderTargets[i] = null;
            }

            // Calculate the necessary render target size in pixels.
            var outputSize = new Size2();

            outputSize.Width  = window.ClientSize.Width;
            outputSize.Height = window.ClientSize.Height;

            // Prevent zero size DirectX content from being created.
            outputSize.Width  = Math.Max(outputSize.Width, 640);
            outputSize.Height = Math.Max(outputSize.Width, 480);

            if (swapChain != null)
            {
                // If the swap chain already exists, resize it.
                swapChain.ResizeBuffers(FrameCount, outputSize.Width, outputSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);

                if (!DXDebug.ValidateDevice(device))
                {
                    throw new ArgumentNullException(nameof(device));
                }
            }
            else
            {
                using (var factory = new Factory4())
                {
                    // Otherwise, create a new one using the same adapter as the existing Direct3D device.
                    SwapChainDescription swapChainDesc = new SwapChainDescription()
                    {
                        BufferCount       = FrameCount,
                        ModeDescription   = new ModeDescription(outputSize.Width, outputSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                        Usage             = Usage.RenderTargetOutput,
                        SwapEffect        = SwapEffect.FlipDiscard,
                        OutputHandle      = window.Handle,
                        SampleDescription = new SampleDescription(1, 0),
                        IsWindowed        = true,
                    };

                    var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                    swapChain           = tempSwapChain.QueryInterface <SwapChain3>();
                    swapChain.DebugName = "SwapChain";
                    tempSwapChain.Dispose();
                }
            }

            // Create a render target view of the swap chain back buffer.
            var descriptorHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Type            = DescriptorHeapType.RenderTargetView,
                Flags           = DescriptorHeapFlags.None
            };

            rtvHeap      = device.CreateDescriptorHeap(descriptorHeapDesc);
            rtvHeap.Name = "Render Target View Descriptor Heap";

            // All pending GPU work was already finished. Update the tracked fence values
            // to the last value signaled.
            for (int i = 0; i < FrameCount; i++)
            {
                fenceValues[i] = fenceValues[currentFrame];
            }

            currentFrame = 0;
            var rtvDescriptor = rtvHeap.CPUDescriptorHandleForHeapStart;

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
            for (int i = 0; i < FrameCount; i++)
            {
                renderTargets[i] = swapChain.GetBackBuffer <Resource>(i);
                device.CreateRenderTargetView(renderTargets[i], null, rtvDescriptor + (rtvDescriptorSize * i));

                renderTargets[i].Name = $"Render Target {i}";
            }

            viewport          = new ViewportF();
            viewport.Width    = outputSize.Width;
            viewport.Height   = outputSize.Height;
            viewport.MaxDepth = 1.0f;

            scissorRect        = new Rectangle();
            scissorRect.Right  = outputSize.Width;
            scissorRect.Bottom = outputSize.Height;
        }
Ejemplo n.º 12
0
        //创建设备
        private void LoadPipeline(SharpDX.Windows.RenderForm form)
        {
            width  = form.ClientSize.Width;
            height = form.ClientSize.Height;

            //创建视口
            viewPort = new ViewportF(0, 0, width, height);

            //创建裁剪矩形
            scissorRectangle = new Rectangle(0, 0, width, height);

#if DEBUG
            //启用调试层
            {
                DebugInterface.Get().EnableDebugLayer();
            }
#endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            //工厂化
            using (var factory = new Factory4())
            {
                //创建命令队列
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                //创建交换链
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount     = FrameCount,
                    ModeDescription = new ModeDescription(
                        width, height,                               //缓存大小,一般与窗口大小相同
                        new Rational(60, 1),                         //刷新率,60hz
                        Format.R8G8B8A8_UNorm),                      //像素格式,8位RGBA格式
                    Usage             = Usage.RenderTargetOutput,    //CPU访问缓冲权限
                    SwapEffect        = SwapEffect.FlipDiscard,      //描述处理曲面后的缓冲区内容
                    OutputHandle      = form.Handle,                 //获取渲染窗口句柄
                    Flags             = SwapChainFlags.None,         //描述交换链的行为
                    SampleDescription = new SampleDescription(1, 0), //一重采样
                    IsWindowed        = true                         //true为窗口显示,false为全屏显示
                };

                //创建交换链
                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface <SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;//获取交换链的当前缓冲区的索引
            }

            //创建描述符堆
            //创建一个渲染目标视图(RTV)的描述符堆
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,                         //堆中的描述符数
                Flags           = DescriptorHeapFlags.None,           //结果值指定符堆,None表示堆的默认用法
                Type            = DescriptorHeapType.RenderTargetView //堆中的描述符类型
            };
            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            //获取给定类型的描述符堆的句柄增量的大小,将句柄按正确的数量递增到描述符数组中
            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            //创建一个CBV的描述符堆
            var cbvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };
            constantBufferViewHeap = device.CreateDescriptorHeap(cbvHeapDesc);
            //创建一个SRV的描述符堆
            var srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };
            shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc);
            srvDescriptorSize    = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            //构建资源描述符来填充描述符堆
            //获取指向描述符堆起始处的指针
            CpuDescriptorHandle srvHandle = shaderRenderViewHeap.CPUDescriptorHandleForHeapStart;

            //创建渲染目标视图
            //获取堆中起始的CPU描述符句柄,for循环为交换链中的每一个缓冲区都创建了一个RTV(渲染目标视图)
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                //获得交换链的第n个缓冲区
                renderTargets[n] = swapChain.GetBackBuffer <Resource>(n);
                device.CreateRenderTargetView(
                    renderTargets[n], //指向渲染目标对象的指针
                    null,             //指向描述渲染目标视图结构的指针
                    rtvHandle);       //CPU描述符句柄,表示渲染目标视图的堆的开始
                rtvHandle += rtvDescriptorSize;
            }

            //创建命令分配器对象
            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
            bundleAllocator  = device.CreateCommandAllocator(CommandListType.Bundle);
        }
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);

            using (var factory = new Factory4())
            {
                var queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                var swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                frameIndex = swapChain.CurrentBackBufferIndex;

            }

            var rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);
            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            var srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 200,
                Flags = DescriptorHeapFlags.ShaderVisible,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc);

            var terrainHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 2,
                Flags = DescriptorHeapFlags.ShaderVisible,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            terrainHeap = device.CreateDescriptorHeap(terrainHeapDesc);

            var meshCtrCbvDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags = DescriptorHeapFlags.ShaderVisible,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            meshCtrBufferViewHeap = device.CreateDescriptorHeap(meshCtrCbvDesc);

            var rtcHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtcHandle);
                rtcHandle += rtvDescriptorSize;
            }

            var svHeapDesc = new DescriptorHeapDescription()
            {
                Type = DescriptorHeapType.Sampler,
                DescriptorCount = 1,
                Flags = DescriptorHeapFlags.ShaderVisible,
                NodeMask = 0
            };
            samplerViewHeap = device.CreateDescriptorHeap(svHeapDesc);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
        }
        private void LoadPipeline(RenderForm form)
        {
            int width  = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width    = width;
            viewport.Height   = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right  = width;
            scissorRect.Bottom = height;

            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);

            using (var factory = new Factory4())
            {
                var queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                var swapChainDesc = new SwapChainDescription()
                {
                    BufferCount       = FrameCount,
                    ModeDescription   = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage             = Usage.RenderTargetOutput,
                    SwapEffect        = SwapEffect.FlipDiscard,
                    OutputHandle      = form.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = true
                };

                var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain  = tempSwapChain.QueryInterface <SwapChain3>();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            var rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);
            rtvDescriptorSize    = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            var srvCbvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            srvCbvHeap = device.CreateDescriptorHeap(srvCbvHeapDesc);

            var rtcHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;

            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer <Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtcHandle);
                rtcHandle += rtvDescriptorSize;
            }

            var svHeapDesc = new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.Sampler,
                DescriptorCount = 10,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                NodeMask        = 0
            };

            samplerViewHeap = device.CreateDescriptorHeap(svHeapDesc);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
        }
Ejemplo n.º 15
0
        /// <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);
        }
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }

            //create depth buffer;
            DescriptorHeapDescription dsvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.DepthStencilView
            };
            depthStencilViewHeap = device.CreateDescriptorHeap(dsvHeapDesc);
            CpuDescriptorHandle dsvHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart;

            ClearValue depthOptimizedClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue() { Depth = 1.0F, Stencil = 0 },
            };

            depthTarget = device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil),
                ResourceStates.DepthWrite, depthOptimizedClearValue);

            var depthView = new DepthStencilViewDescription()
            {
                Format = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                Flags = DepthStencilViewFlags.None,
            };

            //bind depth buffer
            device.CreateDepthStencilView(depthTarget, null, dsvHandle);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
            bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle);
        }
Ejemplo n.º 17
0
        public RenderToHandleDeviceProxy(Adapter adapter, IntPtr handle, GraphicSurfaceSize size)
        {
            var backBufferDesc = new ModeDescription(size.Width, size.Height, new Rational(60, 1), GraphicsDevice.BackBufferTextureFormat);

            // Descriptor for the swap chain
            var swapChainDesc = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                BufferCount       = 2,
                IsWindowed        = true,
                OutputHandle      = handle,
                Usage             = Usage.RenderTargetOutput,
                Flags             = SwapChainFlags.None,
                // SwapEffect = SwapEffect.FlipSequential
            };
            // Create device and swap chain
            var flags = DeviceCreationFlags.None;

#if DEBUG
            //flags |= DeviceCreationFlags.Debug;
#endif
            if (SharpDX.Direct3D11.Device.IsSupportedFeatureLevel(adapter, FeatureLevel.Level_11_1))   //update win->dxdiag
                                                                                                       //flags |= DeviceCreationFlags.Debuggable;
            {
            }
            if (SharpDX.Direct3D11.Device.IsSupportedFeatureLevel(adapter, FeatureLevel.Level_12_0))
            {
            }

            //using (var factory = adapter.GetParent<Factory2>()) {
            //    var device11 = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None,
            //       new[] {
            //               FeatureLevel.Level_12_1,
            //               FeatureLevel.Level_12_0,
            //               FeatureLevel.Level_11_1,
            //               FeatureLevel.Level_11_0,
            //       });
            //    var desc1 = new SwapChainDescription1() {
            //        Width = width,
            //        Height = height,
            //        Format = BackBufferTextureFormat,
            //        Stereo = false,
            //        SampleDescription = new SampleDescription(1, 0),
            //        Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
            //        BufferCount = 1,
            //        Scaling = Scaling.Stretch,
            //        SwapEffect = SwapEffect.Discard,

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

            SharpDX.Direct3D11.Device.CreateWithSwapChain(adapter, flags, swapChainDesc, out var d3dDevice, out var sch);

            var wc = sch.QueryInterfaceOrNull <SwapChain1>();
            if (wc != null)
            {
                swapChain1 = wc;
            }
            var sc3 = sch.QueryInterfaceOrNull <SwapChain3>();
            if (sc3 != null)
            {
                swapChain3 = sc3;
            }

            swapChain = sch;                                                        //.QueryInterface<SwapChain4>();//

            var d3 = d3dDevice.QueryInterfaceOrNull <SharpDX.Direct3D11.Device3>(); //Device5
            if (d3 != null)
            {
                device3 = d3;
            }
            D3DDevice = d3dDevice;

            ImmediateContext = d3dDevice.ImmediateContext;

            // Enable object tracking
            //SharpDX.Configuration.EnableObjectTracking = true;
        }
Ejemplo n.º 18
0
        private List<IntPtr> GetProcAddress()
        {
            var address = new List<IntPtr>();

            _device12 = new SharpDX.Direct3D12.Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var renderForm = new Form())
            {
                using (var factory = new SharpDX.DXGI.Factory4())
                {
                    _commandQueue
                        = _device12.CreateCommandQueue(new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct));

                    _commandAllocator
                        = _device12.CreateCommandAllocator(CommandListType.Direct);

                    _commandList
                        = _device12.CreateCommandList(CommandListType.Direct, _commandAllocator, null);

                    var swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                    {
                        BufferCount = 2,
                        ModeDescription = new SharpDX.DXGI.ModeDescription(100, 100, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                        Usage = SharpDX.DXGI.Usage.RenderTargetOutput,
                        SwapEffect = SharpDX.DXGI.SwapEffect.FlipDiscard,
                        OutputHandle = renderForm.Handle,
                        Flags = SwapChainFlags.AllowModeSwitch,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        IsWindowed = true
                    };

                    var tempSwapChain = new SharpDX.DXGI.SwapChain(factory, _commandQueue, swapChainDesc);
                    _swapChain = tempSwapChain.QueryInterface<SharpDX.DXGI.SwapChain3>();
                    tempSwapChain.Dispose();
                }

                if (_device12 != null && _swapChain != null)
                {
                    address.AddRange(GetVTblAddresses(_device12.NativePointer, 44));
                    address.AddRange(GetVTblAddresses(_commandQueue.NativePointer, 19));
                    address.AddRange(GetVTblAddresses(_commandAllocator.NativePointer, 9));
                    address.AddRange(GetVTblAddresses(_commandList.NativePointer, 60));
                    address.AddRange(GetVTblAddresses(_swapChain.NativePointer, 18));

                    _device12.Dispose();
                    _device12 = null;

                    _commandQueue.Dispose();
                    _commandQueue = null;

                    _commandAllocator.Dispose();
                    _commandAllocator = null;

                    _commandList.Dispose();
                    _commandList = null;

                    _swapChain.Dispose();
                    _swapChain = null;
                }
            }

            return address;
        }
Ejemplo n.º 19
0
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_12_0);
            using (var factory = new Factory4())
            {

                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            //Init Direct3D11 device from Direct3D12 device
            device11 = SharpDX.Direct3D11.Device.CreateFromDirect3D12(device, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, commandQueue);
            deviceContext11 = device11.ImmediateContext;
            device11on12 = device11.QueryInterface<SharpDX.Direct3D11.ID3D11On12Device>();
            var d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.MultiThreaded);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;

                //init Direct2D surfaces
                SharpDX.Direct3D11.D3D11ResourceFlags format = new SharpDX.Direct3D11.D3D11ResourceFlags()
                {
                    BindFlags = (int)SharpDX.Direct3D11.BindFlags.RenderTarget,
                    CPUAccessFlags = (int)SharpDX.Direct3D11.CpuAccessFlags.None
                };

                device11on12.CreateWrappedResource(
                    renderTargets[n], format,
                    (int)ResourceStates.Present,
                    (int)ResourceStates.RenderTarget,
                    typeof(SharpDX.Direct3D11.Resource).GUID,
                    out wrappedBackBuffers[n]);

                //Init direct2D surface
                var d2dSurface = wrappedBackBuffers[n].QueryInterface<Surface>();
                direct2DRenderTarget[n] = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
                d2dSurface.Dispose();
            }

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);

            d2dFactory.Dispose();

            //Init font
            var directWriteFactory = new SharpDX.DirectWrite.Factory();
            textFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near };
            textBrush = new SharpDX.Direct2D1.SolidColorBrush(direct2DRenderTarget[0], Color.White);
            directWriteFactory.Dispose();
        }
Ejemplo n.º 20
0
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            renderTargetViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            });
            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            //create depth buffer;
            depthStencilViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.DepthStencilView
            });

            //constant buffer view heap
            constantBufferViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = 100,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags = DescriptorHeapFlags.ShaderVisible
            });

            //Create targets
            CreateTargets(width, height);

            //sampler buffer view heap
            samplerViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = 10,
                Type = DescriptorHeapType.Sampler,
                Flags = DescriptorHeapFlags.ShaderVisible
            });

            //bind sampler
            device.CreateSampler(new SamplerStateDescription()
            {
                Filter = Filter.ComparisonMinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                MinimumLod = float.MinValue,
                MaximumLod = float.MaxValue,
                MipLodBias = 0,
                MaximumAnisotropy = 0,
                ComparisonFunction = Comparison.Never
            }, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
            bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle);

            form.UserResized += (sender, e) =>
             {
                 isResizing = true;
             };
        }
Ejemplo n.º 21
0
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags = DescriptorHeapFlags.ShaderVisible,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
        }
Ejemplo n.º 22
0
        void loadDevice()
        {
            _resources = new GraphicsResource[0];

            _viewport.Width    = WIDTH;
            _viewport.Height   = HEIGHT;
            _viewport.MaxDepth = 1.0f;

            _scissorRect.Right  = WIDTH;
            _scissorRect.Bottom = HEIGHT;

#if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
#endif

            using (var factory = new Factory4())
            {
                _device = new Device(factory.GetAdapter(_adapterIndex), SharpDX.Direct3D.FeatureLevel.Level_12_1).QueryInterface <Device3>();
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                _graphicsQueue = _device.CreateCommandQueue(queueDesc);


                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount       = FRAME_COUNT,
                    ModeDescription   = new ModeDescription(WIDTH, HEIGHT, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage             = Usage.RenderTargetOutput,
                    SwapEffect        = SwapEffect.FlipDiscard,
                    OutputHandle      = _window.Handle,
                    Flags             = SwapChainFlags.AllowModeSwitch,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, _graphicsQueue, swapChainDesc);
                _swapChain = tempSwapChain.QueryInterface <SwapChain3>();
                tempSwapChain.Dispose();
                _frameIndex = _swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FRAME_COUNT,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            };

            _renderTargetViewHeap = _device.CreateDescriptorHeap(rtvHeapDesc);

            DescriptorHeapDescription _dsvHeapDescription = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.None,
                NodeMask        = 0,
                Type            = DescriptorHeapType.DepthStencilView
            };
            _depthStencilView = _device.CreateDescriptorHeap(_dsvHeapDescription);

            _rtvDescriptorSize = _device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = _renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FRAME_COUNT; n++)
            {
                _renderTargets[n] = _swapChain.GetBackBuffer <Resource>(n);
                _device.CreateRenderTargetView(_renderTargets[n], null, rtvHandle);
                rtvHandle += _rtvDescriptorSize;
            }

            //Initialize Depth/Stencil Buffer
            _depthStencilDesc = new ResourceDescription(ResourceDimension.Texture2D, 0,
                                                        _window.Width, _window.Height, 1, 1, Format.D24_UNorm_S8_UInt, 1, 0,
                                                        TextureLayout.Unknown, ResourceFlags.AllowDepthStencil);
            _depthStencilClear = new ClearValue()
            {
                DepthStencil = new DepthStencilValue()
                {
                    Depth   = 1.0f,
                    Stencil = 0
                },
                Format = Format.D24_UNorm_S8_UInt
            };
            _depthStencilBuffer = _device.CreateCommittedResource(new HeapProperties(HeapType.Default),
                                                                  HeapFlags.None, _depthStencilDesc, ResourceStates.Common, _depthStencilClear);

            //Create Descriptor to mip level 0 of the entire resource using format of the resouce
            _device.CreateDepthStencilView(_depthStencilBuffer, null, DepthStencilHandle);

            _commandAllocator       = _device.CreateCommandAllocator(CommandListType.Direct);
            _bundleCommandAllocator = _device.CreateCommandAllocator(CommandListType.Bundle);

            // Create the command list.
            _commandList       = _device.CreateCommandList(CommandListType.Direct, _commandAllocator, null);
            _bundleCommandList = _device.CreateCommandList(CommandListType.Bundle, _bundleCommandAllocator, null);

            _commandList.ResourceBarrier(new ResourceBarrier(new ResourceTransitionBarrier(_depthStencilBuffer,
                                                                                           ResourceStates.Common, ResourceStates.DepthWrite)));

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            _bundleCommandList.Close();
        }