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

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

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

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

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

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

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

            #endregion

            #region Render loop

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

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

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

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

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

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

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

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

            #region Direct3D Cleanup

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

            #endregion
        }
        private void CreateSwapChain()
        {
            var swapChainDescription = new SwapChainDescription1
            {
                Width             = _savedSize.Width,
                Height            = _savedSize.Height,
                Format            = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription
                {
                    Count   = 1,
                    Quality = 0,
                },
                Usage       = Usage.RenderTargetOutput,
                BufferCount = 1,
                SwapEffect  = SwapEffect.Discard,
            };

            using (var dxgiAdapter = Direct2D1Platform.DxgiDevice.Adapter)
                using (var dxgiFactory = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                {
                    _swapChain = CreateSwapChain(dxgiFactory, swapChainDescription);
                }
        }
        private static IDXGISwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, IntPtr windowHandle)
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1
            {
                Width             = presentationParameters.BackBufferWidth,
                Height            = presentationParameters.BackBufferHeight,
                SampleDescription = new SampleDescription(1, 0),
                Stereo            = presentationParameters.Stereo,
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = BufferCount,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.FlipSequential,
                Format            = (Format)presentationParameters.BackBufferFormat,
                Flags             = SwapChainFlags.None,
                AlphaMode         = AlphaMode.Unspecified
            };

            DXGI.CreateDXGIFactory2(false, out IDXGIFactory2 factory);
            using IDXGISwapChain1 tempSwapChain = factory.CreateSwapChainForHwnd(device.NativeDirectCommandQueue, windowHandle, swapChainDescription);
            factory.Dispose();

            return(tempSwapChain.QueryInterface <IDXGISwapChain3>());
        }
            /// <summary>
            /// Creates the swap chain description.
            /// </summary>
            /// <returns>A swap chain description</returns>
            /// <remarks>
            /// This method can be overloaded in order to modify default parameters.
            /// </remarks>
            protected virtual SwapChainDescription1 CreateSwapChainDescription()
            {
                var sampleCount   = 1;
                var sampleQuality = 0;
                // SwapChain description

                var desc = new SwapChainDescription1()
                {
                    Width  = Math.Max(1, TargetWidth),
                    Height = Math.Max(1, TargetHeight),
                    // B8G8R8A8_UNorm gives us better performance
                    Format            = Format,
                    Stereo            = false,
                    SampleDescription = new SampleDescription(sampleCount, sampleQuality),
                    Usage             = Usage.RenderTargetOutput,
                    BufferCount       = 2,
                    SwapEffect        = SwapEffect.FlipSequential,
                    Scaling           = Scaling.Stretch,
                    Flags             = SwapChainFlags.None
                };

                return(desc);
            }
Ejemplo n.º 5
0
        public MainWindow()
        {
            DataContext = _model = new MainWindowViewModel();

            _desc = new SwapChainDescription1()
            {
                BufferCount       = 1,
                Width             = (int)ClientSize.Width,
                Height            = (int)ClientSize.Height,
                Format            = Format.R8G8B8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            using (var factory = Direct2D1Platform.DxgiDevice.Adapter.GetParent <Factory2>())
            {
                _swapChain = new SwapChain1(factory, Direct2D1Platform.DxgiDevice, PlatformImpl?.Handle.Handle ?? IntPtr.Zero, ref _desc);
            }

            _deviceContext = new DeviceContext(Direct2D1Platform.Direct2D1Device, DeviceContextOptions.None)
            {
                DotsPerInch = new Size2F(96, 96)
            };

            CreateMesh();

            _view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);

            this.GetObservable(ClientSizeProperty).Subscribe(Resize);

            Resize(ClientSize);

            AvaloniaXamlLoader.Load(this);

            Background = Avalonia.Media.Brushes.Transparent;
        }
Ejemplo n.º 6
0
        private void HandleDeviceChangeEnd(object sender, EventArgs e)
        {
            var device = _graphicsDeviceManager.GraphicsDevice;

            var swapChain = (SwapChain)device.Presenter.NativePresenter;
            var d = swapChain.Description;

            var d3DDevice = (SharpDX.Direct3D11.Device)device;
            using (var dxgiDevice = d3DDevice.QueryInterface<Device3>())
            {
                var adapter = dxgiDevice.Adapter;
                var factory = adapter.GetParent<Factory2>();

                var description = new SwapChainDescription1
                                  {
                                      Width = d.ModeDescription.Width,
                                      Height = d.ModeDescription.Height,
                                      Format = d.ModeDescription.Format,
                                      Stereo = false,
                                      SampleDescription = new SampleDescription(1, 0),
                                      Usage = Usage.RenderTargetOutput,
                                      BufferCount = 2,
                                      SwapEffect = SwapEffect.FlipSequential,
                                      Flags = SwapChainFlags.ForegroundLayer,
                                      Scaling = Scaling.None,
                                      AlphaMode = AlphaMode.Premultiplied
                                  };

                // create the foreground swap chain for the core window
                using (var comWindow = new ComObject(Window.NativeWindow))
                    _foregroundChain = new SwapChain1(factory, (SharpDX.Direct3D11.Device)device, comWindow, ref description);

                // recreate the foreground render target
                using (var backBuffer = _foregroundChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0))
                    _foregroundRenderTarget = RenderTarget2D.New(device, backBuffer);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates the SwapChain object that is used on WinRT platforms.
        /// </summary>
        /// <param name="device">The device on which to create the SwapChain.</param>
        /// <param name="width">Width of the screen in pixels.</param>
        /// <param name="height">Height of the screen in pixels.</param>
        /// <param name="gfxConfig">Current graphics configuration.</param>
        internal static IDXGISwapChain1 CreateSwapChainForComposition(EngineDevice device, int width, int height, GraphicsViewConfiguration gfxConfig)
        {
            device.EnsureNotNull(nameof(device));
            width.EnsurePositiveOrZero(nameof(width));
            height.EnsurePositiveOrZero(nameof(height));
            gfxConfig.EnsureNotNull(nameof(gfxConfig));

            var desc = new SwapChainDescription1
            {
                Width             = width,
                Height            = height,
                Format            = GraphicsHelper.Internals.DEFAULT_TEXTURE_FORMAT,
                Stereo            = false,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.Backbuffer | Usage.RenderTargetOutput,
                BufferCount       = 2,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.FlipSequential,
                AlphaMode         = gfxConfig.AlphaEnabledSwapChain ? AlphaMode.Premultiplied : AlphaMode.Ignore
            };

            //Creates the swap chain for XAML composition
            return(device.Internals.FactoryDxgi.CreateSwapChainForComposition(device.Internals.DeviceD3D11_1, desc));
        }
Ejemplo n.º 8
0
        private static IDXGISwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, SwapChainPanel swapChainPanel)
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1
            {
                Width             = presentationParameters.BackBufferWidth,
                Height            = presentationParameters.BackBufferHeight,
                SampleDescription = new Vortice.DXGI.SampleDescription(1, 0),
                Stereo            = presentationParameters.Stereo,
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = BufferCount,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.FlipSequential,
                Format            = (Format)presentationParameters.BackBufferFormat.ToNonSRgb(),
                Flags             = SwapChainFlags.None,
                AlphaMode         = AlphaMode.Unspecified
            };

            swapChainDescription.AlphaMode = AlphaMode.Premultiplied;

            DXGI.CreateDXGIFactory2(false, out IDXGIFactory2 factory);
            Direct3DInterop.ISwapChainPanelNative nativePanel = (Direct3DInterop.ISwapChainPanelNative)swapChainPanel;
            using IDXGISwapChain1 tempSwapChain = factory.CreateSwapChainForComposition(device.DirectCommandQueue.NativeCommandQueue, swapChainDescription);
            factory.Dispose();

            IDXGISwapChain3 swapChain = tempSwapChain.QueryInterface <IDXGISwapChain3>();

            nativePanel.SetSwapChain(swapChain.NativePointer);

            swapChain.MatrixTransform = new Matrix3x2
            {
                M11 = 1.0f / swapChainPanel.CompositionScaleX,
                M22 = 1.0f / swapChainPanel.CompositionScaleY
            };

            return(swapChain);
        }
