/// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="BackBuffer">Буффер на который будем рисовать, наш холст</param>
        /// <param name="Width">Ширина области в которую будем рисовать</param>
        /// <param name="Height">Высота объласти в которую будем рисовать</param>
        public TextWirter(SharpDX.Direct3D11.Device2 device, SwapChain2 swapChain, Color color, float dpi = 96f, string font = "Calibri", int size = 14)
        {
#if DEBUG
            var debug = SharpDX.Direct2D1.DebugLevel.Error;
#else
            var debug = SharpDX.Direct2D1.DebugLevel.None;
#endif

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

            BitmapProperties1 properties = new BitmapProperties1(
                new PixelFormat(
                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied),
                dpi,
                dpi,
                BitmapOptions.Target | BitmapOptions.CannotDraw);
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);
            d2dTarget        = new Bitmap1(_RenderTarget2D, backBuffer, properties);
            this.TextFont    = font;
            this.TextSize    = size;
            _FactoryDWrite   = new SharpDX.DirectWrite.Factory();
            _SceneColorBrush = new SolidColorBrush(_RenderTarget2D, color);
            InitTextFormat();
            _RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;
        }
Ejemplo n.º 2
0
        public void Dispose()
        {
            if (ColorConverter.IsValueCreated)
            {
                ColorConverter.Value.Dispose();
            }

            _solidColorBrush?.Dispose();
            _solidColorBrush = null;

            RenderTarget.Dispose();
            RenderTarget = null;

            _factory.Dispose();
            _factory = null;

            _writeFactory?.Dispose();
            _writeFactory = null;

            _imagingFactory?.Dispose();
            _imagingFactory = null;

            PreviewTexture.Dispose();
            PreviewTexture = null;

            DesktopTexture.Dispose();
            DesktopTexture = null;

            StagingTexture.Dispose();
            StagingTexture = null;

            Device.Dispose();
            Device = null;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Converts rendered image to bitmap
        /// </summary>
        /// <returns></returns>
        private D2D1.BitmapRenderTarget RenderBitmap()
        {
            using (var textureToBitmap = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0)) {
                using (var surface = textureToBitmap.QueryInterface <Surface>()) {
                    using (D2D1.Factory factory = new D2D1.Factory1()) {
                        var target = new D2D1.RenderTarget(
                            factory,
                            surface,
                            new D2D1.RenderTargetProperties(
                                new D2D1.PixelFormat(Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Ignore)
                                )
                            );

                        D2D1.BitmapRenderTarget tes = null;

                        tes = new D2D1.BitmapRenderTarget(
                            target,
                            D2D1.CompatibleRenderTargetOptions.None,
                            new D2D1.PixelFormat(
                                Format.B8G8R8A8_UNorm,
                                D2D1.AlphaMode.Ignore));

                        target.Dispose();

                        return(tes);
                    }
                }
            }
        }
Ejemplo n.º 4
0
            public Core()
            {
                using (var dxgiDevice =
                           ImageFramework.DirectX.Device.Get().Handle.QueryInterface <SharpDX.DXGI.Device>())
                {
#if DEBUG
                    var debugLevel = DebugLevel.Information;
#else
                    var debugLevel = DebugLevel.None;
#endif
                    var factory = new SharpDX.Direct2D1.Factory1(FactoryType.MultiThreaded, debugLevel);
                    Factory = factory;
                    Handle  = new SharpDX.Direct2D1.Device(factory, dxgiDevice);
                    Context = new SharpDX.Direct2D1.DeviceContext(Handle, DeviceContextOptions.None);
                }

                WriteFactory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);

                RoundStroke = new StrokeStyle(Factory, new StrokeStyleProperties
                {
                    StartCap = CapStyle.Round,
                    EndCap   = CapStyle.Round
                });
                HardStroke = new StrokeStyle(Factory, new StrokeStyleProperties
                {
                    StartCap = CapStyle.Flat,
                    EndCap   = CapStyle.Flat
                });

                ImageFramework.DirectX.Device.Get().DeviceDispose += (sender, args) => Dispose();
            }
