Example #1
0
        public ScreenContext(Control owner, 行列管理 manager)
            : base()
        {
            // SwapChain の生成
            var d3ddevice  = RenderContext.Instance.DeviceManager.D3DDevice;
            var sampleDesc = new SampleDescription(1, 0);

            this.SwapChain = new SwapChain(RenderContext.Instance.DeviceManager.DXGIFactory, d3ddevice, getSwapChainDescription(owner, sampleDesc));

            //ラスタライザの設定

            //深度ステンシルバッファの初期化
            using (var depthBuffer = new Texture2D(d3ddevice, getDepthBufferTexture2DDescription(owner, sampleDesc)))
            {
                this.深度ステンシルビュー = new DepthStencilView(d3ddevice, depthBuffer);
            }
            //レンダーターゲットの初期化
            using (Texture2D renderTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0))
            {
                this.D3Dレンダーターゲットビュー = new RenderTargetView(d3ddevice, renderTexture);
            }

            // その他

            this.ワールド空間        = new ワールド空間();
            this.BindedControl = owner;
            this.行列管理          = manager;
            this.パネル監視         = new マウス監視(owner);
            this.ビューポートを設定する();
        }
Example #2
0
 private void CreateRenderTargetView()
 {
     using (var backBuffer = Resource.FromSwapChain <Texture2D>(_swapChain, 0))
     {
         _renderTargetView = new RenderTargetView(Device, backBuffer);
     }
 }
Example #3
0
        public BackBuffer(Factory2 factory, Device1 device1, RenderForm renderForm)
        {
            swapChainDescription1 = new SwapChainDescription1()
            {
                Width             = renderForm.ClientSize.Width,
                Height            = renderForm.ClientSize.Height,
                Format            = Format.R8G8B8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(4, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                SwapEffect        = SwapEffect.Discard,
                Flags             = SwapChainFlags.AllowModeSwitch,
            };

            SwapChain = new SwapChain1(factory,
                                       device1,
                                       renderForm.Handle,
                                       ref swapChainDescription1,
                                       new SwapChainFullScreenDescription()
            {
                RefreshRate = new Rational(60, 1),
                Scaling     = DisplayModeScaling.Centered,
                Windowed    = true
            }, null);

            BackBufferTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
        }
 private void ResetDeviceToNewViewportSize(Size newSizeInPixel)
 {
     ResizeBackBufferIfItExistedBefore();
     backBuffer     = Resource.FromSwapChain <Texture2D>(swapChain, 0);
     backBufferView = new RenderTargetView(nativeDevice, backBuffer);
     surface        = backBuffer.QueryInterface <Surface>();
 }
Example #5
0
        /// <summary>
        /// Create required DirectX resources.
        /// Derived calls should begin with base.InternalInitialize()
        /// </summary>
        protected virtual void InternalInitialize()
        {
            var dpiScale = GetDpiScale();

            SurfaceWidth  = (int)(ActualWidth < 0 ? 0 : Math.Ceiling(ActualWidth * dpiScale));
            SurfaceHeight = (int)(ActualHeight < 0 ? 0 : Math.Ceiling(ActualHeight * dpiScale));

            var swapChainDescription = new SwapChainDescription
            {
                OutputHandle      = Hwnd,
                BufferCount       = 1,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(SurfaceWidth, SurfaceHeight, new Rational(60, 1), Format.B8G8R8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput | Usage.Shared
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, swapChainDescription, out _device, out _swapChain);

            // Ignore all windows events
            using (var factory = _swapChain.GetParent <Factory>())
            {
                factory.MakeWindowAssociation(Hwnd, WindowAssociationFlags.IgnoreAll);
            }

            // New RenderTargetView from the backbuffer
            _backBuffer       = Resource.FromSwapChain <Texture2D>(_swapChain, 0);
            _renderTargetView = new RenderTargetView(_device, _backBuffer);
        }
        public void CreateDevice(object hostControl, DeviceCreationFlags flags)
        {
            OnDeviceChangeBegin(this, EventArgs.Empty);
            // SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new ModeDescription(PreferredBackBufferWidth, PreferredBackBufferHeight, new Rational(60, 1),
                                                      PreferredBackBufferFormat),
                IsWindowed        = true,
                OutputHandle      = (IntPtr)hostControl,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            IsDebugMode = flags.HasFlag(DeviceCreationFlags.Debug);
            var device = ToDispose(new Device(DriverType.Hardware, flags, PreferredGraphicsProfile[0]));

            this.device = ToDispose(device.QueryInterface <Device1>());

            var factory = ToDispose(new Factory1());

            swapChain = ToDispose(new SwapChain(factory, device, desc));
            factory.MakeWindowAssociation(swapChain.Description.OutputHandle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            backBuffer       = ToDispose(Resource.FromSwapChain <Texture2D>(swapChain, 0));
            renderTargetView = ToDispose(new RenderTargetView(device, backBuffer));
            context          = ToDispose(this.device.ImmediateContext.QueryInterface <DeviceContext1>());
            OnDeviceCreated(this, EventArgs.Empty);
            OnDeviceChangeEnd(this, EventArgs.Empty);
        }
Example #7
0
        /// <summary>
        /// Rebuilds the swap chain and render targets.
        /// </summary>
        protected void UpdatePresenter()
        {
            PresenterReady = false;

            // release our buffers since we are updating the swap chain
            RenderTarget2D.Dispose();
            DxgiSurface.Dispose();
            RenderTargetView.Dispose();
            _backBuffer.Dispose();

            // resize swapchain
            _swapChain.ResizeBuffers(1, Size.Width, Size.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);

            // recreate the buffers
            _backBuffer                  = Resource.FromSwapChain <Texture2D>(_swapChain, 0);
            RenderTargetView             = new RenderTargetView(_device, _backBuffer);
            DxgiSurface                  = _backBuffer.QueryInterface <Surface>();
            RenderTarget2D               = new RenderTarget(Factory2D, DxgiSurface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            RenderTarget2D.AntialiasMode = AntialiasMode;
            PresenterReady               = true;

            Brushes.Cleanup();
            Fonts.Cleanup();
            IsDirty = true;
            foreach (IRenderComponent component in Layers)
            {
                component.PresenterReset();
            }
        }
Example #8
0
        protected override void Initialize(Configuration configuration)
        {
            var desc = new SwapChainDescription
            {
                BufferCount = 1,
                //ModeDescription = new ModeDescription(configuration.Width, configuration.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = DisplayHandle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput | Usage.ShaderInput,
                Flags             = SwapChainFlags.None
            };

            //SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new[] { FeatureLevel.Level_10_0 }, desc, out _device, out _swapChain);
            // above line is expanded to...
            Device = new Device(
                DriverType.Hardware,
                DeviceCreationFlags.BgraSupport
#if DEBUG
                //| DeviceCreationFlags.Debug
#endif
                ,
                FeatureLevel.Level_10_0);
            using (Factory1 factory1 = new Factory1())
                SwapChain = new SwapChain(factory1, Device, desc);
            // ...this!

            var factory = SwapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll);

            BackBuffer = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
            RenderView = new RenderTargetView(Device, BackBuffer);
        }
Example #9
0
        public void InitRendering()
        {
            try
            {
                lock (_drawLock)
                {
                    m_Ready      = false;
                    ResizeRedraw = true;
                    var desc = new SwapChainDescription
                    {
                        BufferCount     = 2,
                        ModeDescription = new ModeDescription(ClientSize.Width, ClientSize.Height, new Rational(60, 1),
                                                              Format.R8G8B8A8_UNorm),
                        IsWindowed        = true,
                        OutputHandle      = Handle,
                        SampleDescription = new SampleDescription(1, 0),
                        SwapEffect        = SwapEffect.Discard,
                        Usage             = Usage.RenderTargetOutput | Usage.Shared
                    };

                    Device.CreateWithSwapChain(DriverType.Hardware,
                                               DeviceCreationFlags.BgraSupport,
                                               new[] { SharpDX.Direct3D.FeatureLevel.Level_9_3 },
                                               desc,
                                               out device,
                                               out swapChain);

                    var d2dFactory = new SharpDX.Direct2D1.Factory();

                    Factory factory = swapChain.GetParent <Factory>();
                    factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAll);

                    Texture2D backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);

                    surface = backBuffer.QueryInterface <Surface>();

                    d2dRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, surface,
                                                                         new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));


                    var bitmapProperties = new BitmapProperties(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Ignore));

                    clientArea = new RawRectangleF
                    {
                        Left   = 0,
                        Top    = 0,
                        Bottom = ClientSize.Height,
                        Right  = ClientSize.Width
                    };

                    factory.Dispose();
                    backBuffer.Dispose();
                    m_Ready = true;
                }
            }
            catch (Exception ee)
            {
            }
        }