Ejemplo n.º 9
0
 public DXGISwapChain CreateSwapchain(IntPtr hWnd)
 {
     using (var adapter = DXGIDevice.Adapter)
         using (var factory2 = adapter.GetParent <Factory2>())
         {
             // SwapChain description
             var desc = new SwapChainDescription1
             {
                 Width             = 0,
                 Height            = 0,
                 Format            = Format.R8G8B8A8_UNorm,
                 Stereo            = false,
                 SampleDescription = new SampleDescription(1, 0),
                 Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                 BufferCount       = 1,
                 Scaling           = Scaling.Stretch,
                 SwapEffect        = SwapEffect.Discard,
                 AlphaMode         = AlphaMode.Unspecified,
                 Flags             = SwapChainFlags.None,
             };
             var swapchain = new SwapChain1(factory2, Device, hWnd, ref desc);
             return(new DXGISwapChain(swapchain));
         }
 }
        private SwapChain CreateSwapChainForWindowsRuntime()
        {
            bufferCount = 2;
            var description = new SwapChainDescription1
            {
                // Automatic sizing
                Width = Description.BackBufferWidth,
                Height = Description.BackBufferHeight,
                Format = (SharpDX.DXGI.Format)Description.BackBufferFormat.ToNonSRgb(),
                Stereo = false,
                SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultiSampleCount, 0),
                Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                // Use two buffers to enable flip effect.
                BufferCount = bufferCount,
                Scaling = SharpDX.DXGI.Scaling.Stretch,
                SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential,
            };

            SwapChain swapChain = null;
            switch (Description.DeviceWindowHandle.Context)
            {
                case Games.AppContextType.WindowsRuntime:
                {
                    var nativePanel = ComObject.As<ISwapChainPanelNative>(Description.DeviceWindowHandle.NativeHandle);
                    // Creates the swap chain for XAML composition
                    swapChain = new SwapChain1(GraphicsAdapterFactory.NativeFactory, GraphicsDevice.NativeDevice, ref description);

                    // Associate the SwapChainPanel with the swap chain
                    nativePanel.SwapChain = swapChain;
                    break;
                }
                default:
                    throw new NotSupportedException(string.Format("Window context [{0}] not supported while creating SwapChain", Description.DeviceWindowHandle.Context));
            }

            return swapChain;
        }
Ejemplo n.º 11
0
        private void InitSwapChain(int width, int height)
        {
            if (width <= 0 || height <= 0)
                throw new ArgumentException("panel must have a valid width or height");

            // Create swap chain for composition and bind to panel
            var desc = new SwapChainDescription1
                {
                    Width = width,
                    Height = height,
                    Format = Format.B8G8R8A8_UNorm,
                    Flags = SwapChainFlags.None,
                    BufferCount = 2,
                    AlphaMode = AlphaMode.Unspecified,
                    Stereo = false,
                    Scaling = Scaling.Stretch,
                    SampleDescription = { Count = 1, Quality = 0 },
                    SwapEffect = SwapEffect.FlipSequential,
                    Usage = Usage.RenderTargetOutput
                };

            _width = width;
            _height = height;

            var dxgiDev = ComObject.As<SharpDX.DXGI.Device1>(_device.NativePointer);
            var adapter = dxgiDev.Adapter;
            var fact = adapter.GetParent<SharpDX.DXGI.Factory2>();
            _swap = fact.CreateSwapChainForComposition(_device, ref desc, null);

            dxgiDev.MaximumFrameLatency = 1;
        }
Ejemplo n.º 12
0
 protected abstract SwapChain1 CreateSwapChain(Factory2 dxgiFactory, SwapChainDescription1 swapChainDesc);
Ejemplo n.º 13
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.SetViewports(viewport);
            }
        protected virtual void CreateSizeDependentResources()
        {
            // Ensure dependent objects have been released.
            d2dContext.Target = null;
            if (d2dTargetBitmap != null)
            {
                RemoveAndDispose(ref d2dTargetBitmap);
            }
            d3dContext.OutputMerger.SetRenderTargets((RenderTargetView)null);
            d3dContext.Flush();

            /*d3dContext.FinishCommandList(false);
             * d3dContext.li*/

            // Set render target size to the rendered size of the panel including the composition scale,
            // defaulting to the minimum of 1px if no size was specified.
            var scale              = Dpi / 96;
            var renderTargetWidth  = (int)(panel.ActualWidth * scale);
            var renderTargetHeight = (int)(panel.ActualHeight * scale);

            if (renderTargetWidth == 0 || renderTargetHeight == 0)
            {
                return;
            }

            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, renderTargetWidth, renderTargetHeight, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
            }
            else
            {
                var swapChainDesc = new SwapChainDescription1();
                swapChainDesc.Width  = renderTargetWidth;
                swapChainDesc.Height = renderTargetHeight;
                swapChainDesc.Format = Format.B8G8R8A8_UNorm;
                swapChainDesc.Stereo = new RawBool(false);
                swapChainDesc.SampleDescription.Count   = 1;
                swapChainDesc.SampleDescription.Quality = 0;
                swapChainDesc.Usage       = Usage.RenderTargetOutput;
                swapChainDesc.BufferCount = 2;
                swapChainDesc.SwapEffect  = SwapEffect.FlipSequential;
                swapChainDesc.Flags       = SwapChainFlags.None;
                swapChainDesc.AlphaMode   = AlphaMode.Unspecified; // Todo... May need to change
                //swapChainDesc.Scaling = Scaling.None;

                using (var dxgiDevice = d3dDevice.QueryInterface <global::SharpDX.DXGI.Device1>())
                {
                    var dxgiAdapter = dxgiDevice.Adapter;
                    var dxgiFactory = dxgiAdapter.GetParent <global::SharpDX.DXGI.Factory2>();

                    swapChain = Collect(new SwapChain1(dxgiFactory, d3dDevice, ref swapChainDesc, null));

                    // Counter act the composition scale of the render target as
                    // we already handle this in the platform window code.
                    using (var swapChain2 = swapChain.QueryInterface <SwapChain2>())
                    {
                        var inverseScale = new RawMatrix3x2();
                        inverseScale.M11           = 1.0f / scale;
                        inverseScale.M22           = 1.0f / scale;
                        swapChain2.MatrixTransform = inverseScale;
                    }

                    dxgiDevice.MaximumFrameLatency = 1;
                }

                // Associate the SwapChainBackgroundPanel with the swap chain
                using (var panelNative = ComObject.As <ISwapChainPanelNative>(panel))
                {
                    panelNative.SwapChain = swapChain;
                }
            }

            var bitmapProperties = new BitmapProperties1(
                new PixelFormat(Format.B8G8R8A8_UNorm, global::SharpDX.Direct2D1.AlphaMode.Premultiplied),
                Dpi,
                Dpi,
                BitmapOptions.Target | BitmapOptions.CannotDraw);

            using (var dxgiBackBuffer = swapChain.GetBackBuffer <Surface>(0))
            {
                d2dTargetBitmap   = Collect(new Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));
                d2dContext.Target = d2dTargetBitmap;
            }
        }
 public IDXGISwapChain1 CreateSwapChainForCompositionSurfaceHandle(IUnknown device, IntPtr surface, SwapChainDescription1 description, IDXGIOutput restrictToOutput)
 {
     return(CreateSwapChainForCompositionSurfaceHandle(device, surface, ref description, restrictToOutput));
 }
        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;
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Creates a swapchain associated to the specified HWND. This is applicable only for Desktop platform.
 /// </summary>
 /// <param name="factory">The DXGI Factory used to create the swapchain.</param>
 /// <param name="device">The associated device instance.</param>
 /// <param name="hwnd">The HWND of the window to which this swapchain is associated.</param>
 /// <param name="description">The swap chain description.</param>
 /// <param name="fullScreenDescription">The fullscreen description of the swap chain. Default is null.</param>
 /// <param name="restrictToOutput">The output to which this swap chain should be restricted. Default is null, meaning that there is no restriction.</param>
 public SwapChain1(Factory2 factory, ComObject device, IntPtr hwnd, ref SwapChainDescription1 description, SwapChainFullScreenDescription? fullScreenDescription = null, Output restrictToOutput = null)
     : base(IntPtr.Zero)
 {
     factory.CreateSwapChainForHwnd(device, hwnd, ref description, fullScreenDescription, restrictToOutput, this);
 }
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = new SwapChain1(dxgiFactory2, device, new ComObject(window), ref description);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer<Surface>(0);
            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Load bitmap images
            playerBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/player.png");
            terrainBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/terrain.png");

            // Create hue rotation effect
            hueRotationEffect = new SharpDX.Direct2D1.Effects.HueRotation(d2dContext);

            // Create image shadow effect
            shadowEffect = new SharpDX.Direct2D1.Effects.Shadow(d2dContext);

            // Create image transform effect
            affineTransformEffect = new SharpDX.Direct2D1.Effects.AffineTransform2D(d2dContext);
            affineTransformEffect.SetInputEffect(0, shadowEffect);
            affineTransformEffect.TransformMatrix = Matrix3x2.Translation(terrainBitmap.PixelSize.Width * 0.25f, terrainBitmap.PixelSize.Height * 0.25f);

            // Create composite effect
            compositeEffect = new SharpDX.Direct2D1.Effects.Composite(d2dContext);
            compositeEffect.InputCount = 2;
            compositeEffect.SetInputEffect(0, affineTransformEffect);

            // Create tiling brush for terrain bitmap
            terrainBrush = new ImageBrush(d2dContext, terrainBitmap, new ImageBrushProperties()
            {
                ExtendModeX = ExtendMode.Wrap,
                ExtendModeY = ExtendMode.Wrap,
                SourceRectangle = new RectangleF(0, 0, terrainBitmap.Size.Width, terrainBitmap.Size.Height),
            });

            // Create rendertarget for drawing the tiling brush
            brushTarget = new Bitmap1(d2dContext, new Size2((int)(terrainBitmap.Size.Width * 10), (int)terrainBitmap.Size.Height), new BitmapProperties1()
            {
                PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                BitmapOptions = BitmapOptions.Target
            });
        }
