Exemple #1
0
// ReSharper restore InconsistentNaming

        static CompositionEngine()
        {
            _wicFactory    = new SharpDX.WIC.ImagingFactory();
            _dWriteFactory = new SharpDX.DirectWrite.Factory();

            var d3DDevice = new SharpDX.Direct3D11.Device(
                DriverType.Hardware,
                DeviceCreationFlags.BgraSupport
#if DEBUG
                | DeviceCreationFlags.Debug
#endif
                ,
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3,
                FeatureLevel.Level_9_2,
                FeatureLevel.Level_9_1
                );

            var dxgiDevice = ComObject.As <SharpDX.DXGI.Device>(d3DDevice.NativePointer);
            //new SharpDX.DXGI.Device2(d3DDevice.NativePointer);
            var d2DDevice = new SharpDX.Direct2D1.Device(dxgiDevice);

            _d2DFactory                   = d2DDevice.Factory;
            _d2DDeviceContext             = new SharpDX.Direct2D1.DeviceContext(d2DDevice, D2D.DeviceContextOptions.None);
            _d2DDeviceContext.DotsPerInch = new DrawingSizeF(
                Windows.Graphics.Display.DisplayProperties.LogicalDpi,
                Windows.Graphics.Display.DisplayProperties.LogicalDpi);
        }
Exemple #2
0
        public static T AttachAs <T>(IntPtr pointer) where T : ComObject
        {
            var comObject = ComObject.As <T>(pointer);

            Marshal.AddRef(pointer);
            return(comObject);
        }
        public Direct2DFactories()
        {
            WICFactory = new WIC.ImagingFactory();
            DWFactory  = new DW.Factory();

            var d3DDevice = new D3D11.Device(
                D3D.DriverType.Hardware,
                D3D11.DeviceCreationFlags.BgraSupport
#if DEBUG
                | D3D11.DeviceCreationFlags.Debug
#endif
                ,
                D3D.FeatureLevel.Level_11_1,
                D3D.FeatureLevel.Level_11_0,
                D3D.FeatureLevel.Level_10_1,
                D3D.FeatureLevel.Level_10_0,
                D3D.FeatureLevel.Level_9_3,
                D3D.FeatureLevel.Level_9_2,
                D3D.FeatureLevel.Level_9_1
                );

            var dxgiDevice = ComObject.As <SharpDX.DXGI.Device> (d3DDevice.NativePointer);
            var d2DDevice  = new D2D1.Device(dxgiDevice);

            D2DFactory = d2DDevice.Factory;
            //_d2DDeviceContext = new D2D1.DeviceContext (d2DDevice, D2D1.DeviceContextOptions.None);
            //var dpi = DisplayDpi;
            //_d2DDeviceContext.DotsPerInch = new Size2F (dpi, dpi);
        }
Exemple #4
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;
        }
 /// <summary>
 /// Initialzes a new <see cref="SurfaceImageSourceTarget"/> instance.
 /// </summary>
 /// <param name="pixelWidth">Width of the target in pixels</param>
 /// <param name="pixelHeight">Height of the target in pixels</param>
 public SurfaceImageSourceTarget(int pixelWidth, int pixelHeight, bool supportOpacity = false)
 {
     this.pixelWidth          = pixelWidth;
     this.pixelHeight         = pixelHeight;
     this.surfaceImageSource  = new SurfaceImageSource(pixelWidth, pixelHeight, supportOpacity);
     surfaceImageSourceNative = Collect(ComObject.As <SharpDX.DXGI.ISurfaceImageSourceNative>(surfaceImageSource));
 }
        void CreateSwapChain()
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 2,
                SwapEffect        = SwapEffect.FlipSequential,
                Stereo            = false,
                SampleDescription = new SampleDescription(1, 0),
                Scaling           = Scaling.Stretch,
                Format            = Format.R8G8B8A8_UNorm,
                Height            = 1080,
                Width             = 1920,
            };

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

            // 把Xaml的SwapChainPanel與DirectX的SwapChain連結起來
            using (ISwapChainPanelNative swapChainPanelNative = ComObject.As <ISwapChainPanelNative>(this)) {
                swapChainPanelNative.SwapChain = swapChain1;
                SetViewport();
            }
        }