Example #10
0
        public MainWindow() : base("Heat Simulator")
        {
            ClientSize  = new Size(400, 400);
            MouseClick += MainWindow_MouseClick;
            MouseMove  += MainWindow_MouseMove;
            MaximizeBox = false;
            KeyPreview  = true;
            KeyPress   += MainWindow_KeyPress;

            var desc = new SwapChainDescription {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(Width, Height, new Rational(60, 1), Format.B8G8R8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport,
                                       new[] { FeatureLevel.Level_12_0, FeatureLevel.Level_11_0 }, desc, out device, out swapChain);

            factory = swapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAll);
            backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            renderView = new RenderTargetView(device, backBuffer);
            surface    = backBuffer.QueryInterface <Surface>();

            factory2d      = new Factory2D();
            renderTarget2d = new RenderTarget(factory2d, surface,
                                              new RenderTargetProperties(new PixelFormat(Format.Unknown,
                                                                                         AlphaMode.Premultiplied)));

            sColorBrush = new SolidColorBrush(renderTarget2d, Color4.White);

            factoryWrite = new FactoryW();
            textFormat   = new TextFormat(factoryWrite, "Ricty", 25)
            {
                TextAlignment      = TextAlignment.Leading,
                ParagraphAlignment = ParagraphAlignment.Near
            };
            renderTarget2d.TextAntialiasMode = TextAntialiasMode.Cleartype;
            textArea = new RectangleF(0, 0, Width / 2f, Height / 2f);

            simulator = new HeatSimulator();
            stopWatch = new Stopwatch();
            cells     = new GridCell[simulator.DivNum, simulator.DivNum];
            for (var i = 0; i < simulator.DivNum; i++)
            {
                for (var j = 0; j < simulator.DivNum; j++)
                {
                    cells[i, j] = new GridCell(factory2d, Width, Height, i, j, simulator.DivNum, simulator.State);
                }
            }
        }
        private void BuildBuffer()
        {
            Utilities.Dispose(ref backBuffer);
            Utilities.Dispose(ref renderView);
            Utilities.Dispose(ref depthBuffer);
            Utilities.Dispose(ref depthView);

            Trace.TraceInformation("Building new buffer");
            swapChain.ResizeBuffers(swapChainDescription.BufferCount, (int)ScreenSize.X, (int)ScreenSize.Y, Format.Unknown, SwapChainFlags.None);
            backBuffer  = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            renderView  = new RenderTargetView(graphicsDevice, backBuffer);
            depthBuffer = new Texture2D(graphicsDevice, new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = (int)ScreenSize.X,
                Height            = (int)ScreenSize.Y,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });
            depthView = new DepthStencilView(graphicsDevice, depthBuffer);

            rasterizerState = new RasterizerState(graphicsDevice, new RasterizerStateDescription()
            {
                CullMode = CullMode.Back,
                FillMode = FillMode.Solid
            });

            graphicsContext.Rasterizer.State = rasterizerState;
            graphicsContext.Rasterizer.SetViewport(0, 0, (int)ScreenSize.X, (int)ScreenSize.Y);

            BlendStateDescription blending = new BlendStateDescription();

            blending.RenderTarget[0].IsBlendEnabled        = true;
            blending.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            blending.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            blending.RenderTarget[0].SourceBlend           = BlendOption.SourceAlpha;
            blending.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            blending.RenderTarget[0].SourceAlphaBlend      = BlendOption.Zero;
            blending.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blending.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            blendState = new BlendState(graphicsDevice, blending);

            graphicsContext.OutputMerger.SetBlendState(blendState);
            graphicsContext.OutputMerger.SetTargets(depthView, renderView);
        }