Ejemplo n.º 19
0
        public Form1()
        {
            InitializeComponent();
            // Store the vsync setting.
            VerticalSyncEnabled = false;
            width  = this.ClientSize.Width;
            height = this.ClientSize.Height;
            // Create a DirectX graphics interface factory.
            //var factory = new Factory1();

            // Use the factory to create an adapter for the primary graphics interface (video card).
            //var adapter = factory.GetAdapter1(0);
            //
            //// Get the primary adapter output (monitor).
            //var monitor = adapter.GetOutput(0);
            //
            //// Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
            //var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);


            Device = new SharpDX.Direct3D11.Device(
                SharpDX.Direct3D.DriverType.Hardware,
                DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport,
                new[] {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0,
            });
            // Query device for the Device1 interface (ID3D11Device1)
            var device = Device.QueryInterfaceOrNull <SharpDX.Direct3D11.Device1>();

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

            using (var dxgi = device.QueryInterface <SharpDX.DXGI.Device2>())
                using (var adapter = dxgi.Adapter)
                    using (var factory = adapter.GetParent <Factory2>())
                    {
                        var desc1 = new SwapChainDescription1()
                        {
                            Width             = this.ClientSize.Width,
                            Height            = this.ClientSize.Height,
                            Format            = Format.R8G8B8A8_UNorm,
                            Stereo            = false,
                            SampleDescription = new SampleDescription(1, 0),
                            Usage             = Usage.RenderTargetOutput,
                            BufferCount       = 1,
                            Scaling           = Scaling.Stretch,
                            SwapEffect        = SwapEffect.Discard,
                        };

                        SwapChain = new SwapChain1(factory,
                                                   device,
                                                   this.Handle,
                                                   ref desc1,
                                                   new SwapChainFullScreenDescription()
                        {
                            RefreshRate = new Rational(60, 1),
                            Scaling     = DisplayModeScaling.Centered,
                            Windowed    = true
                        },
                                                   // Restrict output to specific Output (monitor)
                                                   adapter.Outputs[0]);
                    }


            DeviceContext = Device.ImmediateContext;

            // Get the pointer to the back buffer.
            var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);

            // Create the render target view with the back buffer pointer.
            RenderTargetView = new RenderTargetView(Device, backBuffer);

            // Release pointer to the back buffer as we no longer need it.
            backBuffer.Dispose();

            // Initialize and set up the description of the depth buffer.
            var depthBufferDesc = new Texture2DDescription()
            {
                Width             = this.width,
                Height            = this.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
            };

            // Create the texture for the depth buffer using the filled out description.
            DepthStencilBuffer = new Texture2D(device, depthBufferDesc);

            // Initialize and set up the description of the stencil state.
            var 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);

            // Set the depth stencil state.
            DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState);

            // Initialize and set up the depth stencil view.
            var depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format      = Format.D24_UNorm_S8_UInt,
                Dimension   = DepthStencilViewDimension.Texture2DMultisampled,
                Texture2DMS = new DepthStencilViewDescription.Texture2DMultisampledResource()
                {
                }
            };

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

            // 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 = true,
                CullMode                = CullMode.None,
                DepthBias               = 0,
                DepthBiasClamp          = .0f,
                IsDepthClipEnabled      = true,
                FillMode                = FillMode.Solid,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled    = true,
                IsScissorEnabled        = false,
                SlopeScaledDepthBias    = .0f
            };

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


            // Now set the rasterizer state.
            DeviceContext.Rasterizer.State = RasterState;
            // Setup and create the viewport for rendering.
            DeviceContext.Rasterizer.SetViewport(0, 0, this.width, this.height, 0, 1);



            // Setup and create the projection matrix.
            //ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)this.width / (float)this.height), ScreenNear, ScreenDepth);
            ProjectionMatrix = Matrix.OrthoLH(this.width, this.height, 0, 1000);
            // Initialize the world matrix to the identity matrix.
            WorldMatrix = Matrix.Identity;
            initResources();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Create the swap chain used to store rendered scenes.
        /// </summary>
        /// <param name="windowHandle">The handle of the window that displays the game.</param>
        /// <param name="scWidth">The desired width of the swap chain.</param>
        /// <param name="scHeight">The desired height of the swap chain.</param>
        private void CreateSwapChain(IntPtr windowHandle, int scWidth, int scHeight)
        {
            SwapChainDescription1 scDescription = new SwapChainDescription1()
            {
                BufferCount = 1,
                Flags = SwapChainFlags.AllowModeSwitch,
                Format = Format.B8G8R8A8_UNorm,
                Height = scHeight,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Scaling = Scaling.Stretch,
                Stereo = false,
                SwapEffect = SwapEffect.Discard,
                Usage = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput,
                Width = scWidth,
            };
            using (var dxgiDevice = Device3D.QueryInterface<SharpDX.DXGI.Device2>())
            using (var dxgiAdapter = dxgiDevice.Adapter)
            using (var dxgiFactory = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
            using (var output = dxgiAdapter.Outputs.First())
            {
                // Create a swap chain for a desktop application
                SwapChain = ToDispose(new SwapChain1(
                    dxgiFactory,
                    Device3D,
                    windowHandle,
                    ref scDescription,
                    CreateFullScreenDescription(),
                    null));

                // Retrieve the list of supported display modes
                DisplayModeList = output.GetDisplayModeList(scDescription.Format, DisplayModeEnumerationFlags.Scaling);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device     = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width  = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                                                                 DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Create a solid color brush.
            solidBrush = new 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 LinearGradientBrush(d2dContext, new LinearGradientBrushProperties()
            {
                StartPoint = new Vector2(50, 0),
                EndPoint   = new Vector2(450, 0),
            },
                                                          new GradientStopCollection(d2dContext, new GradientStop[]
            {
                new GradientStop()
                {
                    Color    = Color.Blue,
                    Position = 0,
                },
                new GradientStop()
                {
                    Color    = Color.Green,
                    Position = 1,
                }
            }));

            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new RadialGradientBrush(d2dContext, new RadialGradientBrushProperties()
            {
                Center  = new Vector2(250, 525),
                RadiusX = 100,
                RadiusY = 100,
            },
                                                          new GradientStopCollection(d2dContext, new GradientStop[]
            {
                new GradientStop()
                {
                    Color    = Color.Yellow,
                    Position = 0,
                },
                new GradientStop()
                {
                    Color    = Color.Red,
                    Position = 1,
                }
            }));
        }
Ejemplo n.º 22
0
        public Renderer(Player player)
        {
            this.player = player;
            this.player.Control.Resize += ResizeBuffers;

            /* [Enable Debug Layer]
             *
             * 1) Enable native code debugging in your main project properties
             * 2) Requires SDK
             *
             * https://docs.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-devices-layers
             * https://docs.microsoft.com/en-us/windows/win32/direct3d11/using-the-debug-layer-to-test-apps
             *
             * For Windows 7 with Platform Update for Windows 7 (KB2670838) or Windows 8.x, to create a device that supports the debug layer, install the Windows Software Development Kit (SDK) for Windows 8.x to get D3D11_1SDKLayers.dll
             * For Windows 10, to create a device that supports the debug layer, enable the "Graphics Tools" optional feature. Go to the Settings panel, under System, Apps & features, Manage optional Features, Add a feature, and then look for "Graphics Tools".
             */

            //device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.VideoSupport | DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, ((SharpDX.Direct3D.FeatureLevel[]) Enum.GetValues(typeof(SharpDX.Direct3D.FeatureLevel))).Reverse().ToArray() );
            //deviceDbg = new DeviceDebug(device); // To Report Live Objects if required
            device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.VideoSupport | DeviceCreationFlags.BgraSupport, ((SharpDX.Direct3D.FeatureLevel[])Enum.GetValues(typeof(SharpDX.Direct3D.FeatureLevel))).Reverse().ToArray());
            using (var mthread = device.QueryInterface <Multithread>()) mthread.SetMultithreadProtected(true);

            using (var device2 = device.QueryInterface <SharpDX.DXGI.Device2>())
                using (var adapter = device2.Adapter)
                    using (var factory = adapter.GetParent <Factory2>())
                    {
                        device2.MaximumFrameLatency = 1; // Dont queue more than 1 frame

                        RendererInfo.Fill(this, adapter);
                        Log("\r\n" + Info.ToString());

                        // Swap Chain (TODO: Backwards compatibility)
                        var desc1 = new SwapChainDescription1()
                        {
                            BufferCount = device.FeatureLevel >= SharpDX.Direct3D.FeatureLevel.Level_11_0 ? 6 : 1, // Should be 1 for Win < 8 | HDR 60 fps requires 6 for non drops
                            SwapEffect  = device.FeatureLevel >= SharpDX.Direct3D.FeatureLevel.Level_12_0 ? SwapEffect.FlipSequential : SwapEffect.FlipDiscard,
                            //Format      = HDREnabled ? Format.R10G10B10A2_UNorm : Format.B8G8R8A8_UNorm, // Create always 10 bit and fallback to 8?
                            Format = Format.B8G8R8A8_UNorm,
                            //Format      = Format.R16G16B16A16_Float,
                            //Format      = Format.R10G10B10A2_UNorm,
                            Width     = player.Control.Width,
                            Height    = player.Control.Height,
                            AlphaMode = AlphaMode.Ignore,
                            Usage     = Usage.RenderTargetOutput,
                            Scaling   = Scaling.None,
                            //Flags = SwapChainFlags.AllowModeSwitch,
                            //Flags = 0 (or if already in fullscreen while recreating -> SwapChainFlags.AllowModeSwitch)
                            SampleDescription = new SampleDescription()
                            {
                                Count   = 1,
                                Quality = 0
                            }
                        };

                        swapChain = new SwapChain1(factory, device, this.player.Control.Handle, ref desc1);
                    }

            backBuffer   = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            rtv          = new RenderTargetView(device, backBuffer);
            context      = device.ImmediateContext;
            vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, vertexBufferData);

            SamplerState textureSampler = new SamplerState(device, new SamplerStateDescription()
            {
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                ComparisonFunction = Comparison.Never,
                Filter             = Filter.MinMagMipLinear,
                MaximumLod         = float.MaxValue
            });

            // Load Shaders Byte Code
            Dictionary <string, byte[]> Shaders = Shaders_v5.Shaders;

            if (device.FeatureLevel < SharpDX.Direct3D.FeatureLevel.Level_11_0)
            {
                Shaders = Shaders_v4.Shaders;
            }

            pixelShaders = new Dictionary <string, PixelShader>();
            foreach (var entry in Shaders)
            {
                if (entry.Key.ToString() == "VertexShader")
                {
                    vertexLayout = new InputLayout(device, entry.Value, inputElements);
                    vertexShader = new VertexShader(device, entry.Value);
                }
                else
                {
                    pixelShaders.Add(entry.Key.ToString(), new PixelShader(device, entry.Value));
                }
            }

            context.InputAssembler.InputLayout       = vertexLayout;
            context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <float>() * 5, 0));

            context.VertexShader.Set(vertexShader);
            context.PixelShader.SetSampler(0, textureSampler);

            if (player.Status == Status.Stopped)
            {
                GetViewport = new Viewport(0, 0, player.Control.Width, player.Control.Height);
                context.Rasterizer.SetViewport(0, 0, player.Control.Width, player.Control.Height);
            }
            else
            {
                SetViewport();
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug);

            // Query the default device for the supported device and context interfaces.
            device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            context = device.ImmediateContext.QueryInterface<DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Create the texture and render target that will hold our backbuffer.
            Texture2D backBufferTexture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            backBuffer = new RenderTargetView(device, backBufferTexture);

            backBufferTexture.Dispose();
        }
        public void CreateDirectXSwapChain(Adapter adapter)
        {
            var desc = adapter.Description;

            Debug.WriteLine(desc.Description);
            Debug.WriteLine($"vender = {desc.VendorId:X4}");
            Debug.WriteLine($"Shared Memory: {desc.SharedSystemMemory} bytes");
            Debug.WriteLine($"Video Memory: {desc.DedicatedVideoMemory} bytes");
            Debug.WriteLine($"device: {desc.DeviceId}");

            FeatureLevel[] featureLevels = new FeatureLevel[] {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
            };

            D3D11Device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.BgraSupport, featureLevels);

            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                // Double buffer.
                BufferCount = 2,
                // BGRA 32bit pixel format.
                Format = Format.B8G8R8A8_UNorm,
                // Unlike in CoreWindow swap chains, the dimensions must be set.
                Height = (int)(ActualHeight),
                Width  = (int)(ActualWidth),
                // Default multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // In case the control is resized, stretch the swap chain accordingly.
                Scaling = Scaling.Stretch,
                // No support for stereo display.
                Stereo = false,
                // Sequential displaying for double buffering.
                SwapEffect = SwapEffect.FlipSequential,
                // This swapchain is going to be used as the back buffer.
                Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
            };

            // 建立SwapChain
            using (SharpDX.DXGI.Device3 dxgiDevice3 = D3D11Device.QueryInterface <SharpDX.DXGI.Device3>()) {
                using (Factory2 dxgiFactory2 = dxgiDevice3.Adapter.GetParent <Factory2>()) {
                    using (SwapChain1 swapChain1 = new SwapChain1(dxgiFactory2, D3D11Device, ref swapChainDescription)) {
                        swapChain = swapChain1.QueryInterface <SwapChain>();
                    }
                }
            }

            // 把Xaml的SwapChainPanel與DirectX的SwapChain連結起來
            using (ISwapChainPanelNative swapChainPanelNative = ComObject.As <ISwapChainPanelNative>(this)) {
                swapChainPanelNative.SwapChain = swapChain;
            }

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

            var renderTarget = new RenderTargetView(D3D11Device, backBuffer);

            context = D3D11Device.ImmediateContext;
            // Clear Screen to Teel Blue.
            context.ClearRenderTargetView(renderTarget, new Color(0xFF887536));
            swapChain.Present(1, PresentFlags.None);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer<Surface>(0);
            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Create the DirectWrite factory objet.
            SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();

            // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs.
            textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f);

            // Create two TextLayout objects for rendering the moving text.
            textLayout1 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with snapped pixel boundaries.", textFormat, 400.0f, 200.0f);
            textLayout2 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with no snapped pixel boundaries.", textFormat, 400.0f, 200.0f);

            // Vertical offset for the moving text.
            layoutY = 0.0f;

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush = new SolidColorBrush(d2dContext, Color.Black);
        }