Ejemplo n.º 5
0
        public Direct2DEditorSession(Texture2D Texture, Device Device, Texture2D StagingTexture)
        {
            _texture            = Texture;
            this.Device         = Device;
            this.StagingTexture = StagingTexture;

            PreviewTexture = new Texture2D(Device, new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.None,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = Texture.Description.Width,
                Height            = Texture.Description.Height,
                OptionFlags       = ResourceOptionFlags.Shared,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Default
            });

            _surface = Texture.QueryInterface <Surface>();

            _factory = new Factory1(FactoryType.MultiThreaded);

            var renderTargetProps = new RenderTargetProperties(
                new PixelFormat(Format.Unknown, AlphaMode.Ignore))
            {
                Type = RenderTargetType.Hardware
            };

            RenderTarget = new RenderTarget(_factory, _surface, renderTargetProps);
        }
Ejemplo n.º 6
0
        public WindowedDirect2dRenderEnvironment(string formName, bool debug)
        {
            form = new RenderForm(formName);

            d3dDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport | (debug ? DeviceCreationFlags.Debug : DeviceCreationFlags.None));

            dxgiDevice  = d3dDevice.QueryInterface <SharpDX.DXGI.Device>();
            dxgiFactory = new SharpDX.DXGI.Factory1();
            swapChain   = new SwapChain(dxgiFactory, dxgiDevice, new SwapChainDescription {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(Format.B8G8R8A8_UNorm),
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            });
            dxgiSurface = swapChain.GetBackBuffer <Surface>(0);

            d2dFactory        = new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded, debug ? DebugLevel.Warning : DebugLevel.None);
            d2dDevice         = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice);
            d2dContext        = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.None);
            bitmap            = new Bitmap1(d2dContext, dxgiSurface, null);
            d2dContext.Target = bitmap;
        }
        public Direct2DEditorSession(int Width, int Height, IPreviewWindow PreviewWindow)
        {
            _previewWindow = PreviewWindow;

            try
            {
                Device = new Device(DriverType.Hardware,
                                    DeviceCreationFlags.BgraSupport);
            }
            catch (SharpDXException)
            {
                Device = new Device(DriverType.Warp,
                                    DeviceCreationFlags.BgraSupport);
            }

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

            DesktopTexture = new Texture2D(Device, new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.None,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = Width,
                Height            = Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Default
            });

            var desc = DesktopTexture.Description;

            desc.OptionFlags = ResourceOptionFlags.Shared;

            PreviewTexture = new Texture2D(Device, desc);

            _factory = new Factory1(FactoryType.MultiThreaded);

            var pixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Ignore);

            var renderTargetProps = new RenderTargetProperties(pixelFormat);

            using (var surface = DesktopTexture.QueryInterface <Surface>())
            {
                RenderTarget = new RenderTarget(_factory, surface, renderTargetProps);
            }
        }
Ejemplo n.º 8
0
        public Direct2DEditorSession(Texture2D Texture, Device Device, Texture2D StagingTexture)
        {
            _texture            = Texture;
            this.Device         = Device;
            this.StagingTexture = StagingTexture;

            var desc = Texture.Description;

            desc.OptionFlags = ResourceOptionFlags.Shared;

            PreviewTexture = new Texture2D(Device, desc);

            _factory = new Factory1(FactoryType.MultiThreaded);

            var pixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Ignore);

            var renderTargetProps = new RenderTargetProperties(pixelFormat)
            {
                Type = RenderTargetType.Hardware
            };

            using (var surface = Texture.QueryInterface <Surface>())
            {
                RenderTarget = new RenderTarget(_factory, surface, renderTargetProps);
            }
        }
        public void Dispose()
        {
            _solidColorBrush?.Dispose();
            _solidColorBrush = null;

            RenderTarget.Dispose();
            RenderTarget = null;

            _factory.Dispose();
            _factory = null;

            _writeFactory?.Dispose();
            _writeFactory = null;

            _imagingFactory?.Dispose();
            _imagingFactory = null;

            PreviewTexture.Dispose();
            PreviewTexture = null;

            DesktopTexture.Dispose();
            DesktopTexture = null;

            StagingTexture.Dispose();
            StagingTexture = null;

            Device.Dispose();
            Device = null;
        }