Example #12
0
        public SwapChain(Form form, Renderer renderer, int fullScreenWidth, int fullScreenHeight)
        {
            if (fullScreenWidth == 0 || fullScreenHeight == 0)
            {
                fullScreenWidth  = SystemInformation.VirtualScreen.Width;
                fullScreenHeight = SystemInformation.VirtualScreen.Height;
            }
            this.fullScreenWidth  = fullScreenWidth;
            this.fullScreenHeight = fullScreenHeight;

            formWidth  = form.ClientSize.Width;
            formHeight = form.ClientSize.Height;

            var swapChainDescriptor = new SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(0, 1), Format.R8G8B8A8_UNorm),
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard
            };

            using (var factory = new Factory1()) {
                swapChain = new DXSwapChain(factory, renderer.Device, swapChainDescriptor);
            }
            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0)) {
                RenderTarget = new RenderTargetGroup(resource);
            }

            using (var fac = swapChain.GetParent <Factory>()) {
                fac.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);
            }

            form.ResizeBegin += (o, e) => {
                formHeight = ((Form)o).Height;
                formWidth  = ((Form)o).Width;
            };
            form.ResizeBegin += (o, e) => {
                isResizing = true;
            };
            form.ResizeEnd += (o, e) => {
                isResizing = false;
                HandleResize(o, e);
            };
            form.KeyDown += HandleKeyDown;

            form.SizeChanged += HandleResize;
        }
Example #13
0
        private void ResetDeviceToNewViewportSize(Size newSizeInPixel)
        {
            backBuffer.Dispose();
            surface.Dispose();
            RenderTarget.Dispose();

            width  = (int)newSizeInPixel.Width;
            height = (int)newSizeInPixel.Height;
            swapChain.ResizeBuffers(BackBufferCount, width, height, BackBufferFormat, SwapChainFlags.None);
            backBuffer   = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            surface      = backBuffer.QueryInterface <Surface>();
            RenderTarget = new RenderTarget(direct2DFactory, surface, defaultRenderTargetProperties);
            Screen       = new ScreenSpace(newSizeInPixel);
        }
Example #14
0
        protected override void OnSurfaceInvalidated(object sender, EventArgs e)
        {
            var swapChain        = D3DApp11.I.SwapChain;
            var clientSize       = D3DApp11.I.ControlWindow.ClientSize;
            var device           = D3DApp11.I.D3DDevice;
            var immediateContext = D3DApp11.I.ImmediateContext;

            // Dispose all previous allocated resources
            Utilities.Dispose(ref _backBuffer);
            Utilities.Dispose(ref _renderView);
            Utilities.Dispose(ref _depthBuffer);
            Utilities.Dispose(ref _depthView);

            // Resize the backbuffer
            swapChain.ResizeBuffers(_swapChainDescription.BufferCount, clientSize.Width, clientSize.Height, Format.Unknown, SwapChainFlags.None);
            // Get the backbuffer from the swapchain
            _backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);

            // Renderview on the backbuffer
            _renderView = new RenderTargetView(device, _backBuffer);

            // Create the depth buffer
            _depthBuffer = new Texture2D(device, new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = clientSize.Width,
                Height            = clientSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            // Create the depth buffer view
            _depthView = new DepthStencilView(device, _depthBuffer);

            // Setup targets and viewport for rendering
            _viewport = new Viewport(0, 0, clientSize.Width, clientSize.Height, 0.0f, 1.0f);
            immediateContext.Rasterizer.SetViewport(_viewport);
            immediateContext.OutputMerger.SetTargets(_depthView, _renderView);

            base.OnSurfaceInvalidated(sender, e);
        }
Example #15
0
        public void Resize(Int2 resolution, bool fullScreen)
        {
            Helpers.Dispose(ref drawingSurfaceRTV);
            Helpers.Dispose(ref drawingSurfaceBuffer);
            swapChain.ResizeBuffers(2, resolution.X, resolution.Y, Format.Unknown, SwapChainFlags.None);
            swapChain.IsFullScreen = fullScreen;

            // Get the backbuffer from the swapchain.
            drawingSurfaceBuffer           = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            drawingSurfaceBuffer.DebugName = "Window Backbuffer";
            drawingSurfaceRTV = new RenderTargetView(Device, drawingSurfaceBuffer)
            {
                DebugName = "Window Backbuffer RTV"
            };

            Resolution = resolution;
        }