Exemple #7
0
 /// <summary>
 /// Initialzes a new <see cref="SurfaceImageSourceTarget"/> instance.
 /// </summary>
 /// <param name="pixelWidth">Width of the target in pixels</param>
 /// <param name="pixelHeight">Height of the target in pixels</param>
 public SurfaceImageSourceTarget(int pixelWidth, int pixelHeight)
 {
     this.pixelWidth          = pixelWidth;
     this.pixelHeight         = pixelHeight;
     this.surfaceImageSource  = new SurfaceImageSource(pixelWidth, pixelHeight);
     surfaceImageSourceNative = ComObject.As <SharpDX.DXGI.ISurfaceImageSourceNative>(surfaceImageSource);
 }
        /// <summary>
        /// Initializes a new <see cref="SwapChainPanelTarget"/> instance
        /// </summary>
        /// <param name="panel">The <see cref="SwapChainPanel"/> to render to</param>
        public SwapChainPanelTarget(SwapChainPanel panel)
        {
            this.panel = panel;

            // Gets the native panel
            nativePanel        = ComObject.As <ISwapChainPanelNative>(panel);
            panel.SizeChanged += panel_SizeChanged;
        }
Exemple #9
0
 /// <summary>
 ///     Initializes a new <see cref="SurfaceImageSourceTarget" /> instance.
 /// </summary>
 /// <param name="pixelWidth">Width of the target in pixels</param>
 /// <param name="pixelHeight">Height of the target in pixels</param>
 public SurfaceImageSourceTarget(int pixelWidth, int pixelHeight, bool supportOpacity = false)
 {
     this._pixelWidth          = pixelWidth;
     this._pixelHeight         = pixelHeight;
     _surfaceImageSource       = new SurfaceImageSource(pixelWidth, pixelHeight, supportOpacity);
     _surfaceImageSourceNative = Collect(ComObject.As <ISurfaceImageSourceNative>(_surfaceImageSource));
     _viewDatas[0]             = Collect(new SurfaceViewData());
     _viewDatas[1]             = Collect(new SurfaceViewData());
 }