Ejemplo n.º 10
0
 internal void ReleaseDevices()
 {
     IsRendererSuppressed = true;
     RenderTarget.Dispose();
     Backbuffer.Dispose();
     RenderTargetSurface.Dispose();
     RenderTargetView.Dispose();
     D2DDeviceContext.Dispose();
     D2DDevice.Dispose();
     D2DFactory.Dispose();
     DXGIDevice.Dispose();
     D3DDevice.Dispose();
     D3DDefaultDevice.Dispose();
     SwapChain.Dispose();
     SwapChain           = null;
     RenderTarget        = null;
     RenderTargetSurface = null;
     Backbuffer          = null;
     RenderTargetView    = null;
     D2DDeviceContext    = null;
     D2DFactory          = null;
     D2DDevice           = null;
     DXGIDevice          = null;
     D3DDevice           = null;
     D3DDefaultDevice    = null;
 }
Ejemplo n.º 11
0
        internal void Initialise()
        {
            RemoveAndDispose(ref _d2dFactory);
            RemoveAndDispose(ref _dwFactory);

            _d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded));
            _dwFactory  = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));

            RemoveAndDispose(ref _d3dDevice);
            RemoveAndDispose(ref _d3dContext);
            RemoveAndDispose(ref _d2dDevice);
            RemoveAndDispose(ref _d2dContext);


            //var desc = CreateSwapChainDescription();

            using (var device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport)) // | DeviceCreationFlags.Debug,
            {
                _d3dDevice = ToDispose(device.QueryInterface <SharpDX.Direct3D11.Device1>());
            }

            _d3dContext = ToDispose(_d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>());



            using (var dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device>())
            {
                _d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice));
            }
            _d2dContext = ToDispose(new DeviceContext(_d2dDevice, DeviceContextOptions.None));

            /*
             * D2Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new [] { FeatureLevel.Level_10_0 }, desc, out _device, out _swapChain);
             *
             * ToDispose(_device);
             * ToDispose(_swapChain);
             *
             * var d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory());
             *
             * Factory factory = ToDispose(_swapChain.GetParent<Factory>());
             * factory.MakeWindowAssociation(_outputHandle, WindowAssociationFlags.IgnoreAll);
             *
             * _backBuffer = ToDispose(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0));
             * _renderTargetView = ToDispose(new RenderTargetView(_device, _backBuffer));
             * _surface = ToDispose(_backBuffer.QueryInterface<Surface>());
             *
             * _target = ToDispose(new RenderTarget(d2dFactory, _surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))));
             */

            InitialiseResources();

            RemoveAndDispose(ref _fpsCounter);

            _fpsCounter = new FpsCounter();
            _fpsCounter.InitialiseGraphics(this);

            OnInitialize?.Invoke(this);
        }
Ejemplo n.º 12
0
        public static Direct2D1.DeviceContext CreateRenderTarget(
            Direct2D1.Factory1 factory2d,
            Direct3D11.Device device3d)
        {
            var dxgiDevice = device3d.QueryInterface <DXGI.Device>();

            using (var device2d = new Direct2D1.Device(factory2d, dxgiDevice))
            {
                return(new Direct2D1.DeviceContext(
                           device2d,
                           Direct2D1.DeviceContextOptions.None));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Create a batch manager for drawing text and sprite
        /// </summary>
        /// <param name="device">Device pointer</param>
        internal Canvas(Device device)
        {
            Device = device;

            NativeFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, DebugLevel.Information);

            using (var dxgiDevice = device.NativeDevice.QueryInterface <DeviceGI>())
                NativeDevice = new Device2D(NativeFactory, dxgiDevice);

            NativeDeviceContext = new DeviceContext(NativeDevice, DeviceContextOptions.None);

            InitializeFont();
            Brush = new SolidColorBrush(NativeDeviceContext, default(Color4));
        }
Ejemplo n.º 14
0
        public Direct2DDevice(IServiceRegistry services, SharpDX.Direct3D11.Device d3dDevice, DebugLevel debugLevel)
        {
            this.services = services;
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>())
            {
                factory       = ToDispose(new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded, debugLevel));
                device        = ToDispose(new Device(factory, dxgiDevice));
                deviceContext = ToDispose(new DeviceContext(device, DeviceContextOptions.None));
            }

            backBuffer = ToDispose(BackBufferSurface.New(this));
            backBuffer.Initialize();

            directWriteFactory = ToDispose(new DWFactory());
        }