Example #16
0
        public SharpDXDevice(Window window)
        {
            this.window = window;
            width       = (int)window.ViewportSize.Width;
            height      = (int)window.ViewportSize.Height;
            DxDevice.CreateWithSwapChain(DriverType.Hardware,
#if DEBUG
                                         DeviceCreationFlags.Debug |
#endif
                                         DeviceCreationFlags.BgraSupport,
                                         CreateSwapChainDescription(), out device, out swapChain);
            direct2DFactory             = new D2dFactory();
            backBuffer                  = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            surface                     = backBuffer.QueryInterface <Surface>();
            RenderTarget                = new RenderTarget(direct2DFactory, surface, defaultRenderTargetProperties);
            window.ViewportSizeChanged += ResetDeviceToNewViewportSize;
            Screen = new ScreenSpace(window.ViewportSize);
        }
Example #17
0
        private void DoResize(int width, int height)
        {
            while (Renderer.Instance.RenderingInProgress)
            {
            }
            var rt = RenderTarget.RenderTargets[0];

            rt.Clear();
            swapChain.ResizeBuffers(1, width, height, Format.Unknown, SwapChainFlags.AllowModeSwitch);
            using (var tex = Resource.FromSwapChain <Texture2D>(swapChain, 0)) {
                rt.Update(null, new RenderTargetView(Renderer.Instance.Device, tex));
                rt.SendResizeEvent();
            }
            Viewport = new Viewport(0, 0, width, height);
            OnResize?.Invoke(this, new Event.SResizeEvent {
                Size = new System.Drawing.Size(width, height)
            });
        }
Example #18
0
        public void Initialize()
        {
            if (!_deviceManager.IsInitialized)
            {
                throw new InvalidOperationException("Device manager is not initialized");
            }

            if (Initialized)
            {
                Uninitialize();
            }

            var swapChainDescription = new SwapChainDescription1
            {
                Width             = Width,
                Height            = Height,
                Format            = Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(SampleCount, SampleQuality),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                BufferCount       = 1,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.Discard,
                Flags             = SwapChainFlags.AllowModeSwitch
            };
            var fullScreenDescription = new SwapChainFullScreenDescription
            {
                RefreshRate = new Rational(60, 1),
                Scaling     = DisplayModeScaling.Centered,
                Windowed    = true
            };

            using (var dxgiDevice2 = _deviceManager.Device.QueryInterface <Device2>())
                using (var dxgiFactory2 = dxgiDevice2.Adapter.GetParent <Factory2>())
                {
                    SwapChain = new SwapChain1(dxgiFactory2, _deviceManager.Device, _windowHandle, ref swapChainDescription, fullScreenDescription);
                    dxgiFactory2.MakeWindowAssociation(_windowHandle, WindowAssociationFlags.IgnoreAll);
                }

            Texture          = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
            RenderTargetView = new RenderTargetView(_deviceManager.Device, Texture);

            Initialized = true;
        }
Example #19
0
        protected override void WindowResize(int width, int height)
        {
            base.WindowResize(width, height);


            Device.ImmediateContext.ClearState();

            _renderTarget2D.Dispose();
            BackBuffer.Dispose();
            RenderView.Dispose();
            _surface?.Dispose();

            SwapChain.ResizeBuffers(1, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.None);

            BackBuffer      = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
            RenderView      = new RenderTargetView(Device, BackBuffer);
            _surface        = BackBuffer.QueryInterface <Surface>();
            _renderTarget2D = new RenderTarget(Factory2D, _surface,
                                               new RenderTargetProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)));
        }
Example #20
0
        private void RecreateBuffers()
        {
            Utilities.Dispose(ref this.backBuffer);
            Utilities.Dispose(ref this.renderTargetView);
            Utilities.Dispose(ref this.depthBuffer);
            Utilities.Dispose(ref this.depthStencilView);

            this.backBuffer       = Resource.FromSwapChain <Texture2D>(this.swapChain, 0);
            this.renderTargetView = new RenderTargetView(this.device, this.backBuffer);
            this.depthBuffer      = new Texture2D(this.device, new Texture2DDescription
            {
                Format            = Format.D24_UNorm_S8_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = this.Width,
                Height            = this.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None,
            });
            this.depthStencilView = new DepthStencilView(this.device, this.depthBuffer);

            this.deviceContext.Rasterizer.State = new RasterizerState(this.device, new RasterizerStateDescription
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = false,
                DepthBias                = 0,
                DepthBiasClamp           = 0,
                SlopeScaledDepthBias     = 0,
                IsDepthClipEnabled       = true,
                IsScissorEnabled         = false,
                IsMultisampleEnabled     = false,
                IsAntialiasedLineEnabled = false,
            });

            this.deviceContext.Rasterizer.SetViewport(new Viewport(0, 0, this.Width, this.Height, 0.0f, 1.0f));
            this.deviceContext.OutputMerger.SetTargets(this.depthStencilView, this.renderTargetView);
        }
        public void CreateDeviceAndSwapChain(System.Windows.Forms.Control form)
        {
            this.form = form;

            var description = new SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out device, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            resource     = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            renderTarget = new RenderTargetView(device, resource);

            // setting a viewport is required if you want to actually see anything
            context  = device.ImmediateContext;
            viewport = new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height);
            context.OutputMerger.SetTargets(renderTarget);
            context.Rasterizer.SetViewport(viewport);

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            //using (var factory = swapChain.GetParent<Factory>())
            //    factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // handle alt+enter ourselves
            form.KeyDown += (o, e) =>
            {
                if (e.Alt && e.KeyCode == Keys.Enter)
                {
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;
                }
            };
        }