Exemple #10
0
 /// <summary>
 /// Initialzes a new <see cref="SurfaceImageSourceTarget"/> instance.
 /// </summary>
 /// <param name="pixelWidth">Width of the target in pixels</param>
 /// <param name="pixelHeight">Height of the target in pixels</param>
 public SurfaceImageSourceTarget(int pixelWidth, int pixelHeight, bool supportOpacity = false)
 {
     this.pixelWidth          = pixelWidth;
     this.pixelHeight         = pixelHeight;
     this.surfaceImageSource  = new SurfaceImageSource(pixelWidth, pixelHeight, supportOpacity);
     surfaceImageSourceNative = ToDispose(ComObject.As <SharpDX.DXGI.ISurfaceImageSourceNative>(surfaceImageSource));
     viewDatas[0]             = new SurfaceViewData();
     viewDatas[1]             = new SurfaceViewData();
 }
 /// <summary>
 /// Initialzes a new <see cref="SurfaceImageSourceTarget"/> instance.
 /// </summary>
 /// <param name="pixelWidth">Width of the target in pixels</param>
 /// <param name="pixelHeight">Height of the target in pixels</param>
 /// <param name="isOpaque">Indicates whether the surface is expected to be always opaque (without transparency support).</param>
 public SurfaceImageSourceTarget(int pixelWidth, int pixelHeight, bool isOpaque = false)
 {
     this.pixelWidth          = pixelWidth;
     this.pixelHeight         = pixelHeight;
     this.surfaceImageSource  = new SurfaceImageSource(pixelWidth, pixelHeight, isOpaque);
     surfaceImageSourceNative = ComObject.As <SharpDX.DXGI.ISurfaceImageSourceNative>(surfaceImageSource);
     viewDatas[0]             = new SurfaceViewData();
     viewDatas[1]             = new SurfaceViewData();
 }
        public void CreateDirectXSwapChain()
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                // Want Transparency.
                AlphaMode = SharpDX.DXGI.AlphaMode.Premultiplied,
                // 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,
            };

            using (SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport))
            {
                this.device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device2>();
            }

            // Save the context instance
            //this.d3d11DC = this.device.ImmediateContext2;

            using (SharpDX.DXGI.Device3 dxgiDevice3 = device.QueryInterface <SharpDX.DXGI.Device3>())
            {
                using (SharpDX.DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent <SharpDX.DXGI.Factory3>())
                {
                    using (SwapChain1 swapChain1 = new SwapChain1(dxgiFactory3, device, ref swapChainDescription))
                    {
                        swapChain = swapChain1.QueryInterface <SwapChain2>();
                    }
                }
            }

            using (ISwapChainPanelNative nativeObject = ComObject.As <ISwapChainPanelNative>(this))
            {
                nativeObject.SwapChain = swapChain;
            }

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

            using (var surface = backBufferTexture.QueryInterface <Surface2>())
            {
                d2d1DC = new DeviceContext(surface);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SwapChainPanelWrapper"/> class.
        /// </summary>
        /// <param name="bgPanel">The panel for which to create the wrapper.</param>
        public SwapChainPanelWrapper(SwapChainBackgroundPanel bgPanel)
            : this()
        {
            m_bgPanel       = bgPanel;
            m_bgPanelNative = ComObject.As <DXGI.ISwapChainBackgroundPanelNative>(m_bgPanel);

            m_bgPanel.SizeChanged += OnAnyPanel_SizeChanged;
            m_bgPanel.Loaded      += OnAnyPanel_Loaded;
            m_bgPanel.Unloaded    += OnAnyPanel_Unloaded;
        }
Exemple #14
0
        public D3DAppSwapChainBackgroundTarget(SwapChainBackgroundPanel panel)
        {
            this.backgroundPanel = panel;

            nativeBackgrounPanel              = ToDispose(ComObject.As <SharpDX.DXGI.ISwapChainBackgroundPanelNative>(panel));
            this.backgroundPanel.SizeChanged += (sender, args) =>
            {
                SizeChanged();
            };
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SwapChainPanelWrapper"/> class.
        /// </summary>
        /// <param name="panel">The panel for which to create the wrapper.</param>
        public SwapChainPanelWrapper(SwapChainPanel panel)
            : this()
        {
            m_panel       = panel;
            m_panelNative = ComObject.As <DXGI.ISwapChainPanelNative>(m_panel);

            m_panel.SizeChanged             += OnAnyPanel_SizeChanged;
            m_panel.Loaded                  += OnAnyPanel_Loaded;
            m_panel.Unloaded                += OnAnyPanel_Unloaded;
            m_panel.CompositionScaleChanged += OnPanelCompositionScaleChanged;
        }
        /// <summary>
        /// Initializes a new <see cref="SwapChainBackgroundPanelTarget"/> instance
        /// </summary>
        /// <param name="panel">The <see cref="SwapChainBackgroundPanel"/> to render to</param>
        public SwapChainBackgroundPanelTarget(SwapChainBackgroundPanel panel)
        {
            this.panel = panel;

            // Gets the native panel
            nativePanel = ComObject.As <ISwapChainBackgroundPanelNative>(panel);

            // Register event on Window Size Changed
            // So that resources dependent size can be resized
            Window.Current.CoreWindow.SizeChanged += CoreWindow_SizeChanged;
        }
Exemple #17
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();
            }
        }
        public SurfaceImageSourceCanvas(SurfaceImageSource surfaceImageSource, Rect updateRect, Direct2DFactories factories = null)
            : base(factories)
        {
            sisn = ComObject.As <DXGI.ISurfaceImageSourceNative> (surfaceImageSource);
            SharpDX.Point offset;
            var           surface = sisn.BeginDraw(updateRect.ToRectangle(), out offset);

            var dpi        = 96.0;
            var properties = new D2D1.RenderTargetProperties(D2D1.RenderTargetType.Default, new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Unknown), (float)(dpi), (float)(dpi), D2D1.RenderTargetUsage.None, D2D1.FeatureLevel.Level_DEFAULT);

            Initialize(new D2D1.RenderTarget(this.factories.D2DFactory, surface, properties));
        }