Ejemplo n.º 15
0
        public Direct2DGraphics(UserControl control)
        {
            factory       = new SharpDX.Direct2D1.Factory1();
            windowScaling = Direct2DTheme.MainWindowScaling;

            HwndRenderTargetProperties properties = new HwndRenderTargetProperties();

            properties.Hwnd           = control.Handle;
            properties.PixelSize      = new SharpDX.Size2(control.ClientSize.Width, control.ClientSize.Height);
            properties.PresentOptions = PresentOptions.None;

            renderTarget = new WindowRenderTarget(factory, new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)), properties);

            Initialize();
        }
Ejemplo n.º 16
0
        private void InitializeDevices()
        {
            try
            {
                SwapChainDescription                   = new DXGI.SwapChainDescription();
                SwapChainDescription.BufferCount       = 2;
                SwapChainDescription.SampleDescription = new DXGI.SampleDescription(1, 0);
                SwapChainDescription.SwapEffect        = DXGI.SwapEffect.Discard;
                SwapChainDescription.Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput;
                SwapChainDescription.IsWindowed        = true;
                SwapChainDescription.ModeDescription   = new DXGI.ModeDescription(GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm);
                SwapChainDescription.OutputHandle      = GameWindowHandle;

                D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport, featureLevels, SwapChainDescription, out D3DDefaultDevice, out SwapChain);

                DXGI.Factory factory = SwapChain.GetParent <DXGI.Factory>();
                factory.MakeWindowAssociation(GameWindowHandle, DXGI.WindowAssociationFlags.IgnoreAll);

                D3DDevice = D3DDefaultDevice.QueryInterface <D3D11.Device1>();

                Backbuffer       = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(SwapChain, 0);
                RenderTargetView = new D3D11.RenderTargetView(D3DDevice, Backbuffer);
                D3DDevice.ImmediateContext.Rasterizer.SetViewport(0, 0, GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height);
                D3DDevice.ImmediateContext.OutputMerger.SetTargets(RenderTargetView);

                DXGIDevice = D3DDevice.QueryInterface <DXGI.Device>();

                D2DFactory       = new D2D1.Factory1(D2D1.FactoryType.MultiThreaded);
                D2DDevice        = new D2D1.Device(D2DFactory, DXGIDevice);
                D2DDeviceContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);

                RenderTargetSurface        = Backbuffer.QueryInterface <DXGI.Surface>();
                RenderTarget               = new D2D1.RenderTarget(D2DFactory, RenderTargetSurface, new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)));
                RenderTarget.AntialiasMode = D2D1.AntialiasMode.PerPrimitive;

                // Initialize debug drawings brushes
                DrawingBoundsBrush  = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 1f, 0f));
                CollisionBoxesBrush = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 0f, 0f));

                RenderFrame = new RenderFrame(RenderTarget);

                Clock = Stopwatch.StartNew();
            }
            catch (Exception ex)
            {
                throw new DeviceInitializationException("Unable to initialize DirectX device!", ex);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates device independent resources.
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceIndependentResources()
        {
#if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
#else
            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
#endif
            // Dispose previous references and set to null
            RemoveAndDispose(ref d2dFactory);
            RemoveAndDispose(ref dwriteFactory);
            RemoveAndDispose(ref wicFactory);

            // Allocate new references
            d2dFactory    = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel));
            dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));
            wicFactory    = ToDispose(new SharpDX.WIC.ImagingFactory2());
        }