Example #22
0
        public void スワップチェーンをリサイズする()
        {
            if (BindedControl.ClientSize.Width == 0 || BindedControl.ClientSize.Height == 0)
            {
                return; //フォームがフロート状態になった時一瞬だけ来て、デバイスが作れなくなるのでこの時はなしにする。
            }
            // デバイスリソースの解放
            レンダーターゲットと深度ステンシルターゲットをDisposeする();

            // スワップチェーンのリサイズ
            var desc = SwapChain.Description;

            SwapChain.ResizeBuffers(desc.BufferCount, BindedControl.ClientSize.Width, BindedControl.ClientSize.Height, desc.ModeDescription.Format, desc.Flags);

            // デバイスリソースの作成
            using (Texture2D depthBuffer = new Texture2D(RenderContext.Instance.DeviceManager.D3DDevice, getDepthBufferTexture2DDescription(BindedControl, desc.SampleDescription)))
            {
                深度ステンシルビュー = new DepthStencilView(RenderContext.Instance.DeviceManager.D3DDevice, depthBuffer);
            }
            using (Texture2D renderTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0))
            {
                D3Dレンダーターゲットビュー = new RenderTargetView(RenderContext.Instance.DeviceManager.D3DDevice, renderTexture);
            }
        }
Example #23
0
        public DX11(RenderForm form, CoreSettings coreSettings)
        {
            _form = form;
            sw    = Stopwatch.StartNew();
            LoadedTexturesByName = new Dictionary <string, ShaderResourceView>();
            LoadedTexturesByPtrs = new Dictionary <IntPtr, ShaderResourceView>();

            var swapChainDesc = new SwapChainDescription
            {
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                BufferCount       = 1,
                IsWindowed        = true,
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard,
                SampleDescription = new SampleDescription(1, 0),
                ModeDescription   = new ModeDescription
                {
                    Format           = Format.R8G8B8A8_UNorm,
                    Width            = form.Width,
                    Height           = form.Height,
                    Scaling          = DisplayModeScaling.Unspecified,
                    RefreshRate      = new Rational(60, 1),
                    ScanlineOrdering = DisplayModeScanlineOrder.Unspecified
                }
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None,
                                       new[] { FeatureLevel.Level_11_0, FeatureLevel.Level_10_0 }, swapChainDesc, out var device,
                                       out var swapChain);

            D11Device     = device;
            DeviceContext = device.ImmediateContext;
            _swapChain    = swapChain;

            factory = swapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);
            BackBuffer       = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            RenderTargetView = new RenderTargetView(device, BackBuffer);

            using (new PerformanceTimer("Init ImGuiRender"))
            {
                ImGuiRender = new ImGuiRender(this, form, coreSettings);
            }

            using (new PerformanceTimer("Init SpriteRender"))
            {
                SpritesRender = new SpritesRender(this, form, coreSettings);
            }

            InitStates();

            form.UserResized += (sender, args) =>
            {
                RenderTargetView?.Dispose();
                BackBuffer.Dispose();

                swapChain.ResizeBuffers(1, form.Width, form.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);
                BackBuffer       = Resource.FromSwapChain <Texture2D>(swapChain, 0);
                RenderTargetView = new RenderTargetView(device, BackBuffer);
                ImGuiRender.Resize(form.Bounds);
                ImGuiRender.UpdateConstantBuffer();
                SpritesRender.ResizeConstBuffer(BackBuffer.Description);
                var descp = BackBuffer.Description;
                Viewport.Height = form.Height;
                Viewport.Width  = form.Width;
                DeviceContext.Rasterizer.SetViewport(Viewport);
                DeviceContext.OutputMerger.SetRenderTargets(RenderTargetView);
            };

            ImGuiDebug     = new DebugInformation("ImGui");
            SpritesDebug   = new DebugInformation("Sprites");
            SwapchainDebug = new DebugInformation("Swapchain");

            // Core.DebugInformations.Add(ImGuiDebug);
            // Core.DebugInformations.Add(ImGuiInputDebug);
            // Core.DebugInformations.Add(SpritesDebug);
            // Core.DebugInformations.Add(SwapchainDebug);
        }
Example #24
0
        public void Run()
        {
            form = CreateForm();

            SwapChainDescription desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(1280, 720, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = DisplayHandle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new[] { FeatureLevelDX.Level_10_0 }, desc, out device, out swapChain);
            FactoryDX factory = swapChain.GetParent <FactoryDX>();

            factory.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll);
            backBuffer     = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            backBufferView = new RenderTargetView(device, backBuffer);

            Factory2D = new Factory2D();
            using (Surface surface = backBuffer.QueryInterface <Surface>()) {
                RenderTarget2D = new RenderTarget(Factory2D, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            }
            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;
            FactoryDirectWrite           = new FactoryDW();
            SceneColorBrush = new SolidColorBrush(RenderTarget2D, new RawColor4(1, 1, 1, 1));

            Initialize();
            bool isFormClosed   = false;
            bool formIsResizing = false;

            form.MouseClick  += HandleMouseClick;
            form.KeyDown     += HandleKeyDown;
            form.KeyUp       += HandleKeyUp;
            form.FormClosed  += (o, args) => { isFormClosed = true; };
            form.ResizeBegin += (o, args) => { formIsResizing = true; };
            form.ResizeEnd   += (o, args) => {
                formIsResizing = false;
                HandleResize(o, args);
            };
            form.Resize += (o, args) => {
                if (form.WindowState != currentFormWindowState)
                {
                    HandleResize(o, args);
                }
                currentFormWindowState = form.WindowState;
            };

            LoadContent();
            clock.Start();
            BeginRun();
            RenderLoop.Run(form, () => {
                if (isFormClosed)
                {
                    return;
                }
                OnUpdate();
                if (!formIsResizing)
                {
                    Render();
                }
            });

            UnloadContent();
            EndRun();

            Dispose();
        }