Exemple #19
0
        public void Initialise(int width, int height, params SharpDX.Direct3D.FeatureLevel[] featureLevels)
        {
            // Create device
            var dev = new D3D11.Device(SharpDX.Direct3D.DriverType.Hardware, D3D11.DeviceCreationFlags.None,
                                       featureLevels);

            _device  = ComObject.As <D3D11.Device1>(dev.NativePointer);
            _context = _device.ImmediateContext1;

            ToolkitDevice = SharpDX.Toolkit.Graphics.GraphicsDevice.New(_device);

            InitSwapChain(width, height);
            RetrieveSetBuffers();
            _ready = true;
        }
Exemple #20
0
        public D3DAppSwapChainPanelTarget(SwapChainPanel panel)
        {
            this.panel  = panel;
            nativePanel = ToDispose(ComObject.As <SharpDX.DXGI.ISwapChainPanelNative>(panel));

            this.panel.CompositionScaleChanged += (sender, args) =>
            {
                //SizeChanged();
                ScaleChanged();
            };
            this.panel.SizeChanged += (sender, args) =>
            {
                SizeChanged();
            };
        }
Exemple #21
0
        public void InitializeDevice(int width, int height, object swapChainPanel)
        {
            var nativePanel = ComObject.As <DXGI.ISwapChainPanelNative>(swapChainPanel);

            Debug.Assert(nativePanel != null, $"{nameof(swapChainPanel)} should not be null.");

            D3Device = DirectXTools.CreateD3Device();
            {
                RenderTarget          = DirectXTools.CreateRenderTarget(Direct2DFactory, D3Device);
                _solidBrush           = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
                SwapChain             = DirectXTools.CreateSwapChain(width, height, D3Device);
                nativePanel.SwapChain = SwapChain;
                DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
                Bitmaps.SetRenderTarget(RenderTarget);
                TextLayouts.SetRenderTarget(RenderTarget);
            }
        }
Exemple #22
0
        private void swapChainPanel_Unloaded(object sender, RoutedEventArgs e)
        {
            Application.Current.Suspending -= Current_Suspending;
            CompositionTarget.Rendering    -= CompositionTarget_Rendering;

            using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(this.swapChainPanel))
                nativeObject.SwapChain = null;
            Utilities.Dispose(ref this.backBufferView);
            Utilities.Dispose(ref this.backBufferTexture);
            Utilities.Dispose(ref this.swapChain);
            Utilities.Dispose(ref this.deviceContext);
            Utilities.Dispose(ref this.device);

            Utilities.Dispose(ref this.vertBuffer);
            Utilities.Dispose(ref this.vs);
            Utilities.Dispose(ref this.ps);
            Utilities.Dispose(ref this.vertLayout);
        }
Exemple #23
0
        private void SwapChainPanel_Unloaded(object sender, RoutedEventArgs e)
        {
            // Unsubscribe from suspending event.
            App.Current.Suspending -= Application_Suspending;

            // Unsubscribe from rendering event.
            CompositionTarget.Rendering -= CompositionTarget_Rendering;

            // Unset native swap chanel's reference.
            using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(this.SwapChainPanel))
            {
                nativeObject.SwapChain = null;
            }

            // Safely dispose all resources.
            Utilities.Dispose(ref this.backBufferView);
            Utilities.Dispose(ref this.backBufferTexture);
            Utilities.Dispose(ref this.swapChain);
            Utilities.Dispose(ref this.deviceContext);
            Utilities.Dispose(ref this.device);
        }