Ejemplo n.º 26
0
        static void Main()
        {
            #region d3d initialization
            // create winform
            Form1 form = new Form1();
            form.Text   = "D3D11.2Rendering";
            form.Width  = 800;
            form.Height = 600;

            // device & swapChain
            Device2    device;
            SwapChain1 swapChain;

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

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


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

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

                        swapChain.QueryInterfaceOrNull <SwapChain2>();
                    }

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

            #region render loop

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

            RenderLoop.Run(form, () =>
            {
                // Time in seconds
                var totalSeconds = clock.ElapsedTicks / clockFrequency;

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

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

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

                // clearcolor
                var lerpColor = SharpDX.Color.Lerp(Color.LightBlue, Color.DarkBlue, (float)(Math.Sin(totalSeconds) / 2.0 + 0.5));

                device.ImmediateContext.ClearRenderTargetView(renderTargetView, lerpColor);

                // rendering commands

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

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

            #region d3d cleanup
            // release
            renderTargetView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
            #endregion
        }
 public IDXGISwapChain1 CreateSwapChainForCompositionSurfaceHandle(IUnknown device, IntPtr surface, SwapChainDescription1 description)
 {
     return(CreateSwapChainForCompositionSurfaceHandle(device, surface, ref description, null));
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Creates a swapchain for DirectComposition API or WinRT XAML framework. This is applicable only for WinRT platform.
 /// </summary>
 /// <param name="factory">The DXGI Factory used to create the swapchain.</param>
 /// <param name="device">The associated device instance.</param>
 /// <param name="description">The swap chain description.</param>
 /// <param name="restrictToOutput">The output to which this swap chain should be restricted. Default is null, meaning that there is no restriction.</param>
 public SwapChain1(Factory2 factory, ComObject device, ref SwapChainDescription1 description, Output restrictToOutput = null)
     : base(IntPtr.Zero)
 {
     factory.CreateSwapChainForComposition(device, ref description, restrictToOutput, this);
 }
Ejemplo n.º 29
0
        private SwapChain CreateSwapChainForWinRT()
        {
            var coreWindow = Description.DeviceWindowHandle as CoreWindow;
            var swapChainBackgroundPanel = Description.DeviceWindowHandle as SwapChainBackgroundPanel;

            bufferCount = 2;
            var description = new SwapChainDescription1
            {
                // Automatic sizing
                Width = Description.BackBufferWidth,
                Height = Description.BackBufferHeight,
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // TODO: Check if we can use the Description.BackBufferFormat
                Stereo = false,
                SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultiSampleCount, 0),
                Usage = Description.RenderTargetUsage,
                // Use two buffers to enable flip effect.
                BufferCount = bufferCount,
                Scaling = SharpDX.DXGI.Scaling.Stretch,
                SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential,
            };

            if (coreWindow != null)
            {
                // Creates a SwapChain from a CoreWindow pointer
                using (var comWindow = new ComObject(coreWindow))
                    return new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, comWindow, ref description);
            }
            else if (swapChainBackgroundPanel != null)
            {
                var nativePanel = ComObject.As<ISwapChainBackgroundPanelNative>(swapChainBackgroundPanel);
                // Creates the swap chain for XAML composition
                var swapChain = new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, ref description);

                // Associate the SwapChainBackgroundPanel with the swap chain
                nativePanel.SwapChain = swapChain;
                return swapChain;
            }
            else
            {
#if DIRECTX11_2
                using (var comObject = new ComObject(Description.DeviceWindowHandle))
                {
                    var swapChainPanel = comObject.QueryInterfaceOrNull<ISwapChainPanelNative>();
                    if (swapChainPanel != null)
                    {
                        var swapChain = new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, ref description);
                        swapChainPanel.SwapChain = swapChain;
                        return swapChain;
                    }
                }