Example #25
0
            private void SetupScreenBuffers()
            {
                width  = (int)window.Bounds.Width;
                height = (int)window.Bounds.Height;

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

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

                    // First, retrieve the underlying DXGI Device from the D3D Device.
                    // Creates the swap chain
                    using (var dxgiDevice2 = graphicsDevice.QueryInterface <Device2>())
                        using (Adapter dxgiAdapter = dxgiDevice2.Adapter)
                            using (var dxgiFactory2 = dxgiAdapter.GetParent <Factory2>())
                            {
                                // Creates a SwapChain from a CoreWindow pointer
                                using (var comWindow = new ComObject(window))
                                    swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(graphicsDevice, comWindow, ref desc, null);

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

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

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

                // Set the current viewport using the descriptor.
                graphicsDevice.ImmediateContext.Rasterizer.SetViewport(viewport);
            }
Example #26
0
        public void InitializeBuffers()
        {
            //Create back buffer
            Texture2D backBuffer = Resource.FromSwapChain <Texture2D>(SwapChain, 0);

            _renderTargetView = new RenderTargetView(Device, backBuffer);
            backBuffer.Dispose();

            //Create the depth/stencil buffer
            var depthBufferDesc = new Texture2DDescription
            {
                Width             = ConfigurationManager.Config.Width,
                Height            = ConfigurationManager.Config.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D24_UNorm_S8_UInt,
                SampleDescription = ConfigurationManager.Config.AntiAliasing ? new SampleDescription(4, _maxQualityLevel - 1) : new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            _depthStencilBuffer = new Texture2D(Device, depthBufferDesc);

            DepthStencilStateDescription depthStencilDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask  = 0xFF,
                StencilWriteMask = 0xFF,
                // Stencil operation if pixel front-facing.
                FrontFace = new DepthStencilOperationDescription
                {
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation      = StencilOperation.Keep,
                    Comparison         = Comparison.Always
                },
                // Stencil operation if pixel is back-facing.
                BackFace = new DepthStencilOperationDescription
                {
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation      = StencilOperation.Keep,
                    Comparison         = Comparison.Always
                }
            };

            // Create the depth stencil state.
            _depthStencilState = new DepthStencilState(Device, depthStencilDesc);

            DepthStencilStateDescription depthDisabledStencilDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled   = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask  = 0xFF,
                StencilWriteMask = 0xFF,
                // Stencil operation if pixel front-facing.
                FrontFace = new DepthStencilOperationDescription
                {
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation      = StencilOperation.Keep,
                    Comparison         = Comparison.Always
                },
                // Stencil operation if pixel is back-facing.
                BackFace = new DepthStencilOperationDescription
                {
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation      = StencilOperation.Keep,
                    Comparison         = Comparison.Always
                }
            };

            _depthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);

            // Set the depth stencil state.
            _isZBufferEnabled = true;
            DeviceContext.OutputMerger.SetDepthStencilState(_depthStencilState, 1);

            // Initialize and set up the depth stencil view.
            DepthStencilViewDescription depthStencilViewDesc;

            if (ConfigurationManager.Config.AntiAliasing)
            {
                depthStencilViewDesc = new DepthStencilViewDescription
                {
                    Format      = Format.D24_UNorm_S8_UInt,
                    Dimension   = DepthStencilViewDimension.Texture2DMultisampled,
                    Texture2DMS = new DepthStencilViewDescription.Texture2DMultisampledResource()
                }
            }
            ;
            else
            {
                depthStencilViewDesc = new DepthStencilViewDescription
                {
                    Format    = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                }
            };

            // Create the depth stencil view.
            DepthStencilView = new DepthStencilView(Device, _depthStencilBuffer, depthStencilViewDesc);

            RenderToTextureDepthStencilView = new DepthStencilView(Device, new Texture2D(Device, new Texture2DDescription
            {
                Width             = ConfigurationManager.Config.Width,
                Height            = ConfigurationManager.Config.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            }), new DepthStencilViewDescription
            {
                Format    = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            });


            // Bind the render target view and depth stencil buffer to the output render pipeline.
            DeviceContext.OutputMerger.SetTargets(DepthStencilView, _renderTargetView);

            // Setup the raster description which will determine how and what polygon will be drawn.
            var rasterDesc = new RasterizerStateDescription
            {
                IsAntialiasedLineEnabled = false,
                CullMode                = CullMode.Back,
                DepthBias               = 0,
                DepthBiasClamp          = .0f,
                IsDepthClipEnabled      = true,
                FillMode                = FillMode.Solid,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled    = false,
                IsScissorEnabled        = false,
                SlopeScaledDepthBias    = .0f
            };

            // Create the rasterizer state from the description we just filled out.
            _rasterStateSolid = new RasterizerState(Device, rasterDesc);

            rasterDesc.FillMode = FillMode.Wireframe;

            _rasterStateWireFrame = new RasterizerState(Device, rasterDesc);

            // Now set the rasterizer state.
            DeviceContext.Rasterizer.State = _rasterStateSolid;

            // Setup and create the viewport for rendering.
            DeviceContext.Rasterizer.SetViewport(0, 0, ConfigurationManager.Config.Width, ConfigurationManager.Config.Height, 0, 1);

            var blendStateDescription = new BlendStateDescription();

            blendStateDescription.RenderTarget[0].IsBlendEnabled        = true;
            blendStateDescription.RenderTarget[0].SourceBlend           = BlendOption.SourceAlpha;
            blendStateDescription.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            blendStateDescription.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
            blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blendStateDescription.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            // Create the blend state using the description.
            _alphaEnabledBlendState = new BlendState(Device, blendStateDescription);

            blendStateDescription.RenderTarget[0].IsBlendEnabled = false;
            // Create the blend state using the description.
            _alphaDisabledBlendState = new BlendState(Device, blendStateDescription);
        }