Ejemplo n.º 18
0
        private void Initialize()
        {
            _d2dFactory   = new SharpDX.Direct2D1.Factory1();
            DWriteFactory = new SharpDX.DirectWrite.Factory1();
            WicFactory    = new ImagingFactory2();

            DevicePixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied);
            ImagePixelFormat  = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
                using (var d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>())
                    using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    {
                        _d2dDevice    = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
                        DeviceContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, new DeviceContextOptions());
                    }

            WicImageEncoder = new ImageEncoder(WicFactory, _d2dDevice);
            DeviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
Ejemplo n.º 19
0
        private void InitializeDirectX(GameWindow gameWindow)
        {
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
            {
                _d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }

            var swapChainDesc = new SwapChainDescription1()
            {
                Width             = 0,
                Height            = 0,
                Format            = Format.B8G8R8A8_UNorm,
                BufferCount       = 2,
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                SwapEffect        = SwapEffect.FlipSequential,
                SampleDescription = new SampleDescription(1, 0),
                Scaling           = Scaling.AspectRatioStretch
            };

            using (var dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                using (var dxgiFactory = dxgiDevice.Adapter.GetParent <SharpDX.DXGI.Factory2>())
                {
                    var window = new ComObject(gameWindow.WindowObject);
                    _swapChain  = new SwapChain1(dxgiFactory, _d3dDevice, window, ref swapChainDesc);
                    _d2dFactory = new SharpDX.Direct2D1.Factory1();
                    _d2dDevice  = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
                }

            _deviceContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, new DeviceContextOptions());
            using (var surface = Surface.FromSwapChain(_swapChain, 0))
            {
                var pixelFormat      = new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied);
                var bitmapProperties = new BitmapProperties1(pixelFormat, 0, 0, BitmapOptions.Target | BitmapOptions.CannotDraw);

                _d2dTargetBitmap      = new SharpDX.Direct2D1.Bitmap1(_deviceContext, surface, bitmapProperties);
                _deviceContext.Target = _d2dTargetBitmap;
            }

            _dwriteFactory   = new SharpDX.DirectWrite.Factory1();
            _wicFactory      = new ImagingFactory();
            _formatConverter = new FormatConverter(_wicFactory);
            _deviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype;
        }
Ejemplo n.º 20
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));
        }
Ejemplo n.º 21
0
        private void CreateAndBindTargets()
        {
            d3DSurface.SetRenderTarget(null);

            Disposer.SafeDispose(ref d2DRenderTarget);
            Disposer.SafeDispose(ref D2dDeviceContext);
            Disposer.SafeDispose(ref D2dFactory);
            Disposer.SafeDispose(ref renderTarget);

            var scale  = DpiScale;
            var width  = Math.Max((int)(ActualWidth * scale.X), 100);
            var height = Math.Max((int)(ActualHeight * scale.Y), 100);

            var renderDesc = new Texture2DDescription
            {
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.Shared,
                CpuAccessFlags    = CpuAccessFlags.None,
                ArraySize         = 1
            };

            renderTarget = new Texture2D(device, renderDesc);

            var surface = renderTarget.QueryInterface <Surface>();

            D2dFactory = new SharpDX.Direct2D1.Factory1();
            var rtp = new RenderTargetProperties(new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied));

            d2DRenderTarget            = new RenderTarget(D2dFactory, surface, rtp);
            D2dDeviceContext           = new SharpDX.Direct2D1.DeviceContext(surface);
            ResourceCache.RenderTarget = d2DRenderTarget;

            d3DSurface.SetRenderTarget(renderTarget);

            device.ImmediateContext.Rasterizer.SetViewport(0, 0, width, height, 0.0f, 1.0f);
        }
