Beispiel #1
0
        void resize()
        {
            if (renderView == null)//first show
            {
                var dxgiFactory = device.QueryInterface <IDXGIDevice>().GetParent <IDXGIAdapter>().GetParent <IDXGIFactory>();

                var swapchainDesc = new SwapChainDescription()
                {
                    BufferCount       = 1,
                    BufferDescription = new ModeDescription(Win32Window.Width, Win32Window.Height, format),
                    IsWindowed        = true,
                    OutputWindow      = Win32Window.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect        = SwapEffect.Discard,
                    Usage             = Vortice.DXGI.Usage.RenderTargetOutput
                };

                swapChain = dxgiFactory.CreateSwapChain(device, swapchainDesc);
                dxgiFactory.MakeWindowAssociation(Win32Window.Handle, WindowAssociationFlags.IgnoreAll);

                backBuffer = swapChain.GetBuffer <ID3D11Texture2D>(0);
                renderView = device.CreateRenderTargetView(backBuffer);
            }
            else
            {
                renderView.Dispose();
                backBuffer.Dispose();

                swapChain.ResizeBuffers(1, Win32Window.Width, Win32Window.Height, format, SwapChainFlags.None);

                backBuffer = swapChain.GetBuffer <ID3D11Texture2D1>(0);
                renderView = device.CreateRenderTargetView(backBuffer);
            }
        }