#endif
                throw new NotSupportedException();
            }
        }
Ejemplo n.º 30
0
 protected abstract SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 dxgiFactory, SwapChainDescription1 swapChainDesc);
Ejemplo n.º 31
0
        internal void Initialize()
        {
            adapter = DeviceEnumerator.GetAdapter(int.Parse(Settings.Model.AdapterId));
            output  = adapter.GetOutput1(Settings.Model.DisplayId);

            var scale        = Settings.Model.Scale;
            var bounds       = output.Description.DesktopBounds;
            var outputWidth  = bounds.Right - bounds.Left;
            var outputHeight = bounds.Bottom - bounds.Top;

            renderBounds = new Rectangle(0, 0, outputWidth / scale, outputHeight / scale);
            fpsLocation  = new RectangleF(renderBounds.Width - 92, renderBounds.Height - 19, renderBounds.Width, renderBounds.Height);

            device = new Device(adapter, DeviceCreationFlags.PreventAlteringLayerSettingsFromRegistry
                                | DeviceCreationFlags.SingleThreaded
                                | DeviceCreationFlags.BgraSupport);

            gpuTexture = new Texture2D(device, new TextureDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.None,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = outputWidth,
                Height            = outputHeight,
                OptionFlags       = ResourceOptionFlags.GenerateMipMaps,
                MipLevels         = (int)Math.Log2(scale) + 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Default
            });

            cpuTexture = new Texture2D(device, new TextureDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = renderBounds.Width,
                Height            = renderBounds.Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            });

            renderDescription = new SwapChainDescription1()
            {
                BufferCount       = 1,
                Width             = renderBounds.Width,
                Stereo            = false,
                Height            = renderBounds.Height,
                Format            = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.Discard
            };

            memBuffer       = new byte[renderBounds.Height * renderBounds.Width * 4];
            pinnedMemBuffer = GCHandle.Alloc(memBuffer, GCHandleType.Pinned);
            ptrMemBuffer    = pinnedMemBuffer.AddrOfPinnedObject();

            generateRecPoints();
            Settings.Model.PropertyChanged += LedsChanged;

            duplicator = output.DuplicateOutput(device);
            scaler     = new ShaderResourceView(device, gpuTexture);
        }
Ejemplo n.º 32
0
 private void CreateSwapChain(ref SwapChainDescription1 swapChainDescription1, Factory4 factory)
 {
     using (var sc1 = new SwapChain1(factory, commandQueue, form.Handle, ref swapChainDescription1))
         swapChain = Collect(sc1.QueryInterface <SwapChain3>());
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Creates a swapchain for DirectComposition API or WinRT XAML framework. This is applicable only for WinRT platform.
 /// </summary>
 /// <param name="factory">The DXGI Factory used to create the swapchain.</param>
 /// <param name="device">The associated device instance.</param>
 /// <param name="description">The swap chain description.</param>
 /// <param name="restrictToOutput">The output to which this swap chain should be restricted. Default is null, meaning that there is no restriction.</param>
 public SwapChain1(Factory2 factory, ComObject device, ref SwapChainDescription1 description, Output restrictToOutput = null)
     : base(IntPtr.Zero)
 {
     factory.CreateSwapChainForComposition(device, ref description, restrictToOutput, this);
 }
Ejemplo n.º 34
0
            private void CreateDeviceResources()
            {
                /// デフォルトDirect3Dデバイスの作成(取得)
                var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);
                /// サポートされているデバイスの取得
                var device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();

                /// COMを使って、D3Dデバイスオブジェクトに内在するのDXGIデバイスオブジェクトを取得する
                var dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>();
                /// アダプターの取得
                var dxgiAdapter = dxgiDevice2.Adapter;

                /// COMを使って、DXGIデバイスのファクトリーオブジェクトを取得
                SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();


                var desc = new SwapChainDescription1();

                desc.Width             = 480;
                desc.Height            = 640;
                desc.Format            = Format.B8G8R8A8_UNorm;
                desc.Stereo            = false;
                desc.SampleDescription = new SampleDescription(1, 0);
                desc.Usage             = Usage.RenderTargetOutput;
                desc.BufferCount       = 2;
                desc.Scaling           = Scaling.AspectRatioStretch;
                desc.SwapEffect        = SwapEffect.FlipSequential;
                desc.Flags             = SwapChainFlags.AllowModeSwitch;


                /// スワップチェインの作成
                this.swapChain = new SwapChain1(dxgiFactory2, device, new ComObject(mWindow), ref desc);


                /// Direct2Dデバイスの取得。
                var d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);

                /// Direct2Dデバイスのコンテキストを取得。
                this.d2dDeviceContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.None);

                /// スワップチェインからBuffer0のサーフェイスを取得。
                var backBuffer = this.swapChain.GetBackBuffer <Surface>(0);

                var displayInfo = DisplayInformation.GetForCurrentView();

                this.d2dTarget = new Bitmap1(this.d2dDeviceContext, backBuffer, new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), displayInfo.LogicalDpi
                                                                                                      , displayInfo.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw));

                this.PlayerScorer = new Scorer(this.d2dDeviceContext);
                this.updateList   = new List <IUpdatable>();

                /// 自機の作成
                this.playerShotManager = new PlayerShotManager(this.d2dDeviceContext);
                this.updateList.Add(this.playerShotManager);
                this.fighterDisplay = new Fighter(this.d2dDeviceContext, playerShotManager);
                this.fighterDisplay.SetPosition(540, 240);

                this.displayList = new List <IDrawable>();
                this.displayList.Add(this.fighterDisplay);
                this.displayList.Add(this.playerShotManager);
                this.targetManager = new RectTargetManager(this.d2dDeviceContext, this.playerShotManager, this.PlayerScorer);
                this.displayList.Add(this.targetManager);
                this.updateList.Add(this.targetManager);

                this.displayList.Add(this.PlayerScorer);

                /* 様々な初期化処理を以下に書く */
                var fighterPath = new PathGeometry(d2dDevice.Factory);

                var sink = fighterPath.Open();

                sink.BeginFigure(new Vector2(50f, 0f), FigureBegin.Filled);

                sink.AddLines(new SharpDX.Mathematics.Interop.RawVector2[]
                {
                    new Vector2(0f, 0f), new Vector2(0f, 50f), new Vector2(50f, 50f)
                });
                sink.EndFigure(FigureEnd.Closed);
                sink.Close();

                this.tFighterPath = new TransformedGeometry(d2dDevice.Factory, fighterPath, Matrix3x2.Identity);
                this.fighterBrush = new SolidColorBrush(d2dDeviceContext, Color.OrangeRed);

                this.fpsController = new FramePerSec(this.d2dDeviceContext);

                this.enemyShotManager = new EnemyShotManager(this.d2dDeviceContext, this.targetManager, this.fighterDisplay);

                this.displayList.Add(this.enemyShotManager);
                this.updateList.Add(this.enemyShotManager);
            }