Ejemplo n.º 22
0
        public DeviceResources(IntPtr handle)
        {
            Factory2D      = new Factory1_2D1();
            ImagingFactory = new ImagingFactory();
            FontFactory    = new FactoryDW();
            PixelFormat    = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);

            var modeDescription = new ModeDescription(PixelFormat.Format);

            var swapChainDescription = new SwapChainDescription
            {
                BufferCount       = 1,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = false,
                ModeDescription   = modeDescription,
                OutputHandle      = handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(
                DriverType.Hardware,
                DeviceCreationFlags.BgraSupport,
                swapChainDescription,
                out Device device3D,
                out SwapChain swapChain
                );
            SwapChain = swapChain;

            using (var dxgiDevice = device3D.QueryInterface <SharpDX.DXGI.Device>())
            {
                Device2D = new Device2D1(Factory2D, dxgiDevice);
            }

            device3D.Dispose();

            CreateDeviceContext();
        }
Ejemplo n.º 23
0
        public Direct2DOffscreenGraphics(int imageSizeX, int imageSizeY)
        {
            d3dDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport);

            offscreenTexture = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription
            {
                BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = imageSizeX,
                Height            = imageSizeY,
                MipLevels         = 1,
                ArraySize         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default
            });

            stagingTexture = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription
            {
                BindFlags         = SharpDX.Direct3D11.BindFlags.None,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.Read,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = imageSizeX,
                Height            = imageSizeY,
                MipLevels         = 1,
                ArraySize         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Staging
            });

            windowScaling = 1.0f; // No scaling for now in videos.
            factory       = new SharpDX.Direct2D1.Factory1();
            renderTarget  = new RenderTarget(factory, offscreenTexture.QueryInterface <SharpDX.DXGI.Surface>(), new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            Initialize();
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StrokeStyle1"/> class.
 /// </summary>
 /// <param name="factory">The factory.</param>
 /// <param name="strokeStyleProperties">No documentation.</param>
 /// <unmanaged>HRESULT ID2D1Factory1::CreateStrokeStyle([In] const D2D1_STROKE_STYLE_PROPERTIES1* strokeStyleProperties,[In, Buffer, Optional] const float* dashes,[In] unsigned int dashesCount,[Out, Fast] ID2D1StrokeStyle1** strokeStyle)</unmanaged>
 public StrokeStyle1(Factory1 factory, SharpDX.Direct2D1.StrokeStyleProperties1 strokeStyleProperties)
     : base(IntPtr.Zero)
 {
     factory.CreateStrokeStyle(ref strokeStyleProperties, null, 0, this);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Creates an <see cref="SharpDX.Direct2D1.DrawingStateBlock1"/> that can be used with the {{SaveDrawingState}} and {{RestoreDrawingState}} methods of a render target.
 /// </summary>
 /// <param name="factory">an instance of <see cref = "SharpDX.Direct2D1.Factory1" /></param>
 /// <param name="drawingStateDescription">A structure that contains antialiasing, transform, and tags  information.</param>
 /// <param name="textRenderingParams">Optional text parameters that indicate how text should be rendered.  </param>
 public DrawingStateBlock1(Factory1 factory, SharpDX.Direct2D1.DrawingStateDescription1 drawingStateDescription, SharpDX.DirectWrite.RenderingParams textRenderingParams)
     : base(IntPtr.Zero)
 {
     factory.CreateDrawingStateBlock(drawingStateDescription, textRenderingParams, this);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Device"/> class.
 /// </summary>
 /// <param name="factory"><para>The <see cref="Factory1"/> object used when creating  the <see cref="SharpDX.Direct2D1.Device"/>. </para></param>
 /// <param name="dxgiDevice"><para>The <see cref="SharpDX.DXGI.Device"/> object used when creating  the <see cref="SharpDX.Direct2D1.Device"/>. </para></param>
 /// <remarks>
 /// Each call to CreateDevice returns a unique <see cref="SharpDX.Direct2D1.Device"/> object.The <see cref="SharpDX.DXGI.Device"/> object is obtained by calling QueryInterface on an ID3D10Device or an ID3D11Device.
 /// </remarks>
 /// <unmanaged>HRESULT ID2D1Factory1::CreateDevice([In] IDXGIDevice* dxgiDevice,[Out] ID2D1Device** d2dDevice)</unmanaged>
 public Device(Factory1 factory, SharpDX.DXGI.Device device)
     : base(IntPtr.Zero)
 {
     factory.CreateDevice(device, this);
 }
Ejemplo n.º 27
0
        // Initialize hardware-dependent resources.
        // Device-independent resources, such as ID2D1Geometry, are kept on the CPU.
        // Device-dependent resources, such as ID2D1RenderTarget and ID2D1LinearGradientBrush, directly map to resources on the GPU 
        // (when hardware acceleration is available). 
        // Rendering calls are performed by combining vertex and coverage information from a geometry with texturing information produced by the device-dependent resources.
        private void CreateDeviceResources()
        {
            // http://msdn.microsoft.com/zh-tw/library/windows/apps/dn481540.aspx

            // Unlike the original C++ sample, we don't have smart pointers so we need to
            // dispose Direct3D objects explicitly
            Utilities.Dispose(ref d3dDevice);
            Utilities.Dispose(ref d2dDevice);
            Utilities.Dispose(ref d2dContext);
            Utilities.Dispose(ref d2dFactory);

#if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
#else
            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
#endif
            d2dFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded);

            // This flag adds support for surfaces with a different color channel ordering
            // than the API default. It is required for compatibility with Direct2D.
            var creationFlags = DeviceCreationFlags.BgraSupport;

#if DEBUG
            // If the project is in a debug build, enable debugging via SDK Layers.
            creationFlags |= DeviceCreationFlags.Debug;
#endif

            // This array defines the set of DirectX hardware feature levels this app will support.
            // Note the ordering should be preserved.
            // Don't forget to declare your application's minimum required feature level in its
            // description.  All applications are assumed to support 9.1 unless otherwise stated.
            FeatureLevel[] featureLevels =
            {
                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,
            };

            // Create the Direct3D 11 API device object.
            d3dDevice = new Device(DriverType.Hardware, creationFlags, featureLevels);

            // Get the Direct3D 11.1 API device.
            // DXGI : DirectX Graphics Infrastructure
            // DXGI 是一組用來設定和管理低階圖形與圖形卡資源的 API
            // 為了直接存取 GPU 並管理其資源,必須有一個對應用程式描述它的方式。
            // 您所需最重要的 GPU 資訊就是繪製像素的位置,這樣它才能夠將這些像素傳送到螢幕上。
            // 這通常稱為「背景緩衝區」—GPU 記憶體中的一個位置,您可以在該處繪製像素,
            // 然後「翻轉」或「交換」,並在收到重新整理訊號時傳送到螢幕上。
            // DXGI 可讓您取得該位置以及使用該緩衝區 (稱為「交換鏈結」,
            // 因為這是可交換的緩衝區鏈結,允許多個緩衝處理策略) 的方法。
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
            {
                // Create the Direct2D device object and a corresponding context.
                // 是 GPU 資源的虛擬表示法
                // ID3D11Device 包含您不常呼叫的圖形方法,通常是在任何轉譯發生之前呼叫這些方法,用來取得和設定開始繪製像素時所需的一組資源。
                d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice);

                // 是轉譯管線與處理程序的跨裝置抽象概念
                // ID3D11DeviceContext 則包含您在每個框架呼叫的方法:
                // 在緩衝區與檢視及其他資源中載入、變更輸出合併與轉譯器狀態、管理著色器,
                // 以及繪製將這些資源在狀態與著色器之間傳遞的結果。
                d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.EnableMultithreadedOptimizations);

                // Query for ISurfaceImageSourceNative interface.
                using (var sisNative = ComObject.QueryInterface<ISurfaceImageSourceNative>(this))
                    sisNative.Device = dxgiDevice;
            }
            setPrimitiveBlend();
        }
            public void Init(Output output, GDI.Rectangle srcRect)
            {
                logger.Debug("DesktopDuplicator::Init(...) " + srcRect.ToString());

                try
                {
                    var          descr      = output.Description;
                    RawRectangle screenRect = descr.DesktopBounds;
                    int          width      = screenRect.Right - screenRect.Left;
                    int          height     = screenRect.Bottom - screenRect.Top;

                    SetupRegions(screenRect, srcRect);


                    if (descr.DeviceName == "\\\\.\\DISPLAY1")
                    {
                        drawRect = new Rectangle
                        {
                            X      = 1920,
                            Y      = 0,
                            Width  = width,
                            Height = height,
                        };
                    }
                    else if (descr.DeviceName == "\\\\.\\DISPLAY2")
                    {
                        drawRect = new Rectangle
                        {
                            X      = 0,
                            Y      = 0,
                            Width  = width,
                            Height = height,
                        };
                    }

                    screenTexture = new Texture2D(device,
                                                  new Texture2DDescription
                    {
                        CpuAccessFlags    = CpuAccessFlags.None,
                        BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                        Format            = Format.B8G8R8A8_UNorm,
                        Width             = width,
                        Height            = height,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        SampleDescription = { Count = 1, Quality = 0 },
                        Usage             = ResourceUsage.Default,

                        OptionFlags = ResourceOptionFlags.Shared,
                    });

                    using (SharpDX.Direct2D1.Factory1 factory2D1 = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.MultiThreaded))
                    {
                        using (var surf = screenTexture.QueryInterface <Surface>())
                        {
                            var pixelFormat       = new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied);
                            var renderTargetProps = new Direct2D.RenderTargetProperties(pixelFormat);
                            screenTarget = new Direct2D.RenderTarget(factory2D1, surf, renderTargetProps);
                        }
                    }

                    using (var output1 = output.QueryInterface <Output1>())
                    {
                        // Duplicate the output
                        deskDupl = output1.DuplicateOutput(device);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    Close();

                    throw;
                }

                deviceReady = true;
            }