Beispiel #2
0
        private void CreateSwapChainForDesktop()
        {
            ModeDescription BackBufferDesc = new ModeDescription()
            {
                Width       = Description.BackBufferWidth,
                Height      = Description.BackBufferHeight,
                Format      = Format.R8G8B8A8_UNorm,
                RefreshRate = new Rational()
                {
                    Numerator   = 60,
                    Denominator = 1
                },
                ScanlineOrdering = ModeScanlineOrder.Unspecified,
                Scaling          = ModeScaling.Unspecified,
            };

            SampleDescription sampleDescription = new SampleDescription()
            {
                Count   = 1,
                Quality = 0
            };

            SwapChainFlags Flags = Description.Settings.Fullscreen ? SwapChainFlags.None : SwapChainFlags.AllowModeSwitch;



            SwapChainDescription swapChainDesc = new SwapChainDescription()      // Initialize the swap chain description.
            {
                BufferCount       = bufferCount,                                 // Set to a single back buffer.
                BufferDescription = BackBufferDesc,                              // Set the width and height of the back buffer.
                Usage             = Usage.Backbuffer | Usage.RenderTargetOutput, // Set the usage of the back buffer.
                OutputWindow      = Description.DeviceHandle,                    // Set the handle for the window to render to.
                SampleDescription = sampleDescription,                           // Turn multisampling off.
                IsWindowed        = true,                                        // Set to full screen or windowed mode.
                Flags             = Flags,                                       // Don't set the advanced flags.
                SwapEffect        = SwapEffect.FlipDiscard,                      // Discard the back buffer content after presenting.
            };



            IDXGIFactory4 Factory = GraphicsDevice.NativeAdapter.NativeFactory;

            IDXGISwapChain swapChain = Factory.CreateSwapChain(GraphicsDevice.NativeDirectCommandQueue.Queue, swapChainDesc);

            if (Description.Settings.Fullscreen)
            {
                // Before fullscreen switch
                swapChain.ResizeTarget(BackBufferDesc);

                // Switch to full screen
                swapChain.SetFullscreenState(true, default);

                // This is really important to call ResizeBuffers AFTER switching to IsFullScreen
                swapChain.ResizeBuffers(3, Description.BackBufferWidth, Description.BackBufferHeight, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
            }



            NativeSwapChain = swapChain.QueryInterface <IDXGISwapChain3>();
        }
Beispiel #3
0
        public unsafe Result SetSwapChain(IDXGISwapChain swapChain)
        {
            Result result = LocalInterop.CalliStdCallint(_nativePointer, (void *)swapChain.NativePointer.ToPointer(), (*(void ***)_nativePointer)[3]);

            GC.KeepAlive(swapChain);
            return(result);
        }
Beispiel #4
0
        public D3D11GraphicsDevice(bool validation, Window window)
        {
            Window = window;
            if (CreateDXGIFactory1(out Factory).Failure)
            {
                throw new InvalidOperationException("Cannot create IDXGIFactory1");
            }

            var creationFlags = DeviceCreationFlags.BgraSupport;

            if (validation)
            {
                creationFlags |= DeviceCreationFlags.Debug;
            }

            if (D3D11CreateDevice(
                    null,
                    DriverType.Hardware,
                    creationFlags,
                    _featureLevels,
                    out Device, out FeatureLevel, out DeviceContext).Failure)
            {
                // Remove debug flag not being supported.
                creationFlags &= ~DeviceCreationFlags.Debug;

                var result = D3D11CreateDevice(null, DriverType.Hardware,
                                               creationFlags, _featureLevels,
                                               out Device, out FeatureLevel, out DeviceContext);
                if (result.Failure)
                {
                    // This will fail on Win 7 due to lack of 11.1, so re-try again without it
                    D3D11CreateDevice(
                        null,
                        DriverType.Hardware,
                        creationFlags,
                        _featureLevelsNoLevel11,
                        out Device, out FeatureLevel, out DeviceContext).CheckError();
                }
            }

            var hwnd = (IntPtr)window.Handle;

            var swapChainDescription = new SwapChainDescription()
            {
                BufferCount       = FrameCount,
                BufferDescription = new ModeDescription(window.Width, window.Height, Format.B8G8R8A8_UNorm),
                IsWindowed        = true,
                OutputWindow      = hwnd,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Vortice.DirectX.Usage.RenderTargetOutput
            };

            SwapChain = Factory.CreateSwapChain(Device, swapChainDescription);
            Factory.MakeWindowAssociation(hwnd, WindowAssociationFlags.IgnoreAltEnter);

            BackBuffer       = SwapChain.GetBuffer <ID3D11Texture2D>(0);
            RenderTargetView = Device.CreateRenderTargetView(BackBuffer);
        }
        public static async Task <int> PresentAsync(this IDXGISwapChain obj, uint syncInterval, DXGI_PRESENT flags)
        {
            int result = await Task.Run(() =>
            {
                return(obj.Present(syncInterval, flags));
            }).ConfigureAwait(false);

            return(result);
        }
        public static ComObject <T> GetBuffer <T>(this IDXGISwapChain swapChain, uint index)
        {
            if (swapChain == null)
            {
                throw new ArgumentNullException(nameof(swapChain));
            }

            if (swapChain == null)
            {
                throw new ArgumentNullException(nameof(swapChain));
            }

            swapChain.GetBuffer(index, typeof(T).GUID, out var dc).ThrowOnError();
            return(new ComObject <T>((T)dc));
        }
Beispiel #7
0
        protected unsafe SwapChainDXGI(
            GraphicsDevice device,
            SwapChainDescriptor descriptor,
            IDXGIFactory1 dxgiFactory,
            ComObject deviceOrCommandQueue,
            int bufferCount,
            int backBufferCount)
            : base(device, descriptor)
        {
            BackBufferCount = backBufferCount;
            var width  = Math.Max(descriptor.Width, 1);
            var height = Math.Max(descriptor.Height, 1);

            switch (descriptor.Handle)
            {
            case Win32SwapChainHandle win32Handle:
            {
                // Check tearing support.
                var dxgiFactory5 = dxgiFactory.QueryInterfaceOrNull <IDXGIFactory5>();
                var allowTearing = false;
                if (dxgiFactory5 != null)
                {
                    if (dxgiFactory5.PresentAllowTearing)
                    {
                        // Recommended to always use tearing if supported when using a sync interval of 0.
                        _syncInterval  = 0;
                        _presentFlags |= PresentFlags.AllowTearing;
                        allowTearing   = true;
                    }

                    dxgiFactory5.Dispose();
                }

                var dxgiFactory2 = dxgiFactory.QueryInterfaceOrNull <IDXGIFactory2>();
                if (dxgiFactory2 != null)
                {
                    var swapchainDesc = new SwapChainDescription1()
                    {
                        Width             = width,
                        Height            = height,
                        Format            = BackBufferFormat,
                        Stereo            = false,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = Vortice.DirectX.Usage.RenderTargetOutput,
                        BufferCount       = bufferCount,
                        Scaling           = Scaling.Stretch,
                        SwapEffect        = allowTearing ? SwapEffect.FlipDiscard : SwapEffect.Discard,
                        AlphaMode         = AlphaMode.Ignore,
                        Flags             = allowTearing ? SwapChainFlags.AllowTearing : SwapChainFlags.None,
                    };

                    var fullscreenDescription = new SwapChainFullscreenDescription
                    {
                        Windowed = true
                    };

                    _swapChain = dxgiFactory2.CreateSwapChainForHwnd(
                        deviceOrCommandQueue,
                        win32Handle.HWnd,
                        swapchainDesc,
                        fullscreenDescription);

                    dxgiFactory2.Dispose();
                }
                else
                {
                    SwapChainDescription dxgiSCDesc = new SwapChainDescription
                    {
                        BufferCount       = bufferCount,
                        IsWindowed        = true,
                        BufferDescription = new ModeDescription(width, height, BackBufferFormat),
                        OutputWindow      = win32Handle.HWnd,
                        SampleDescription = new SampleDescription(1, 0),
                        SwapEffect        = SwapEffect.Discard,
                        Usage             = Vortice.DirectX.Usage.Backbuffer | Vortice.DirectX.Usage.RenderTargetOutput
                    };

                    _swapChain = dxgiFactory.CreateSwapChain(deviceOrCommandQueue, dxgiSCDesc);
                }

                dxgiFactory.MakeWindowAssociation(win32Handle.HWnd, WindowAssociationFlags.IgnoreAll);
            }
            break;

                //case CoreWindow coreWindowHandle:
                //    {
                //        var coreWindow = coreWindowHandle.CoreWindow;

                //        var swapchainDesc = new DXGI.SwapChainDescription1()
                //        {
                //            Width = width,
                //            Height = height,
                //            Format = DXGI.Format.B8G8R8A8_UNorm,
                //            Stereo = false,
                //            SampleDescription = new DXGI.SampleDescription(1, 0),
                //            Usage = DXGI.Usage.RenderTargetOutput,
                //            BufferCount = FrameCount,
                //            Scaling = DXGI.Scaling.AspectRatioStretch,
                //            SwapEffect = DXGI.SwapEffect.FlipDiscard,
                //            AlphaMode = DXGI.AlphaMode.Ignore,
                //            Flags = DXGI.SwapChainFlags.None,
                //        };

                //        using (var comCoreWindow = new ComObject(coreWindow))
                //        {
                //            _swapChain = new DXGI.SwapChain1(
                //                factory,
                //                device.D3DDevice,
                //                comCoreWindow,
                //                ref swapchainDesc);
                //        }
                //    }
                //    break;
            }
        }
Beispiel #8
0
        static void Main()
        {
            ReferenceTracker.TrackReferences = true;
            Form form = new Form();

            IDXGIFactory factory = DXGI.CreateFactory();
            IDXGIAdapter adapter = null;

            factory.EnumAdapters(0, out adapter);

            DXGI_SWAP_CHAIN_DESC swapChainDescription = new DXGI_SWAP_CHAIN_DESC
            {
                BufferCount = 1,
                BufferDesc  = new DXGI_MODE_DESC
                {
                    Format      = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM,
                    Height      = form.ClientSize.Height,
                    RefreshRate = new DXGI_RATIONAL
                    {
                        Denominator = 1,
                        Numerator   = 60
                    },

                    Scaling          = DXGI_MODE_SCALING.DXGI_MODE_SCALING_UNSPECIFIED,
                    ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER.DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,
                    Width            = form.ClientSize.Width
                },
                BufferUsage  = (int)DXGI_USAGE.DXGI_USAGE_RENDER_TARGET_OUTPUT,
                Flags        = 0,
                OutputWindow = form.Handle,
                SampleDesc   = new DXGI_SAMPLE_DESC
                {
                    Count   = 1,
                    Quality = 0
                },
                SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_DISCARD,
                Windowed   = true
            };

            ID3D11Device   device    = SlimDX.Direct3D11.Direct3D11.CreateDevice(adapter);
            IDXGISwapChain swapChain = null;

            factory.CreateSwapChain(device, swapChainDescription, out swapChain);

            ID3D11Texture2D        backbuffer = swapChain.GetBuffer <ID3D11Texture2D>(0);
            ID3D11RenderTargetView view       = null;

            device.CreateRenderTargetView(backbuffer, null, out view);

            ID3DBlob vertexShaderBytecode = ShaderCompiler.CompileFromString(File.ReadAllText("MiniTri11.fx"), "MiniTri11.fx", "VS", "vs_4_0");
            ID3DBlob pixelShaderBytecode  = ShaderCompiler.CompileFromString(File.ReadAllText("MiniTri11.fx"), "MiniTri11.fx", "PS", "ps_4_0");

            D3D11_INPUT_ELEMENT_DESC[] inputElements = new[] {
                new D3D11_INPUT_ELEMENT_DESC {
                    SemanticName = "POSITION", AlignedByteOffset = 0, SemanticIndex = 0, Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_FLOAT, InstanceDataStepRate = 0, InputSlot = 0, InputSlotClass = D3D11_INPUT_CLASSIFICATION.D3D11_INPUT_PER_VERTEX_DATA
                },
                new D3D11_INPUT_ELEMENT_DESC {
                    SemanticName = "COLOR", AlignedByteOffset = 16, SemanticIndex = 0, Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_FLOAT, InstanceDataStepRate = 0, InputSlot = 0, InputSlotClass = D3D11_INPUT_CLASSIFICATION.D3D11_INPUT_PER_VERTEX_DATA
                }
            };

            ID3DBlob inputSignature;

            ShaderCompiler.D3DGetInputSignatureBlob(vertexShaderBytecode.GetBufferPointer(), vertexShaderBytecode.GetBufferSize(), out inputSignature);
            ID3D11InputLayout inputLayout;

            device.CreateInputLayout(inputElements, inputElements.Length, inputSignature.GetBufferPointer(), inputSignature.GetBufferSize(), out inputLayout);

            ByteBuffer vertexData = new ByteBuffer(3 * 32);

            vertexData.Write(0 * Vector4.SizeInBytes, new Vector4(0.0f, 0.5f, 0.5f, 1.0f));
            vertexData.Write(1 * Vector4.SizeInBytes, new Vector4(1.0f, 0.0f, 0.0f, 1.0f));
            vertexData.Write(2 * Vector4.SizeInBytes, new Vector4(0.5f, -0.5f, 0.5f, 1.0f));
            vertexData.Write(3 * Vector4.SizeInBytes, new Vector4(0.0f, 1.0f, 0.0f, 1.0f));
            vertexData.Write(4 * Vector4.SizeInBytes, new Vector4(-0.5f, -0.5f, 0.5f, 1.0f));
            vertexData.Write(5 * Vector4.SizeInBytes, new Vector4(0.0f, 0.0f, 1.0f, 1.0f));

            D3D11_BUFFER_DESC vertexBufferDescription = new D3D11_BUFFER_DESC
            {
                BindFlags           = 1,      //vertex buffer
                ByteWidth           = 3 * 32,
                CPUAccessFlags      = 0,
                MiscFlags           = 0,
                Usage               = D3D11_USAGE.D3D11_USAGE_DEFAULT,
                StructureByteStride = 0
            };
            ID3D11Buffer           vertexBuffer;
            D3D11_SUBRESOURCE_DATA srd = new D3D11_SUBRESOURCE_DATA
            {
                pSysMem          = vertexData.Pin(),
                SysMemPitch      = 0,
                SysMemSlicePitch = 0
            };

            device.CreateBuffer(vertexBufferDescription, srd, out vertexBuffer);
            vertexData.Unpin();

            RenderLoop          loop    = new RenderLoop();
            ID3D11DeviceContext context = null;

            device.GetImmediateContext(out context);

            ID3D11VertexShader vertexShader;
            ID3D11PixelShader  pixelShader;

            device.CreateVertexShader(vertexShaderBytecode.GetBufferPointer(), vertexShaderBytecode.GetBufferSize(), null, out vertexShader);
            device.CreatePixelShader(pixelShaderBytecode.GetBufferPointer(), pixelShaderBytecode.GetBufferSize(), null, out pixelShader);
            context.IASetInputLayout(inputLayout);
            context.VSSetShader(vertexShader, null, 0);
            context.PSSetShader(pixelShader, null, 0);
            context.IASetPrimitiveTopology(4);            //triangle list
            context.IASetVertexBuffers(0, 1, new ID3D11Buffer[] { vertexBuffer }, new int[] { 32 }, new int[] { 0 });
            context.OMSetRenderTargets(1, new ID3D11RenderTargetView[] { view }, IntPtr.Zero);

            D3D11_VIEWPORT vp = new D3D11_VIEWPORT {
                Height   = form.ClientSize.Height,
                Width    = form.ClientSize.Width,
                TopLeftX = 0,
                TopLeftY = 0,
                MinDepth = 0.0f,
                MaxDepth = 1.0f
            };

            context.RSSetViewports(1, new D3D11_VIEWPORT [] { vp });

            loop.Run(form, () =>
            {
                var clearColor = new SlimDX.Color4 {
                    R = 0.0f, G = 0.0f, B = 0.0f, A = 1.0f
                };
                context.ClearRenderTargetView(view, clearColor);
                context.Draw(3, 0);
                swapChain.Present(0, 0);
            });

            view.ReleaseReference();
            backbuffer.ReleaseReference();
            swapChain.ReleaseReference();
            device.ReleaseReference();
            adapter.ReleaseReference();
            factory.ReleaseReference();
        }