Exemple #24
0
        private void InitializeD3D()
        {
            using (D3D11.Device defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.Debug))
                this.device = defaultDevice.QueryInterface <D3D11.Device2>();
            this.deviceContext = this.device.ImmediateContext2;

            DXGI.SwapChainDescription1 swapChainDescription = new DXGI.SwapChainDescription1()
            {
                AlphaMode         = DXGI.AlphaMode.Ignore,
                BufferCount       = 2,
                Format            = DXGI.Format.R8G8B8A8_UNorm,
                Height            = (int)(this.swapChainPanel.RenderSize.Height),
                Width             = (int)(this.swapChainPanel.RenderSize.Width),
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Scaling           = SharpDX.DXGI.Scaling.Stretch,
                Stereo            = false,
                SwapEffect        = DXGI.SwapEffect.FlipSequential,
                Usage             = DXGI.Usage.RenderTargetOutput
            };

            using (DXGI.Device3 dxgiDevice3 = this.device.QueryInterface <DXGI.Device3>())
                using (DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent <DXGI.Factory3>())
                {
                    DXGI.SwapChain1 swapChain1 = new DXGI.SwapChain1(dxgiFactory3, this.device, ref swapChainDescription);
                    this.swapChain = swapChain1.QueryInterface <DXGI.SwapChain2>();
                }

            using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(this.swapChainPanel))
                nativeObject.SwapChain = this.swapChain;

            this.backBufferTexture = this.swapChain.GetBackBuffer <D3D11.Texture2D>(0);
            this.backBufferView    = new D3D11.RenderTargetView(this.device, this.backBufferTexture);

            deviceContext.Rasterizer.SetViewport(0, 0, (int)swapChainPanel.ActualWidth, (int)swapChainPanel.ActualHeight);

            CompositionTarget.Rendering    += CompositionTarget_Rendering;
            Application.Current.Suspending += Current_Suspending;

            isDXInitialized = true;
        }
        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.MultiSampleLevel, 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);
        }
Exemple #26
0
 private void SwapChainPanel_Unloaded(object sender, RoutedEventArgs e)
 {
     App.Current.Suspending      -= Application_Suspending;
     CompositionTarget.Rendering -= CompositionTarget_Rendering;
     using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(this.SwapChainPanel))
     {
         nativeObject.SwapChain = null;
     }
     Utilities.Dispose(ref this.backBufferView);
     Utilities.Dispose(ref this.backBufferTexture);
     Utilities.Dispose(ref this.swapChain);
     Utilities.Dispose(ref this.deviceContext);
     Utilities.Dispose(ref this.device);
     Utilities.Dispose(ref this.textBrush);
     Utilities.Dispose(ref this.backgroundBrush);
     Utilities.Dispose(ref this.textLayout2);
     Utilities.Dispose(ref this.textLayout1);
     Utilities.Dispose(ref this.textFormat);
     Utilities.Dispose(ref this.d2dContext);
     Utilities.Dispose(ref this.d2dTarget);
     Utilities.Dispose(ref this.d2dFactory);
     Utilities.Dispose(ref this.d2dDevice);
     tw?.Dispose();
 }
Exemple #27
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);
        }