Ejemplo n.º 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PathGeometry1"/> class.
 /// </summary>
 /// <param name="factory">The factory.</param>
 /// <unmanaged>HRESULT ID2D1Factory1::CreatePathGeometry([Out, Fast] ID2D1PathGeometry1** pathGeometry)</unmanaged>
 public PathGeometry1(Factory1 factory)
     : base(IntPtr.Zero)
 {
     factory.CreatePathGeometry(this);
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StrokeStyle1"/> class.
 /// </summary>
 /// <param name="factory">The factory.</param>
 /// <param name="strokeStyleProperties">No documentation.</param>
 /// <param name="dashes">No documentation.</param>
 /// <unmanaged>HRESULT ID2D1Factory1::CreateStrokeStyle([In] const D2D1_STROKE_STYLE_PROPERTIES1* strokeStyleProperties,[In, Buffer, Optional] const float* dashes,[In] unsigned int dashesCount,[Out, Fast] ID2D1StrokeStyle1** strokeStyle)</unmanaged>
 ///
 /// <unmanaged>HRESULT ID2D1Factory1::CreateStrokeStyle([In] const D2D1_STROKE_STYLE_PROPERTIES1* strokeStyleProperties,[In, Buffer, Optional] const float* dashes,[In] unsigned int dashesCount,[Out, Fast] ID2D1StrokeStyle1** strokeStyle)</unmanaged>
 /// <remarks>
 /// It is valid to specify a dash array only if <see cref="SharpDX.Direct2D1.DashStyle.Custom"/> is also specified.
 /// </remarks>
 public StrokeStyle1(Factory1 factory, SharpDX.Direct2D1.StrokeStyleProperties1 strokeStyleProperties, float[] dashes)
     : base(IntPtr.Zero)
 {
     factory.CreateStrokeStyle(ref strokeStyleProperties, dashes, dashes.Length, this);
 }
Ejemplo n.º 31
0
 public TextOutlineRenderer(D2DFactory factory)
 {
     this.factory = factory;
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Creates device independent resources.
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceIndependentResources()
        {
            #if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
            #else
            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
            #endif
            // Dispose previous references and set to null
            RemoveAndDispose(ref d2dFactory);
            RemoveAndDispose(ref dwriteFactory);
            RemoveAndDispose(ref wicFactory);

            // Allocate new references
            d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel));
            dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));
            wicFactory = ToDispose(new SharpDX.WIC.ImagingFactory2());
        }
Ejemplo n.º 33
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));
        }