Ejemplo n.º 35
0
        static void Main()
        {
            #region Direct3D 11.1 Initialization
            var form = new Form1();
            form.Text   = "D3D 11.1 App";
            form.Width  = 1920;
            form.Height = 1080;

            Device1 device11_1;
            SharpDX.DXGI.SwapChain1 swapChain1;

            // 1. Create a regular D3D11 device
            // Explicitly excluding feature levels below 11_0 as we will be using SM5.0 and other D3D11 features
#if DEBUG
            using (var device11 = new Device(SharpDX.Direct3D.DriverType.Hardware,
                                             DeviceCreationFlags.Debug,
                                             new[]
            {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0
            }))
            {
                // Query device for the device11_1 interface (ID3D11device11_1)
                device11_1 = device11.QueryInterfaceOrNull <Device1>();
                if (device11_1 == null)
                {
                    throw new NotSupportedException("SharpDX.Direct3D11.Device1 is not supported.");
                }
            }
#else
            using (var device11 = new Device(SharpDX.Direct3D.DriverType.Hardware,
                                             DeviceCreationFlags.None,
                                             new[]
            {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0
            }))
            {
                // Query device for the device11_1 interface (ID3D11device11_1)
                device11_1 = device11.QueryInterfaceOrNull <Device1>();
                if (device11_1 == null)
                {
                    throw new NotSupportedException("SharpDX.Direct3D11.Device1 is not supported.");
                }
            }
#endif



            // 2. Initialize Swap Chain
            // To create the swap chain, we need to first get a reference to SharpDX.DXGI.Factory2 instance
            // Rather than creating a new factory, we will use the one that was initialized internally to create our device

            using (var dxgi = device11_1.QueryInterface <SharpDX.DXGI.Device2>())
                using (var adapter = dxgi.Adapter)
                    using (var factory = adapter.GetParent <Factory2>())
                    {
                        // Describing the
                        var desc1 = new SwapChainDescription1()
                        {
                            Width             = form.ClientSize.Width,
                            Height            = form.ClientSize.Height,
                            Format            = Format.R8G8B8A8_UNorm,
                            Stereo            = false,
                            SampleDescription = new SampleDescription(1, 0),
                            Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput,
                            BufferCount       = 1,
                            Scaling           = SharpDX.DXGI.Scaling.Stretch,
                            SwapEffect        = SharpDX.DXGI.SwapEffect.Discard
                        };

                        swapChain1 = new SwapChain1(factory,
                                                    device11_1,
                                                    form.Handle,
                                                    ref desc1,
                                                    new SwapChainFullScreenDescription()
                        {
                            RefreshRate = new Rational(60, 1),
                            Scaling     = DisplayModeScaling.Centered,
                            Windowed    = true
                        },
                                                    adapter.Outputs[0]);
                    }

            // Retrieve references to backbuffer and rendertargetview
            var backBuffer       = Texture2D.FromSwapChain <Texture2D>(swapChain1, 0);
            var renderTargetView = new RenderTargetView(device11_1, backBuffer);

            #endregion



            #region RenderLoop

            var clock     = new System.Diagnostics.Stopwatch();
            var clockFreq = System.Diagnostics.Stopwatch.Frequency;         // Timer tick count per second
            clock.Start();

            var deltaTime = 0.0f;
            var fpsTimer  = new System.Diagnostics.Stopwatch();
            fpsTimer.Start();

            var fps       = 0.0;
            int fpsFrames = 0;

            SharpDX.Windows.RenderLoop.Run(form,
                                           () =>
            {
                // Time in seconds
                var totalSeconds = clock.ElapsedTicks / clockFreq;

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

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

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

                // Execute rendering commends here...
                device11_1.ImmediateContext1.ClearRenderTargetView(renderTargetView, Color.Green);

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

                // Calculate the time it took to render the frame
                deltaTime = (clock.ElapsedTicks / clockFreq) - totalSeconds;
            });

            #endregion



            #region Cleanup Direct3D 11.1

            renderTargetView.Dispose();
            backBuffer.Dispose();
            swapChain1.Dispose();
            device11_1.Dispose();

            #endregion

            /*
             * Application.EnableVisualStyles();
             * Application.SetCompatibleTextRenderingDefault(false);
             * Application.Run(new Form1());
             */
        }
Ejemplo n.º 36
0
 private void CreateSwapChain(ref SwapChainDescription1 swapChainDescription1, Factory4 factory)
 {
     using (var sc1 = new SwapChain1(factory, commandQueue, ref swapChainDescription1))
     {
         swapChain = Collect(sc1.QueryInterface<SwapChain3>());
         using (var comPtr = new ComObject(panel))
         {
             using (var native = comPtr.QueryInterface<ISwapChainPanelNative>())
             {
                 native.SwapChain = swapChain;
             }
         }
     }
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Creates a swapchain associated to the specified HWND. This is applicable only for Desktop platform.
 /// </summary>
 /// <param name="factory">The DXGI Factory used to create the swapchain.</param>
 /// <param name="device">The associated device instance.</param>
 /// <param name="hwnd">The HWND of the window to which this swapchain is associated.</param>
 /// <param name="description">The swap chain description.</param>
 /// <param name="fullScreenDescription">The fullscreen description of the swap chain. Default is null.</param>
 /// <param name="restrictToOutput">The output to which this swap chain should be restricted. Default is null, meaning that there is no restriction.</param>
 public SwapChain1(Factory2 factory, ComObject device, IntPtr hwnd, ref SwapChainDescription1 description, SwapChainFullScreenDescription?fullScreenDescription = null, Output restrictToOutput = null)
     : base(IntPtr.Zero)
 {
     factory.CreateSwapChainForHwnd(device, hwnd, ref description, fullScreenDescription, restrictToOutput, this);
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device     = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width  = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                                                                 DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Create the DirectWrite factory objet.
            SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();

            // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs.
            textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f);

            // Create two TextLayout objects for rendering the moving text.
            textLayout1 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with snapped pixel boundaries.", textFormat, 400.0f, 200.0f);
            textLayout2 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with no snapped pixel boundaries.", textFormat, 400.0f, 200.0f);

            // Vertical offset for the moving text.
            layoutY = 0.0f;

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush       = new SolidColorBrush(d2dContext, Color.Black);
        }
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer<Surface>(0);
            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Create a solid color brush.
            solidBrush = new 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 LinearGradientBrush(d2dContext, new LinearGradientBrushProperties()
                {
                    StartPoint = new Vector2(50, 0),
                    EndPoint = new Vector2(450, 0),
                },
                new GradientStopCollection(d2dContext, new GradientStop[]
                    {
                        new GradientStop()
                        {
                            Color = Color.Blue,
                            Position = 0,
                        },
                        new GradientStop()
                        {
                            Color = Color.Green,
                            Position = 1,
                        }
                    }));

            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new RadialGradientBrush(d2dContext, new RadialGradientBrushProperties()
                {
                    Center = new Vector2(250, 525),
                    RadiusX = 100,
                    RadiusY = 100,
                },
                new GradientStopCollection(d2dContext, new GradientStop[]
                {
                        new GradientStop()
                        {
                            Color = Color.Yellow,
                            Position = 0,
                        },
                        new GradientStop()
                        {
                            Color = Color.Red,
                            Position = 1,
                        }
                }));
        }