Example #27
0
        private void CreateSwapChain()
        {
            if (_swapChain == null)
            {
                //Create the SwapChain Param object
                SwapChainDescription SwapDesc = new SwapChainDescription()
                {
                    BufferCount     = 1,
                    Usage           = Usage.RenderTargetOutput,
                    OutputHandle    = _renderForm.Handle,
                    IsWindowed      = true,
                    ModeDescription = RenderResolution == default(Size) ? new ModeDescription()
                    {
                        Format = Format.R8G8B8A8_UNorm, Width = _renderForm.ClientSize.Width, Height = _renderForm.ClientSize.Height
                    }
                                                                        : new ModeDescription()
                    {
                        Format = Format.R8G8B8A8_UNorm, Width = RenderResolution.Width, Height = RenderResolution.Height
                    },
                    SampleDescription = CurrentMSAASampling,
                    SwapEffect        = SwapEffect.Discard
                };

                if (!FULLDEBUGMODE)
                {
                    Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, SwapDesc, out Device, out _swapChain);
                    logger.Info("Device and swapchain created in Release mode");
                }
                else
                {
                    try
                    {
                        Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, SwapDesc, out Device, out _swapChain);
                        logger.Info("Device et swapchain created in FULLDEBUGMODE mode");
                    }
                    catch (SharpDXException ex)
                    {
                        logger.Warn("Error Creating SwapChain or Device in debug mode : {0}", ex.Message);
                        Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, SwapDesc, out Device, out _swapChain);
                        logger.Info("Device et swapchain created in Release mode");
                    }
                }

                //Create the threaded contexts
                ImmediateContext = Device.ImmediateContext;

#if DEBUG
                //Set resource Name, will only be done at debug time.
                Device.DebugName           = "Main Created DX11 device";
                _swapChain.DebugName       = "Main Swap Chain";
                ImmediateContext.DebugName = "Immediat Context";
#endif
            }
            else
            {
                if (RenderResolution == default(Size) || IsFullScreen)
                {
                    _swapChain.ResizeBuffers(1, _renderForm.ClientSize.Width, _renderForm.ClientSize.Height, Format.R8G8B8A8_UNorm, (int)SwapChainFlags.None);
                }
                else
                {
                    _swapChain.ResizeBuffers(1, RenderResolution.Width, RenderResolution.Height, Format.R8G8B8A8_UNorm, (int)SwapChainFlags.None);
                }
            }

            logger.Info("SwapChain is using the GPU in mode : [{1}px * {2}px], format : {0}, RefreshRate : {3}hz, Scaling : {4}, ScanlineMode : {5}", _swapChain.Description.ModeDescription.Format, _swapChain.Description.ModeDescription.Width, _swapChain.Description.ModeDescription.Height, (float)_swapChain.Description.ModeDescription.RefreshRate.Numerator / _swapChain.Description.ModeDescription.RefreshRate.Denominator, _swapChain.Description.ModeDescription.Scaling, _swapChain.Description.ModeDescription.ScanlineOrdering);
            // Get the created BackBuffer
            BackBufferTex = Resource.FromSwapChain <Texture2D>(_swapChain, 0);

#if DEBUG
            //Set resource Name, will only be done at debug time.
            BackBufferTex.DebugName = "Device BackBuffer";