Exemple #28
0
        /// <summary>
        /// Initializes the SwapChain for use with LibVLC
        /// </summary>
        void CreateSwapChain()
        {
            SharpDX.DXGI.Factory2 dxgiFactory = null;
            try
            {
                var deviceCreationFlags =
                    DeviceCreationFlags.BgraSupport | DeviceCreationFlags.VideoSupport;

#if DEBUG
                if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily != Mobile)
                {
                    deviceCreationFlags |= DeviceCreationFlags.Debug;
                }

                try
                {
                    dxgiFactory = new SharpDX.DXGI.Factory2(true);
                }
                catch (SharpDXException)
                {
                    dxgiFactory = new SharpDX.DXGI.Factory2(false);
                }
#else
                dxgiFactory = new SharpDX.DXGI.Factory2(false);
#endif
                _d3D11Device = null;
                foreach (var adapter in dxgiFactory.Adapters)
                {
                    try
                    {
                        _d3D11Device = new SharpDX.Direct3D11.Device(adapter, deviceCreationFlags);
                        break;
                    }
                    catch (SharpDXException)
                    {
                    }
                }

                if (_d3D11Device is null)
                {
                    throw new VLCException("Could not create Direct3D11 device : No compatible adapter found.");
                }

                _device = _d3D11Device.QueryInterface <SharpDX.DXGI.Device1>();

                //Create the swapchain
                var swapChainDescription = new SharpDX.DXGI.SwapChainDescription1
                {
                    Width             = (int)(_panel.ActualWidth * _panel.CompositionScaleX),
                    Height            = (int)(_panel.ActualHeight * _panel.CompositionScaleY),
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Stereo            = false,
                    SampleDescription =
                    {
                        Count   = 1,
                        Quality = 0
                    },
                    Usage       = Usage.RenderTargetOutput,
                    BufferCount = 2,
                    SwapEffect  = SwapEffect.FlipSequential,
                    Flags       = SwapChainFlags.None,
                    AlphaMode   = AlphaMode.Unspecified
                };

                _swapChain = new SharpDX.DXGI.SwapChain1(dxgiFactory, _d3D11Device, ref swapChainDescription);

                _device.MaximumFrameLatency = 1;

                using (var panelNative = ComObject.As <ISwapChainPanelNative>(_panel))
                {
                    panelNative.SwapChain = _swapChain;
                }

                // This is necessary so we can call Trim() on suspend
                _device3 = _device.QueryInterface <SharpDX.DXGI.Device3>();
                if (_device3 == null)
                {
                    throw new VLCException("Failed to query interface \"Device3\"");
                }

                _swapChain2 = _swapChain.QueryInterface <SharpDX.DXGI.SwapChain2>();
                if (_swapChain2 == null)
                {
                    throw new VLCException("Failed to query interface \"SwapChain2\"");
                }

                UpdateScale();
                UpdateSize();
                _loaded = true;
                Initialized?.Invoke(this, new InitializedEventArgs(SwapChainOptions));
            }
            catch (Exception ex)
            {
                DestroySwapChain();
                if (ex is SharpDXException)
                {
                    throw new VLCException("SharpDX operation failed, see InnerException for details", ex);
                }

                throw;
            }
            finally
            {
                dxgiFactory?.Dispose();
            }
        }
        private void SwapChainPanel_OnLoaded(object sender, RoutedEventArgs e)
        {
            using (var defDevice = new D3D.Device(DriverType.Hardware, D3D.DeviceCreationFlags.Debug))
            {
                _device = defDevice.QueryInterface <D3D.Device3>();
            }
            _context = _device.ImmediateContext3;

            var pixelScale    = DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f;
            var swapChainDesc = new DXGI.SwapChainDescription1()
            {
                AlphaMode         = DXGI.AlphaMode.Premultiplied,
                BufferCount       = 2,
                Flags             = DXGI.SwapChainFlags.None,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                Width             = (int)(panel.RenderSize.Width * pixelScale),
                Height            = (int)(panel.RenderSize.Height * pixelScale),
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Scaling           = DXGI.Scaling.Stretch,
                Stereo            = false,
                SwapEffect        = DXGI.SwapEffect.FlipSequential,
                Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput
            };

            using (var dxgiDevice = _device.QueryInterface <DXGI.Device3>())
            {
                var factory = dxgiDevice.Adapter.GetParent <DXGI.Factory4>();
                using (var tmpSwapChain = new DXGI.SwapChain1(factory, _device, ref swapChainDesc))
                {
                    _swapChain = tmpSwapChain.QueryInterface <DXGI.SwapChain3>();
                }
            }

            using (var nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(panel))
            {
                nativeObject.SwapChain = _swapChain;
            }

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

            _backBuffer = D3D.Resource.FromSwapChain <D3D.Texture2D>(_swapChain, 0);
            _renderView = new D3D.RenderTargetView1(_device, _backBuffer);

            var viewport = new ViewportF(0, 0, (float)panel.RenderSize.Width, (float)panel.RenderSize.Height, 0.0f, 1.0f);

            _context.Rasterizer.SetViewport(viewport);

            ShaderBytecode shaderBytecode;

            using (shaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "vs", "vs_5_0", ShaderFlags.Debug))
            {
                _vertexShader = new D3D.VertexShader(_device, shaderBytecode);
            }

            using (var byteCode = ShaderBytecode.CompileFromFile(@"shaders.hlsl", "ps", "ps_5_0", ShaderFlags.Debug))
            {
                _pixelShader = new D3D.PixelShader(_device, byteCode);
            }

            D3D.InputElement[] inputElements =
            {
                new D3D.InputElement("POSITION", 0, DXGI.Format.R32G32B32A32_Float, 0, 0),
            };
            _inputLayout = new D3D.InputLayout(_device, shaderBytecode, inputElements);

            _vertices = new[]
            {
                new Vector4(-0.5f, 0.0f, 0.5f, 1.0f),
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f),
                new Vector4(0.5f, 0.0f, 0.5f, 1.0f),
            };
            _vertexBuffer  = D3D.Buffer.Create(_device, D3D.BindFlags.VertexBuffer, _vertices);
            _vertexBinding = new D3D.VertexBufferBinding(_vertexBuffer, Utilities.SizeOf <Vector4>(), 0);

            _constantBuffer = new SharpDX.Direct3D11.Buffer(
                _device,
                Utilities.SizeOf <SharpDX.Matrix>(),
                D3D.ResourceUsage.Default,
                D3D.BindFlags.ConstantBuffer,
                D3D.CpuAccessFlags.None,
                D3D.ResourceOptionFlags.None,
                0);

            _timer = new Stopwatch();
            _timer.Start();

            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