Ejemplo n.º 40
0
        private D3D11GraphicsDevice(Window?window, Size size)
        {
            Window = window;
            Size   = size;

            if (CreateDXGIFactory1(out Factory).Failure)
            {
                throw new InvalidOperationException("Cannot create IDXGIFactory1");
            }

            using (IDXGIAdapter1? adapter = GetHardwareAdapter())
            {
                DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport;
#if DEBUG
                if (SdkLayersAvailable())
                {
                    creationFlags |= DeviceCreationFlags.Debug;
                }
#endif

                if (D3D11CreateDevice(
                        adapter !,
                        DriverType.Unknown,
                        creationFlags,
                        s_featureLevels,
                        out ID3D11Device tempDevice, out FeatureLevel, out ID3D11DeviceContext tempContext).Failure)
                {
                    // If the initialization fails, fall back to the WARP device.
                    // For more information on WARP, see:
                    // http://go.microsoft.com/fwlink/?LinkId=286690
                    D3D11CreateDevice(
                        null,
                        DriverType.Warp,
                        creationFlags,
                        s_featureLevels,
                        out tempDevice, out FeatureLevel, out tempContext).CheckError();
                }

                Device        = tempDevice.QueryInterface <ID3D11Device1>();
                DeviceContext = tempContext.QueryInterface <ID3D11DeviceContext1>();
                tempContext.Dispose();
                tempDevice.Dispose();
            }

            if (window != null)
            {
                IntPtr hwnd = window.Handle;

                SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
                {
                    Width             = window.ClientSize.Width,
                    Height            = window.ClientSize.Height,
                    Format            = Format.R8G8B8A8_UNorm,
                    BufferCount       = FrameCount,
                    Usage             = Vortice.DXGI.Usage.RenderTargetOutput,
                    SampleDescription = new SampleDescription(1, 0),
                    Scaling           = Scaling.Stretch,
                    SwapEffect        = SwapEffect.FlipDiscard,
                    AlphaMode         = AlphaMode.Ignore
                };

                SwapChainFullscreenDescription fullscreenDescription = new SwapChainFullscreenDescription
                {
                    Windowed = true
                };

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

                BackBufferTexture = SwapChain.GetBuffer <ID3D11Texture2D>(0);
                RenderTargetView  = Device.CreateRenderTargetView(BackBufferTexture);
            }
            else
            {
                // Create offscreen texture
                OffscreenTexture = Device.CreateTexture2D(new Texture2DDescription(Format.R8G8B8A8_UNorm, Size.Width, Size.Height, 1, 1, BindFlags.ShaderResource | BindFlags.RenderTarget));
                RenderTargetView = Device.CreateRenderTargetView(OffscreenTexture);
            }
        }
Ejemplo n.º 41
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;
            }
        }
Ejemplo n.º 42
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);
            }
Ejemplo n.º 43
0
 private void CreateSwapChain(ref SwapChainDescription1 swapChainDescription1, Factory4 factory)
 {
     using (var sc1 = new SwapChain1(factory, commandQueue, form.Handle, ref swapChainDescription1))
         swapChain = Collect(sc1.QueryInterface<SwapChain3>());
 }
        /// <summary>
        /// Creates resources that depend on the current back buffer size.
        /// </summary>
        private void CreateSizeDependentResources()
        {
            this.ReleaseSizeDependentResources();

            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, (int)this.BackBufferSize.Width, (int)this.BackBufferSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
            }
            else
            {
                SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
                {
                    Width = (int)this.BackBufferSize.Width,
                    Height = (int)this.BackBufferSize.Height,
                    Format = Format.B8G8R8A8_UNorm,
                    Stereo = false,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                    BufferCount = 2,
                    Scaling = Scaling.Stretch,
                    SwapEffect = SwapEffect.FlipSequential,
                };

                using (SharpDX.DXGI.Device2 dxgiDevice2 = this.D3DDevice.QueryInterface<SharpDX.DXGI.Device2>())
                {
                    using (SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter)
                    {
                        using (SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
                        {
                            swapChain = new SwapChain1(dxgiFactory2, this.D3DDevice, ref swapChainDescription);

                            if (this.backgroundPanel != null)
                            {
                                nativeBackgroundPanel.SwapChain = swapChain;
                            }
                            else if (this.panel != null)
                            {
                                nativePanel.SwapChain = swapChain;
                            }

                            dxgiDevice2.MaximumFrameLatency = 1;
                        }
                    }
                }
            }

            this.BackBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            this.BackBufferView = new RenderTargetView(this.D3DDevice, this.BackBuffer);
            this.UpdateBackBufferSize();

            using (Texture2D depthBuffer = new Texture2D(this.D3DDevice, new Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)this.BackBufferSize.Width,
                Height = (int)this.BackBufferSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags = BindFlags.DepthStencil,
            }))
            {
                this.DepthStencilView = new DepthStencilView(this.D3DDevice, depthBuffer, new DepthStencilViewDescription()
                {
                    Dimension = DepthStencilViewDimension.Texture2D
                });
            }

            ViewportF viewport = new ViewportF(0, 0, (float)this.BackBufferSize.Width, (float)this.BackBufferSize.Height, 0.0f, 1.0f);
            this.D3DContext.Rasterizer.SetViewport(viewport);
        }
Ejemplo n.º 45
0
 protected override SwapChain1 CreateSwapChain(Factory2 dxgiFactory, SwapChainDescription1 swapChainDesc)
 {
     return(new SwapChain1(dxgiFactory, DxgiDevice, _window.Handle, ref swapChainDesc));
 }
Ejemplo n.º 46
0
        public static void Run()
        {
            var featureLevels = new[]
            {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0
            };
            const DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug;

            const int width  = 640;
            const int height = 480;

            using (var form = new RenderForm
            {
                Width = width,
                Height = height
            })
            {
                var swapChainDescription = new SwapChainDescription1
                {
                    Width             = form.ClientSize.Width,
                    Height            = form.ClientSize.Height,
                    Format            = Format.B8G8R8A8_UNorm,
                    Stereo            = false,
                    SampleDescription = new SampleDescription(4, 4),
                    Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                    BufferCount       = 1,
                    Scaling           = Scaling.Stretch,
                    SwapEffect        = SwapEffect.Discard,
                    Flags             = SwapChainFlags.AllowModeSwitch
                };
                var swapChainFullScreenDescription = new SwapChainFullScreenDescription
                {
                    RefreshRate = new Rational(60, 1),
                    Scaling     = DisplayModeScaling.Centered,
                    Windowed    = true
                };

                var samplerStateDescription = new SamplerStateDescription
                {
                    AddressU = TextureAddressMode.Wrap,
                    AddressV = TextureAddressMode.Wrap,
                    AddressW = TextureAddressMode.Wrap,
                    Filter   = Filter.MinMagMipLinear
                };
                var rasterizerStateDescription = RasterizerStateDescription.Default();
                rasterizerStateDescription.IsFrontCounterClockwise = true;

                // Set up the graphics devices
                using (var device0 = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags, featureLevels))
                    using (var device1 = device0.QueryInterface <SharpDX.Direct3D11.Device1>())
                        using (var context = device0.ImmediateContext.QueryInterface <DeviceContext1>())


                            // Create shaders and related resources
                            using (var vertexShaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", ShaderFlags.Debug))
                                using (var vertexShader = new VertexShader(device1, vertexShaderBytecode))
                                    using (var pixelShaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", ShaderFlags.Debug))
                                        using (var pixelShader = new PixelShader(device1, pixelShaderBytecode))
                                            using (var inputLayout = new InputLayout(device1, ShaderSignature.GetInputSignature(vertexShaderBytecode), new[]
                                            {
                                                new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0),
                                                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                                                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),
                                            }))
                                                using (var worldViewProjectionBuffer = new SharpDX.Direct3D11.Buffer(device1, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0))
                                                    using (var texture = TextureLoader.CreateTexture2DFromBitmap(device1, TextureLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), "text.png")))
                                                        using (ShaderResourceView textureView = new ShaderResourceView(device1, texture))
                                                            using (var samplerState = new SamplerState(device1, samplerStateDescription))

                                                                // Prepare rendering targets and related resources
                                                                using (var dxgiDevice2 = device1.QueryInterface <SharpDX.DXGI.Device2>())
                                                                    using (var dxgiFactory2 = dxgiDevice2.Adapter.GetParent <Factory2>())
                                                                        using (var swapChain = new SwapChain1(dxgiFactory2, device1, form.Handle, ref swapChainDescription, swapChainFullScreenDescription))
                                                                            using (var backBuffer = SharpDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0))
                                                                                using (var rasterizerState = new RasterizerState(device1, rasterizerStateDescription))
                                                                                    using (var renderTargetView = new RenderTargetView(device1, backBuffer))
                                                                                    {
                                                                                        var viewport = new ViewportF(0, 0, backBuffer.Description.Width, backBuffer.Description.Height);
                                                                                        context.Rasterizer.SetViewport(viewport);
                                                                                        context.Rasterizer.State = rasterizerState;

                                                                                        var depthBufferDescription = new Texture2DDescription
                                                                                        {
                                                                                            Format            = Format.D32_Float_S8X24_UInt,
                                                                                            ArraySize         = 1,
                                                                                            MipLevels         = 1,
                                                                                            Width             = backBuffer.Description.Width,
                                                                                            Height            = backBuffer.Description.Height,
                                                                                            SampleDescription = swapChain.Description.SampleDescription,
                                                                                            BindFlags         = BindFlags.DepthStencil,
                                                                                        };
                                                                                        var depthStencilViewDescription = new DepthStencilViewDescription
                                                                                        {
                                                                                            Dimension = swapChain.Description.SampleDescription.Count > 1 || swapChain.Description.SampleDescription.Quality > 0
                            ? DepthStencilViewDimension.Texture2DMultisampled
                            : DepthStencilViewDimension.Texture2D
                                                                                        };
                                                                                        var depthStencilStateDescription = new DepthStencilStateDescription
                                                                                        {
                                                                                            IsDepthEnabled   = true,
                                                                                            DepthComparison  = Comparison.Less,
                                                                                            DepthWriteMask   = DepthWriteMask.All,
                                                                                            IsStencilEnabled = false,
                                                                                            StencilReadMask  = 0xff,
                                                                                            StencilWriteMask = 0xff,
                                                                                            FrontFace        = new DepthStencilOperationDescription
                                                                                            {
                                                                                                Comparison         = Comparison.Always,
                                                                                                PassOperation      = StencilOperation.Keep,
                                                                                                FailOperation      = StencilOperation.Keep,
                                                                                                DepthFailOperation = StencilOperation.Increment
                                                                                            },
                                                                                            BackFace = new DepthStencilOperationDescription
                                                                                            {
                                                                                                Comparison         = Comparison.Always,
                                                                                                PassOperation      = StencilOperation.Keep,
                                                                                                FailOperation      = StencilOperation.Keep,
                                                                                                DepthFailOperation = StencilOperation.Decrement
                                                                                            }
                                                                                        };

                                                                                        using (var depthBuffer = new Texture2D(device1, depthBufferDescription))
                                                                                            using (var depthStencilView = new DepthStencilView(device1, depthBuffer, depthStencilViewDescription))
                                                                                                using (var depthStencilState = new DepthStencilState(device1, depthStencilStateDescription))
                                                                                                {
                                                                                                    context.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);
                                                                                                    context.OutputMerger.DepthStencilState = depthStencilState;
                                                                                                    context.InputAssembler.InputLayout     = inputLayout;
                                                                                                    context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);
                                                                                                    context.VertexShader.Set(vertexShader);
                                                                                                    context.PixelShader.Set(pixelShader);
                                                                                                    context.PixelShader.SetShaderResource(0, textureView);
                                                                                                    context.PixelShader.SetSampler(0, samplerState);

                                                                                                    form.Show();

                                                                                                    var cameraPosition      = new Vector3(1.5f, 1.8f, -3);
                                                                                                    var cameraTarget        = Vector3.Zero;
                                                                                                    var cameraUp            = Vector3.UnitY;
                                                                                                    var worldMatrix         = Matrix.Identity;
                                                                                                    var viewMatrix          = Matrix.LookAtLH(cameraPosition, cameraTarget, cameraUp);                                                        // reorient everything to camera space
                                                                                                    var projectionMatrix    = Matrix.PerspectiveFovLH((float)Math.PI / 3f, form.ClientSize.Width / (float)form.ClientSize.Height, .5f, 100f); // create a generic perspective projection matrix
                                                                                                    var viewProjection      = Matrix.Multiply(viewMatrix, projectionMatrix);                                                                  // apply the perspective projection to the view matrix so that we're performing both operations
                                                                                                    var worldViewProjection = worldMatrix * viewProjection;                                                                                   // include world translation with the view projection matrix
                                                                                                    worldViewProjection.Transpose();

                                                                                                    var model = GetCubeModel();
                                                                                                    using (var vertexBuffer = CreateBuffer(device1, BindFlags.VertexBuffer, model.Vertices))
                                                                                                        using (var indexBuffer = CreateBuffer(device1, BindFlags.IndexBuffer, model.Triangles))
                                                                                                        {
                                                                                                            var vertexBufferBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vertex>(), 0);
                                                                                                            context.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
                                                                                                            context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
                                                                                                            context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                                                                                                            RenderLoop.Run(form, () =>
                                                                                                            {
                                                                                                                context.ClearRenderTargetView(renderTargetView, Color.CornflowerBlue);
                                                                                                                context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);

                                                                                                                context.DrawIndexed(model.Triangles.Length * 3, 0, 0);

                                                                                                                swapChain.Present(1, PresentFlags.None);
                                                                                                            });
                                                                                                        }
                                                                                                }
                                                                                    }
            }
        }