#endif
        }
        public void Initialize()
        {
            var flags = DeviceCreationFlags.BgraSupport;

            if (dxDebug)
            {
                flags |= DeviceCreationFlags.Debug;
            }

            NativeMethods.GetWindowRect(outputHandle, out var size);

            var swapChainDescription = new SwapChainDescription
            {
                OutputHandle      = outputHandle,
                BufferCount       = 1,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(size.Width, size.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput,
            };


            Device.CreateWithSwapChain(DriverType.Hardware, flags, new FeatureLevel[] { FeatureLevel.Level_11_0 }, swapChainDescription, out device, out swapChain);


            // New RenderTargetView from the backbuffer
            var backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);

            renderTargetView = new RenderTargetView(device, backBuffer);
            backBuffer.Dispose();


            Texture2DDescription depthBufferDesc = new Texture2DDescription()
            {
                Width             = size.Width,
                Height            = size.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            depthStencilBuffer = new Texture2D(device, depthBufferDesc);

            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format    = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            depthStencilView = new DepthStencilView(device, depthStencilBuffer, depthStencilViewDesc);

            RasterizerStateDescription rasterDesc = new RasterizerStateDescription()
            {
                IsAntialiasedLineEnabled = false,
                CullMode                = CullMode.Back,
                DepthBias               = 0,
                DepthBiasClamp          = .0f,
                IsDepthClipEnabled      = true,
                FillMode                = FillMode.Solid, //FillMode.Wireframe,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled    = false,
                IsScissorEnabled        = false,
                SlopeScaledDepthBias    = .0f
            };

            rasterizerState = new RasterizerState(device, rasterDesc);

            device.ImmediateContext.Rasterizer.SetViewport(0, 0, size.Width, size.Height);
            SetRenderTexture(null);
            device.ImmediateContext.Rasterizer.State = rasterizerState;
        }
Example #29
0
        protected void InitialiseResources()
        {
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _surface);
            RemoveAndDispose(ref _target);
            _d2dContext.Target = null;

            var desc = CreateSwapChainDescription();

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

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

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

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

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

            _d3dContext.Rasterizer.SetViewport(viewport);

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


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

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

            /*_backBuffer = ToDispose(Resource.FromSwapChain<Texture2D>(_swapChain, 0));
             * _renderTargetView = ToDispose(new RenderTargetView(_d3dDevice, _backBuffer));
             * _surface = ToDispose(_backBuffer.QueryInterface<Surface>());
             *
             * using (var dxgiBackBuffer = _swapChain.GetBackBuffer<Surface>(0))
             *  _target = ToDispose(new RenderTarget(_d2dFactory, dxgiBackBuffer, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))));
             */
            OnInitialize?.Invoke(this);
        }
Example #30
0
        public void Show()
        {
            using var form = new RenderForm(_title);

            // create a Device and SwapChain
            var swapChainDescription = new SwapChainDescription
            {
                BufferCount       = 2,
                Flags             = SwapChainFlags.None,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.B8G8R8A8_UNorm),
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, swapChainDescription, out var device, out var swapChain);
            using var swapChain1 = swapChain.QueryInterface <SwapChain1>();

            // ignore all Windows events
            using var factory = swapChain1.GetParent <Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            using var vertexShaderByteCode = ShaderBytecode.CompileFromFile("./Shader.fx", "VS", "vs_5_0");
            using var vertexShader         = new VertexShader(device, vertexShaderByteCode);

            using var pixelShaderByteCode = ShaderBytecode.CompileFromFile("./Shader.fx", "PS", "ps_5_0");
            using var pixelShader         = new PixelShader(device, pixelShaderByteCode);

            using var layout = new InputLayout(device, vertexShaderByteCode, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
            });

            using var vertexes = Buffer.Create(device, BindFlags.VertexBuffer, new[]
            {
                new Vertex { Position = new RawVector3(-1.0f, 1.0f, 0.5f), TexCoord = new RawVector2(0.0f, 0.0f) },
                new Vertex { Position = new RawVector3(1.0f, 1.0f, 0.5f), TexCoord = new RawVector2(1.0f, 0.0f) },
                new Vertex { Position = new RawVector3(-1.0f, -1.0f, 0.5f), TexCoord = new RawVector2(0.0f, 1.0f) },
                new Vertex { Position = new RawVector3(1.0f, -1.0f, 0.5f), TexCoord = new RawVector2(1.0f, 1.0f) }
            });

            var samplerStateDescription = new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter   = Filter.MinMagMipLinear
            };

            device.ImmediateContext.InputAssembler.InputLayout       = layout;
            device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexes, Utilities.SizeOf <Vertex>(), 0));
            device.ImmediateContext.VertexShader.Set(vertexShader);
            device.ImmediateContext.PixelShader.SetSampler(0, new SamplerState(device, samplerStateDescription));
            device.ImmediateContext.PixelShader.Set(pixelShader);

            // create a first views
            var backBuffer = Resource.FromSwapChain <Texture2D>(swapChain1, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            device.ImmediateContext.Rasterizer.SetViewport(0, 0, form.ClientSize.Width, form.ClientSize.Height);
            device.ImmediateContext.OutputMerger.SetTargets(renderView);

            // listen events (but processed in render loop)
            var isResized = false;

            form.UserResized += (_, __) => isResized = true;

            RenderLoop.Run(form, () =>
            {
                // ReSharper disable AccessToDisposedClosure
                if (!_captureMethod.IsCapturing)
                {
                    _captureMethod.StartCapture(form.Handle, device, factory);
                }

                if (isResized)
                {
                    Utilities.Dispose(ref backBuffer);
                    Utilities.Dispose(ref renderView);

                    swapChain1.ResizeBuffers(swapChainDescription.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None);
                    backBuffer = Resource.FromSwapChain <Texture2D>(swapChain1, 0);
                    renderView = new RenderTargetView(device, backBuffer);

                    device.ImmediateContext.Rasterizer.SetViewport(0, 0, form.ClientSize.Width, form.ClientSize.Height);
                    device.ImmediateContext.OutputMerger.SetTargets(renderView);

                    isResized = false;
                }

                // clear view
                device.ImmediateContext.ClearRenderTargetView(renderView, new RawColor4(1.0f, 1.0f, 1.0f, 1.0f));

                using var texture2d = _captureMethod.TryGetNextFrameAsTexture2D(device);
                if (texture2d != null)
                {
                    using var shaderResourceView = new ShaderResourceView(device, texture2d);
                    device.ImmediateContext.PixelShader.SetShaderResource(0, shaderResourceView);
                }

                // draw it
                device.ImmediateContext.Draw(4, 0);
                swapChain1.Present(1, PresentFlags.None, new PresentParameters());

                // ReSharper restore AccessToDisposedClosure
            });

            renderView.Dispose();
            backBuffer.Dispose();
            swapChain.Dispose();
            device.Dispose();
        }