Exemple #30
0
        private void SwapChainPanel_Loaded(object sender, RoutedEventArgs e)
        {
            var v = ApplicationView.GetForCurrentView();

            v.FullScreenSystemOverlayMode = FullScreenSystemOverlayMode.Minimal;
            v.TryEnterFullScreenMode();
#if DEBUG
            var debugLevel = D3D11.DeviceCreationFlags.Debug | D3D11.DeviceCreationFlags.BgraSupport;
#else
            var debugLevel = D3D11.DeviceCreationFlags.None | D3D11.DeviceCreationFlags.BgraSupport;
#endif
            using (D3D11.Device defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, debugLevel))
            {
                this.device = defaultDevice.QueryInterface <D3D11.Device2>();
            }
            this.deviceContext = this.device.ImmediateContext2;
            float pixelScale = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f;

            DXGI.SwapChainDescription1 swapChainDescription = new DXGI.SwapChainDescription1()
            {
                AlphaMode         = DXGI.AlphaMode.Premultiplied,
                BufferCount       = 2,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                Height            = (int)(this.SwapChainPanel.RenderSize.Height * pixelScale),
                Width             = (int)(this.SwapChainPanel.RenderSize.Width * pixelScale),
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Scaling           = DXGI.Scaling.Stretch,
                Stereo            = false,
                SwapEffect        = DXGI.SwapEffect.FlipSequential,
                Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput,
            };
            using (DXGI.Device3 dxgiDevice3 = this.device.QueryInterface <DXGI.Device3>())
            {
                using (DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent <DXGI.Factory3>())
                {
                    using (DXGI.SwapChain1 swapChain1 = new DXGI.SwapChain1(dxgiFactory3, this.device, ref swapChainDescription))
                    {
                        this.swapChain = swapChain1.QueryInterface <DXGI.SwapChain2>();
                    }
                }
            }
            using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(this.SwapChainPanel))
            {
                nativeObject.SwapChain = this.swapChain;
            }
            this.backBufferTexture = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(this.swapChain, 0);
            this.backBufferView    = new D3D11.RenderTargetView(this.device, this.backBufferTexture);
            isDXInitialized        = true;
            tw = new TextWirter(device, swapChain, Color.Black, DisplayInformation.GetForCurrentView().LogicalDpi);
//            #region D2D

//#if DEBUG
//            var debug = SharpDX.Direct2D1.DebugLevel.Error;
//#else
//            var debug = SharpDX.Direct2D1.DebugLevel.None;
//#endif

//            d2dFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debug);
//            using (var dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device>())
//            {
//                d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice);
//            }
//            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

//            BitmapProperties1 properties = new BitmapProperties1(
//                new PixelFormat(
//                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
//                    SharpDX.Direct2D1.AlphaMode.Premultiplied),
//                DisplayInformation.GetForCurrentView().LogicalDpi,
//                DisplayInformation.GetForCurrentView().LogicalDpi,
//                BitmapOptions.Target | BitmapOptions.CannotDraw);
//            DXGI.Surface backBuffer = swapChain.GetBackBuffer<DXGI.Surface>(0);
//            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);
//            SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();
//            textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f);
//            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);
//            layoutY = 0.0f;
//            backgroundBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.White);
//            textBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.Black);
//            #endregion

            CompositionTarget.Rendering    += CompositionTarget_Rendering;
            Application.Current.Suspending += Application_Suspending;
        }