Ejemplo n.º 47
0
        private SwapChain CreateSwapChainForUWP()
        {
            bufferCount = 2;
            var description = new SwapChainDescription1
            {
                // Automatic sizing
                Width             = Description.BackBufferWidth,
                Height            = Description.BackBufferHeight,
                Format            = (SharpDX.DXGI.Format)Description.BackBufferFormat.ToNonSRgb(),
                Stereo            = false,
                SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultisampleCount, 0),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                // Use two buffers to enable flip effect.
                BufferCount = bufferCount,
                Scaling     = SharpDX.DXGI.Scaling.Stretch,
                SwapEffect  = SharpDX.DXGI.SwapEffect.FlipSequential,
            };

            SwapChain swapChain = null;

            switch (Description.DeviceWindowHandle.Context)
            {
            case Games.AppContextType.UWPXaml:
            {
                var nativePanel = ComObject.As <ISwapChainPanelNative>(Description.DeviceWindowHandle.NativeWindow);

                // Creates the swap chain for XAML composition
                swapChain = new SwapChain1(GraphicsAdapterFactory.NativeFactory, GraphicsDevice.NativeDevice, ref description);

                // Associate the SwapChainPanel with the swap chain
                nativePanel.SwapChain = swapChain;

                break;
            }

            case Games.AppContextType.UWPCoreWindow:
            {
                using (var dxgiDevice = GraphicsDevice.NativeDevice.QueryInterface <SharpDX.DXGI.Device2>())
                {
                    // 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.
                    dxgiDevice.MaximumFrameLatency = 1;

                    // Next, get the parent factory from the DXGI Device.
                    using (var dxgiAdapter = dxgiDevice.Adapter)
                        using (var dxgiFactory = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                            // Finally, create the swap chain.
                            using (var coreWindow = new SharpDX.ComObject(Description.DeviceWindowHandle.NativeWindow))
                            {
                                swapChain = new SharpDX.DXGI.SwapChain1(dxgiFactory
                                                                        , GraphicsDevice.NativeDevice, coreWindow, ref description);
                            }
                }

                break;
            }

            default:
                throw new NotSupportedException(string.Format("Window context [{0}] not supported while creating SwapChain", Description.DeviceWindowHandle.Context));
            }

            return(swapChain);
        }
Ejemplo n.º 48
0
        void InitializeDirect2D()
        {
            d3dDevice = new D3D.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport);
            dxgiDevice = d3dDevice.QueryInterface<DXGI.Device1>();
            var desc = new SwapChainDescription1()
            {
                Width = 0,
                Height = 0,
                Format = Format.B8G8R8A8_UNorm,
                Stereo = false,
                SampleDescription = new SampleDescription(1, 0),
                Usage = Usage.RenderTargetOutput,
                BufferCount = 3,
                Scaling = Scaling.None,
                SwapEffect = SwapEffect.FlipSequential,
                Flags = SwapChainFlags.None
            };
            DXGI.Factory2 dxgiFactory = dxgiDevice.Adapter.GetParent<DXGI.Factory2>();
            swapChain = new SwapChain1(dxgiFactory, d3dDevice, Child.Handle, ref desc);
            swapChain.BackgroundColor = Color4.White;
            dxgiFactory.Dispose();

            d2dFactory = new D2D.Factory1(FactoryType.SingleThreaded);
            d2dDevice = new D2D.Device(d2dFactory, dxgiDevice);
            d2dDeviceContext = new D2D.DeviceContext(d2dDevice, DeviceContextOptions.None);
            d2dDeviceContext.TextAntialiasMode = TextAntialiasMode.Cleartype;
            //d2dDeviceContext.DotsPerInch = new Size2F(96, 96);
            var props = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
                d2dDeviceContext.DotsPerInch.Width,
                d2dDeviceContext.DotsPerInch.Height,
                BitmapOptions.Target | BitmapOptions.CannotDraw);
            Surface1 dxgiSurface = swapChain.GetBackBuffer<Surface1>(0);
            d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props);
            dxgiSurface.Dispose();
            d2dDeviceContext.Target = d2dSurface;

            VertexFillBrush = new SolidColorBrush(d2dDeviceContext, new Color4(1, 0.5f, 0, 1));
            VertexDrawBrush = new SolidColorBrush(d2dDeviceContext, new Color4(0.2f, 0.2f, 0.2f, 1));
            EdgeDrawBrush = new SolidColorBrush(d2dDeviceContext, Color4.Black);
            RasterDrawBrush = new SolidColorBrush(d2dDeviceContext, new Color4(0.5f, 0.5f, 0.5f, 1));
        }