コード例 #1
0
        /// <summary>
        /// Disposes of object resources.
        /// </summary>
        /// <param name="disposeManagedResources">If true, managed resources should be
        /// disposed of in addition to unmanaged resources.</param>
        protected virtual void Dispose(bool disposeManagedResources)
        {
            if (disposeManagedResources)
            {
                _d3d11Device.Dispose();
                _dxgiDevice.Dispose();
                _backBuffer.Dispose();
                _targetBitmap.Dispose();
                _backBuffer2.Dispose();
                _targetBitmap2.Dispose();
                _d2dDevice.Dispose();
                swapChain.Dispose();
                swapChain2.Dispose();
                d2dContext.Dispose();
                d2dContext2.Dispose();
                dw_Factory.Dispose();
            }

            _d3d11Device   = null;
            _dxgiDevice    = null;
            _backBuffer    = null;
            _targetBitmap  = null;
            _backBuffer2   = null;
            _targetBitmap2 = null;
            _d2dDevice     = null;
            swapChain      = null;
            swapChain2     = null;
            d2dContext     = null;
            d2dContext2    = null;
            dw_Factory     = null;
        }
コード例 #2
0
ファイル: ControlBase.cs プロジェクト: dontpanic92/dotnvim
        private void InitializeBackBuffer(D2D.DeviceContext deviceContext, SharpDX.Size2F size)
        {
            this.backBitmap?.Dispose();

            Size2 pixelSize = Helpers.GetPixelSize(size, this.Factory.DesktopDpi);

            var p = new D2D.BitmapProperties1(
                new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                this.Factory.DesktopDpi.Width,
                this.Factory.DesktopDpi.Height,
                D2D.BitmapOptions.Target);

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

            using (var buffer = new D3D11.Texture2D(this.Device, desc))
                using (var surface = buffer.QueryInterface <DXGI.Surface>())
                {
                    this.backBitmap = new D2D.Bitmap1(this.DeviceContext, surface, p);
                }

            this.DeviceContext.Target = this.backBitmap;
        }
コード例 #3
0
ファイル: D2DImage.cs プロジェクト: rootacite/Shinengine
 protected RenderableImage(DeviceContext dc, WICBitmap im)
 {
     this._Pelete = D2DBitmap.FromWicBitmap(dc, im);
     pel_origin   = _Pelete;
     this.rDc     = dc;
     this._Size   = new Size2(this._Pelete.PixelSize.Width, this._Pelete.PixelSize.Height);
 }
コード例 #4
0
        public D3D11Renderer(ObservableVideoTrack videoTrack, RendererOptions options)
            : base(videoTrack, options)
        {
            // _factoryDWrite = new DWrite.Factory(DWrite.FactoryType.Shared);

            var device2D = new D2D1.Device(DeviceDXGI, new D2D1.CreationProperties
            {
                DebugLevel    = D2D1.DebugLevel.Warning,
                ThreadingMode = D2D1.ThreadingMode.MultiThreaded,
                Options       = D2D1.DeviceContextOptions.None
            });

            _context2D = new D2D1.DeviceContext(device2D, D2D1.DeviceContextOptions.None);

            // Load the background image
            using (var factoryWic = new WIC.ImagingFactory2())
                using (var decoder = new WIC.JpegBitmapDecoder(factoryWic))
                    using (var inputStream = new WIC.WICStream(factoryWic, "background-small.jpg", NativeFileAccess.Read))
                        using (var formatConverter = new WIC.FormatConverter(factoryWic))
                            using (var bitmapScaler = new WIC.BitmapScaler(factoryWic))
                            {
                                decoder.Initialize(inputStream, WIC.DecodeOptions.CacheOnLoad);
                                formatConverter.Initialize(decoder.GetFrame(0), WIC.PixelFormat.Format32bppPBGRA);
                                bitmapScaler.Initialize(formatConverter, VideoFrameWidth, VideoFrameHeight,
                                                        WIC.BitmapInterpolationMode.Fant);
                                _backgroundBitmap = D2D1.Bitmap1.FromWicBitmap(_context2D, bitmapScaler);
                            }

            // Create render target
            _ballEllipse = new D2D1.Ellipse {
                RadiusX = VideoFrameWidth / 20f, RadiusY = VideoFrameWidth / 20f
            };

            _ballBrush = new D2D1.SolidColorBrush(_context2D, new RawColor4(1f, 1f, 0f, 1f));
        }
コード例 #5
0
ファイル: BblBitmapSource.cs プロジェクト: philvanzu/Bubbles
    public static SharpDX.Direct2D1.Bitmap Test(SharpDX.Direct2D1.DeviceContext dc, ImagingFactory factory, System.Windows.Media.Imaging.BitmapSource src)
    {
        // PixelFormat settings/conversion
        if (src.Format != System.Windows.Media.PixelFormats.Bgra32)
        {
            // Convert BitmapSource
            FormatConvertedBitmap fcb = new FormatConvertedBitmap();
            fcb.BeginInit();
            fcb.Source            = src;
            fcb.DestinationFormat = PixelFormats.Bgra32;
            fcb.EndInit();
            src = fcb;
        }

        SharpDX.Direct2D1.Bitmap retval = null;
        try
        {
            int    stride     = src.PixelWidth * (src.Format.BitsPerPixel + 7) / 8;
            int    bufferSize = stride * src.PixelHeight;
            byte[] buffer     = new byte[bufferSize];
            src.CopyPixels(Int32Rect.Empty, buffer, stride, 0);
            GCHandle           pinnedArray = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            IntPtr             pointer     = pinnedArray.AddrOfPinnedObject();
            SharpDX.DataStream datastream  = new SharpDX.DataStream(pointer, bufferSize, true, true);
            var bmpProps1 = new SharpDX.Direct2D1.BitmapProperties1(dc.PixelFormat, dc.Factory.DesktopDpi.Width, dc.Factory.DesktopDpi.Height);

            retval = new SharpDX.Direct2D1.Bitmap1(dc, new SharpDX.Size2(src.PixelWidth, src.PixelHeight), datastream, stride, bmpProps1);
            pinnedArray.Free();
        }
        catch (Exception e)
        {
        }
        return(retval);
    }
コード例 #6
0
        public void Init(Window main_window)
        {
            _main_window = main_window;
            m_theatre    = new Shinengine.Theatre.Theatre(BG, Usage, SBK, AirPt, character_usage, Lines, character, ShowIn, _Contents);

            #region logo
            m_logo = new Direct2DImage(new SharpDX.Size2((int)logo_frames[0].Size.Width, (int)logo_frames[0].Size.Height), 30)
            {
                Loadedsouce = logo_frames
            };
            m_logo.DrawProc += (t, s, w, h) =>
            {
                var frames = s as List <WICBitmap>;

                if (ims == frames.Count)
                {
                    ims = 0;
                }
                t.View.BeginDraw();
                t.View.Clear(null);
                D2DBitmap parl_map = D2DBitmap.FromWicBitmap(t.View, frames[ims]);
                t.View.DrawBitmap(parl_map, 1, InterpolationMode.Anisotropic);
                t.View.EndDraw();

                ims++;
                parl_map.Dispose();
                return(DrawProcResult.Normal);
            };
            m_logo.DrawStartup(Logo);


            #endregion
        }
コード例 #7
0
        public void Render()
        {
            ////////////////////////////////////
            HostDC.EndDraw();

            using (D2DBitmap loadBp = new D2DBitmap(HostDC, Size,
                                                    new BitmapProperties1(HostDC.PixelFormat, HostDC.DotsPerInch.Width, HostDC.DotsPerInch.Height, BitmapOptions.Target | BitmapOptions.CannotDraw)), loadBp2 = new D2DBitmap(HostDC, Size,
                                                                                                                                                                                                                              new BitmapProperties1(HostDC.PixelFormat, HostDC.DotsPerInch.Width, HostDC.DotsPerInch.Height, BitmapOptions.None)))
            {
                var old_target = HostDC.Target;


                HostDC.Target = loadBp;

                HostDC.BeginDraw();
                HostDC.Clear(Color);
                var RCP = RenderGroup.ToArray();
                foreach (var i in RCP)
                {
                    i?.Render();
                }

                HostDC.EndDraw();

                if (Effecting != null)
                {
                    loadBp2.CopyFromBitmap(loadBp);
                    var resultEff = Effecting(loadBp2, HostDC);

                    if (resultEff == null)
                    {
                        Effecting = null;
                        goto tag;
                    }
                    var resultIm = resultEff.Output;
                    HostDC.BeginDraw();
                    HostDC.Clear(Color);
                    HostDC.DrawImage(resultIm, new RawVector2(0, 0), null, SharpDX.Direct2D1.InterpolationMode.Linear, CompositeMode.SourceOver);
                    HostDC.EndDraw();
                    resultEff.Dispose();
                    resultIm.Dispose();
                }
tag:
                loadBp2.CopyFromBitmap(loadBp);
                HostDC.Target = old_target;
                HostDC.BeginDraw();

                if (old_target as D2DBitmap == null)
                {
                    old_target.Dispose();
                }

                if (Effecting != null)
                {
                }

                HostDC.DrawBitmap(loadBp2, OutPutRange, 1f, SharpDX.Direct2D1.InterpolationMode.Linear, Range, null);
            }
        }
コード例 #8
0
 public BitmapFrameD2D1(BouncingBallRenderer renderer, D2D1.DeviceContext context2D)
     : base(renderer)
 {
     using (var surface = Texture.QueryInterface <SharpDX.DXGI.Surface>())
     {
         Bitmap = new D2D1.Bitmap1(context2D, surface);
     }
 }
コード例 #9
0
 public ProcessBar(DeviceContext DC) : base(DC)
 {
     using (WICBitmap sc = Direct2DHelper.LoadBitmap("assets\\process.bmp"))
         using (D2DBitmap sc_cv = D2DBitmap.FromWicBitmap(HostDC, sc))
         {
             br = new BitmapBrush(HostDC, sc_cv);
         }
     br.ExtendModeX = ExtendMode.Mirror;
 }
コード例 #10
0
 public void ResizeScreen2()
 {
     d2dContext2.Target = null;
     _backBuffer2.Dispose();
     _targetBitmap2.Dispose();
     swapChain2.ResizeBuffers(1, 0, 0, DXGI.Format.B8G8R8A8_UNorm, DXGI.SwapChainFlags.None);
     _backBuffer2       = DXGI.Surface.FromSwapChain(swapChain2, 0);
     _targetBitmap2     = new D2D1.Bitmap1(d2dContext2, _backBuffer2);
     d2dContext2.Target = _targetBitmap2;
 }
コード例 #11
0
 public void ResizeScreen1()
 {
     d2dContext.Target = null;
     _backBuffer.Dispose();
     _targetBitmap.Dispose();
     swapChain.ResizeBuffers(1, 0, 0, DXGI.Format.B8G8R8A8_UNorm, DXGI.SwapChainFlags.None);
     _backBuffer       = DXGI.Surface.FromSwapChain(swapChain, 0);
     _targetBitmap     = new D2D1.Bitmap1(d2dContext, _backBuffer);
     d2dContext.Target = _targetBitmap;
 }
コード例 #12
0
ファイル: D2DImage.cs プロジェクト: rootacite/Shinengine
        public InteractiveObject(DeviceContext dc, WICBitmap[] wic) : base(dc, wic[0])
        {
            var ims = new List <D2DBitmap>();

            foreach (var i in wic)
            {
                ims.Add(D2DBitmap.FromWicBitmap(dc, i));
            }

            characters = ims.ToArray();
            listOfExist.Add(this);
        }
コード例 #13
0
        /// <summary>
        /// Creates all resources
        /// </summary>
        private void CreateResources(int viewWidth, int viewHeight, DpiScaling dpiScaling, bool forceInit)
        {
            // Calculate the screen size in device independent units
            Size2F scaledScreenSize = new Size2F(
                (float)viewWidth / dpiScaling.ScaleFactorX,
                (float)viewHeight / dpiScaling.ScaleFactorY);

            // Cancel here if the device does not support 2D rendering
            if ((!forceInit) &&
                (!m_device.Supports2D))
            {
                return;
            }

            if (!m_device.IsUsingFallbackMethodFor2D)
            {
                // Create the render target
                using (DXGI.Surface dxgiSurface = m_renderTarget3D.QueryInterface <DXGI.Surface>())
                {
                    D2D.BitmapProperties1 bitmapProperties = new D2D.BitmapProperties1();
                    bitmapProperties.DpiX          = dpiScaling.DpiX;
                    bitmapProperties.DpiY          = dpiScaling.DpiY;
                    bitmapProperties.BitmapOptions = D2D.BitmapOptions.Target | D2D.BitmapOptions.CannotDraw;
                    bitmapProperties.PixelFormat   = new D2D.PixelFormat(GraphicsHelper.DEFAULT_TEXTURE_FORMAT, D2D.AlphaMode.Premultiplied);

                    m_renderTargetBitmap = new SharpDX.Direct2D1.Bitmap1(m_device.DeviceContextD2D, dxgiSurface, bitmapProperties);
                    m_renderTarget2D     = m_device.DeviceContextD2D;
                    m_graphics2D         = new Graphics2D(m_device, m_device.DeviceContextD2D, scaledScreenSize);
                }
            }
            else
            {
                using (DXGI.Surface dxgiSurface = m_renderTarget3D.QueryInterface <DXGI.Surface>())
                {
                    m_renderTarget2D = new D2D.RenderTarget(
                        m_device.Core.FactoryD2D,
                        dxgiSurface,
                        new D2D.RenderTargetProperties()
                    {
                        MinLevel    = D2D.FeatureLevel.Level_10,
                        Type        = D2D.RenderTargetType.Default,
                        Usage       = D2D.RenderTargetUsage.ForceBitmapRemoting,
                        PixelFormat = new D2D.PixelFormat(GraphicsHelper.DEFAULT_TEXTURE_FORMAT, D2D.AlphaMode.Premultiplied),
                        DpiX        = dpiScaling.DpiX,
                        DpiY        = dpiScaling.DpiY
                    });
                    m_graphics2D = new Graphics2D(m_device, m_renderTarget2D, scaledScreenSize);
                    return;
                }
            }
        }
コード例 #14
0
        public static void CreateDeviceContextCPUBitmap(
            Direct2D1.DeviceContext target, int width, int height)
        {
            var props = new Direct2D1.BitmapProperties1
            {
                BitmapOptions = Direct2D1.BitmapOptions.Target | Direct2D1.BitmapOptions.GdiCompatible,
                PixelFormat   = new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Premultiplied)
            };

            using (var bitmap = new Direct2D1.Bitmap1(target, new Size2(width, height), props))
            {
                target.Target = bitmap;
            }
        }
コード例 #15
0
        internal static D2D.Bitmap1 CreateCpuReadBitmap(int width, int height)
        {
            var cpuReadBitmap = new D2D.Bitmap1(
                _d2DDeviceContext,
                new DrawingSize(width, height),
                new D2D.BitmapProperties1(
                    new D2D.PixelFormat(
                        SharpDX.DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                    Windows.Graphics.Display.DisplayProperties.LogicalDpi,
                    Windows.Graphics.Display.DisplayProperties.LogicalDpi,
                    D2D.BitmapOptions.CpuRead | D2D.BitmapOptions.CannotDraw));

            return(cpuReadBitmap);
        }
コード例 #16
0
        internal static D2D.Bitmap1 CreateRenderTargetBitmap(int width, int height)
        {
            var renderTargetBitmap = new D2D.Bitmap1(
                _d2DDeviceContext,
                new DrawingSize(width, height),
                new D2D.BitmapProperties1(
                    new D2D.PixelFormat(
                        Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                    Windows.Graphics.Display.DisplayProperties.LogicalDpi,
                    Windows.Graphics.Display.DisplayProperties.LogicalDpi,
                    D2D.BitmapOptions.Target));

            return(renderTargetBitmap);
        }
コード例 #17
0
        public void InitializeDeviceResources()
        {
            ModeDescription backBufferDesc = new ModeDescription(1600, 900, new Rational(60, 1), Format.B8G8R8A8_UNorm);

            SwapChainDescription swapChainDesc = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = this.Handle,
                IsWindowed        = true
            };

            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug;

            //SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out d3dDevice, out swapChain);
            d3dDeviceContext = d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();

            using (SharpDX.Direct3D11.Texture2D backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
            {
                renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            System.Drawing.Graphics g = this.CreateGraphics();

            SharpDX.Direct2D1.Factory d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded, SharpDX.Direct2D1.DebugLevel.None);

            // Create Direct2D device
            var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>();

            //d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice);
            d2dDevice  = new SharpDX.Direct2D1.Device(dxgiDevice);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
            //d2dContext.PrimitiveBlend = PrimitiveBlend.SourceOver;

            BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore),
                                                                 g.DpiX, g.DpiY, BitmapOptions.Target | BitmapOptions.CannotDraw);

            Surface backBuffer2D = swapChain.GetBackBuffer <Surface>(0);

            //new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied)
            SharpDX.Direct2D1.RenderTargetProperties rtp = new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore));
            d2dRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, backBuffer2D, rtp);
            d2dTarget       = new Bitmap1(d2dContext, backBuffer2D, properties);

            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
        }
コード例 #18
0
        public void Resize()
        {
            canDraw = false;
            device.ImmediateContext.ClearState();
            d2dTarget.Dispose();
            d2dContext.Dispose();
            backBuffer.Dispose();

            swapChain.ResizeBuffers(2, 0, 0, Format.Unknown, SwapChainFlags.None);

            backBuffer        = Surface.FromSwapChain(swapChain, 0);
            d2dContext        = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
            d2dTarget         = new Bitmap1(d2dContext, backBuffer, properties);
            d2dContext.Target = d2dTarget;
            canDraw           = true;
        }
コード例 #19
0
        public override void Dispose()
        {
            if (_canvas != null)
            {
                _canvas.Dispose();
                _canvas = null;
            }

            if (_bitmap != null && _disposeBitmap)
            {
                _bitmap.Dispose();
                _bitmap = null;
            }

            base.Dispose();
        }
コード例 #20
0
        public RenderController(IntPtr windowHandle)
        {
            writeFactory = new SharpDX.DirectWrite.Factory();

            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device
                                                      (
                DriverType.Hardware,
                DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport
                                                      );

            device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            SwapChainDescription1 description = new SwapChainDescription1()
            {
                Width             = 0,
                Height            = 0,
                Format            = Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 2,
                Scaling           = Scaling.None,
                SwapEffect        = SwapEffect.FlipSequential,
            };

            swapChain  = new SwapChain1(dxgiFactory2, device, windowHandle, ref description);
            backBuffer = Surface.FromSwapChain(swapChain, 0);

            d2dDevice  = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
            properties = new BitmapProperties1
                         (
                new SharpDX.Direct2D1.PixelFormat
                (
                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied
                ),
                0, 0, BitmapOptions.Target | BitmapOptions.CannotDraw
                         );
            d2dTarget         = new Bitmap1(d2dContext, backBuffer, properties);
            d2dContext.Target = d2dTarget;

            canDraw = true;
        }
コード例 #21
0
 public static void CreateDeviceSwapChainBitmap(
     DXGI.SwapChain1 swapChain,
     Direct2D1.DeviceContext target)
 {
     using (var surface = swapChain.GetBackBuffer <DXGI.Surface>(0))
     {
         var props = new Direct2D1.BitmapProperties1
         {
             BitmapOptions = Direct2D1.BitmapOptions.Target | Direct2D1.BitmapOptions.CannotDraw,
             PixelFormat   = new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Ignore)
         };
         using (var bitmap = new Direct2D1.Bitmap1(target, surface, props))
         {
             target.Target = bitmap;
         }
     }
 }
コード例 #22
0
        public void Resize(int width, int height)
        {
            ResolutionX = width; ResolutionY = height;
            MainCamera.renderTargetView?.Dispose();
            MainCamera.depthStencilView?.Dispose();
            D2DTarget?.Dispose();
            D2DContext?.Dispose();

            MainCamera.AspectRatio = width / (float)height;

            swapChain.ResizeBuffers(swapChain.Description.BufferCount, width, height, DXGI.Format.Unknown, DXGI.SwapChainFlags.None);

            D2DContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);
            using (DXGI.Surface surface = swapChain.GetBackBuffer <DXGI.Surface>(0))
                D2DTarget = new D2D1.Bitmap1(D2DContext, surface,
                                             new D2D1.BitmapProperties1(new D2D1.PixelFormat(DXGI.Format.R8G8B8A8_UNorm, D2D1.AlphaMode.Premultiplied),
                                                                        D2DFactory.DesktopDpi.Height, D2DFactory.DesktopDpi.Width, D2D1.BitmapOptions.CannotDraw | D2D1.BitmapOptions.Target)
                                             );
            D2DContext.Target = D2DTarget;

            // render target
            using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0))
                MainCamera.renderTargetView = new D3D11.RenderTargetView(Device, backBuffer);

            // depth buffer
            D3D11.Texture2DDescription depthDescription = new D3D11.Texture2DDescription()
            {
                Format            = DXGI.Format.D32_Float,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = width,
                Height            = height,
                SampleDescription = new DXGI.SampleDescription(SampleCount, SampleQuality),
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.DepthStencil,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            };
            using (D3D11.Texture2D depthTexture = new D3D11.Texture2D(Device, depthDescription))
                MainCamera.depthStencilView = new D3D11.DepthStencilView(Device, depthTexture);

            // viewport
            Viewport = new Viewport(0, 0, width, height);
            Context.Rasterizer.SetViewport(Viewport);
        }
コード例 #23
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;
        }
コード例 #24
0
 private void LoadResources()
 {
     m_textBrush        = new D2D1.SolidColorBrush(m_D2DContext.d2dContext2, new SharpDX.Color(128, 0, 255));
     roundedRecOutColor = new D2D1.SolidColorBrush(m_D2DContext.d2dContext2, new SharpDX.Color(32, 117, 81));
     roundedRecInColor  = new D2D1.SolidColorBrush(m_D2DContext.d2dContext2, new SharpDX.Color(234, 137, 6));
     m_textFormat15     = new TextFormat(m_D2DContext.dw_Factory, "Arial", FontWeight.UltraBold, FontStyle.Normal, fontSize15);
     m_textFormat10     = new TextFormat(m_D2DContext.dw_Factory, "Arial", FontWeight.Bold, FontStyle.Normal, fontSize10);
     //m_textFormat10.ParagraphAlignment = ParagraphAlignment.Center;
     //m_textFormat10.TextAlignment = TextAlignment.Center;
     m_textFormat10.SetParagraphAlignment(ParagraphAlignment.Center);
     m_textFormat10.SetTextAlignment(TextAlignment.Center);
     fontFamily              = new System.Drawing.FontFamily("Arial");
     m_Bitmap1               = new D2D1.Bitmap1(m_D2DContext.d2dContextCdgText, new Size2(SurfaceW, SurfaceH), BitmapProps1);
     m_Bitmap1FullScreen     = new D2D1.Bitmap1(m_D2DContext.d2dContextCdgText2, new Size2(SurfaceW2, SurfaceH2), BitmapProps1);
     m_Shadow                = new D2D1.Effects.Shadow(m_D2DContext.d2dContextCdgText);
     m_ShadowFullScreen      = new D2D1.Effects.Shadow(m_D2DContext.d2dContextCdgText2);
     m_affineTransformEffect = new D2D1.Effects.AffineTransform2D(m_D2DContext.d2dContextCdgText2);
     m_compositeEffect       = new D2D1.Effects.Composite(m_D2DContext.d2dContextCdgText2);
 }
コード例 #25
0
        public DXBitmapExportContext(int width, int height, float displayScale = 1, int dpi = 72, bool disposeBitmap = true)
            : base(width, height, dpi)
        {
            _disposeBitmap = disposeBitmap;

            if (_default3DDevice == null)
            {
                _default3DDevice = new d3d.Device(DriverType.Hardware, d3d.DeviceCreationFlags.VideoSupport | d3d.DeviceCreationFlags.BgraSupport);
                // default3DDevice = new d3d.Device(DriverType.Warp,  d3d.DeviceCreationFlags.BgraSupport);

                _default3DDevice1 = _default3DDevice.QueryInterface <d3d.Device1>();
                _dxgiDevice       = _default3DDevice1.QueryInterface <dxgi.Device>(); // get a reference to DXGI device

                _device2D = new d2.Device(_dxgiDevice);

                // initialize the DeviceContext - it will be the D2D render target
                _deviceContext = new d2.DeviceContext(_device2D, d2.DeviceContextOptions.None);
            }

            // specify a pixel format that is supported by both and WIC
            _pixelFormat = new d2.PixelFormat(dxgi.Format.B8G8R8A8_UNorm, d2.AlphaMode.Premultiplied);

            // create the d2d bitmap description using default flags
            var bitmapProps = new d2.BitmapProperties1(_pixelFormat, Dpi, Dpi,
                                                       d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            // create our d2d bitmap where all drawing will happen
            _bitmap = new d2.Bitmap1(_deviceContext, new Size2(width, height), bitmapProps);

            // associate bitmap with the d2d context
            _deviceContext.Target = _bitmap;
            _deviceContext.BeginDraw();
            _deviceContext.Clear(new Color4 {
                Alpha = 0, Blue = 0, Green = 0, Red = 0
            });

            _canvas = new DXCanvas(_deviceContext)
            {
                DisplayScale = displayScale
            };
        }
コード例 #26
0
        private void CleanUpDeviceIndependentResources()
        {
            if (_deviceIndependedResourcesCreated)
            {
                OnCleanUpDeviceIndependentResources();
            }



            if (_surface != null && !_surface.IsDisposed)
            {
                _surface.Dispose();
            }
            _surface = null;

            if (_dc != null && !_dc.IsDisposed)
            {
                _dc.Dispose();
            }
            _dc = null;

            if (_d2dDevice != null && !_d2dDevice.IsDisposed)
            {
                _d2dDevice.Dispose();
            }
            _d2dDevice = null;

            if (_renderTarget != null && !_renderTarget.IsDisposed)
            {
                _renderTarget.Dispose();
            }
            _renderTarget = null;

            if (_d2dFactory != null && !_d2dFactory.IsDisposed)
            {
                _d2dFactory.Dispose();
            }
            _d2dFactory = null;
        }
コード例 #27
0
        public SharpDX.Direct2D1.Bitmap1 CreateRenderTarget(
            float width,
            float height,
            float dpi = DEFAULT_DPI,
            SharpDX.DXGI.Format format        = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied)
        {
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1()
            {
                BitmapOptions = BitmapOptions.Target,
                DpiX          = dpi,
                DpiY          = dpi,
                PixelFormat   = new SharpDX.Direct2D1.PixelFormat(format, alpha)
            };

            var pixelWidth  = SizeDipsToPixels(width, dpi);
            var pixelHeight = SizeDipsToPixels(height, dpi);

            var bitmap = new SharpDX.Direct2D1.Bitmap1(d2dResourceCreationDeviceContext,
                                                       new Size2(pixelWidth, pixelHeight), bitmapProperties);

            return(bitmap);
        }
コード例 #28
0
 public void InitScreen1(IntPtr handle)
 {
     d2dContext        = new D2D1.DeviceContext(_d2dDevice, D2D1.DeviceContextOptions.None);
     d2dContextCdgText = new D2D1.DeviceContext(_d2dDevice, D2D1.DeviceContextOptions.None);
     // DXGI SwapChain
     DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
     {
         BufferCount       = 1,
         Usage             = DXGI.Usage.RenderTargetOutput,
         OutputHandle      = handle,
         IsWindowed        = true,
         ModeDescription   = new DXGI.ModeDescription(0, 0, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm),
         SampleDescription = new DXGI.SampleDescription(1, 0),
         SwapEffect        = DXGI.SwapEffect.Discard
     };
     swapChain = new DXGI.SwapChain(_dxgiDevice.GetParent <DXGI.Adapter>().GetParent <DXGI.Factory>(), _d3d11Device, swapChainDesc);
     // BackBuffer
     _backBuffer = DXGI.Surface.FromSwapChain(swapChain, 0);
     //BackBuffer DeviceContext
     _targetBitmap     = new D2D1.Bitmap1(d2dContext, _backBuffer);
     d2dContext.Target = _targetBitmap;
     // _dcBrush = new D2D1.SolidColorBrush(d2dContext, Color.Black);
 }
コード例 #29
0
        private void CreateDeviceIndependentResources()
        {
            _dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device>();
            _d2dDevice  = new SharpDX.Direct2D1.Device(_dxgiDevice);
            _d2dFactory = _d2dDevice.Factory;
            var dpiX = _d2dFactory.DesktopDpi.Width;
            var dpiY = _d2dFactory.DesktopDpi.Height;

            _dc = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, DeviceContextOptions.None);
            _dc.PrimitiveBlend = PrimitiveBlend.SourceOver;

            var format     = new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied);
            var properties = new BitmapProperties1(format, dpiX, dpiY, BitmapOptions.Target | BitmapOptions.CannotDraw);

            _surface      = _swapChain.GetBackBuffer <Surface>(0);
            _renderTarget = new Bitmap1(_dc, _surface, properties);

            _dc.Target        = _renderTarget;
            _dc.AntialiasMode = AntialiasMode.PerPrimitive;

            OnCreateDeviceIndependentResources();
            this._deviceIndependedResourcesCreated = true;
        }
コード例 #30
0
ファイル: D2DImage.cs プロジェクト: rootacite/Shinengine
        }//ignore

        unsafe public void Commit()
        {
            D2DBitmap m_copied_buffer = new D2DBitmap(m_d2d_info.View, new Size2(Width, Height), new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 72, 72, BitmapOptions.CannotDraw | BitmapOptions.CpuRead));

            m_copied_buffer.CopyFromBitmap(m_d2d_info._bufferBack);

            var m_copied_map = m_copied_buffer.Map(MapOptions.Read);

            buffer.Lock();

            for (int i = 0; i < m_copied_buffer.PixelSize.Height; i++)
            {
                int *source_base = (int *)(m_copied_map.DataPointer + i * m_copied_map.Pitch);
                int *target_base = (int *)(buffer.BackBuffer + i * buffer.BackBufferStride);

                RtlMoveMemory((void *)target_base, (void *)source_base, 4 * m_copied_buffer.PixelSize.Width);
            }

            buffer.AddDirtyRect(new Int32Rect(0, 0, Width, Height));
            buffer.Unlock();

            m_copied_buffer.Unmap();
            m_copied_buffer.Dispose();
        }//把后台数据呈现到前台
コード例 #31
0
        internal static D2D.Bitmap1 CreateCpuReadBitmap(int width, int height)
        {
            var cpuReadBitmap = new D2D.Bitmap1(
                _d2DDeviceContext,
                new Size2(width, height),
                new D2D.BitmapProperties1(
                    new D2D.PixelFormat(
                        SharpDX.DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                        LogicalDpi,
                        LogicalDpi,
                        D2D.BitmapOptions.CpuRead | D2D.BitmapOptions.CannotDraw));

            return cpuReadBitmap;
        }
コード例 #32
0
		/// <summary>
		/// 使用指定的渲染目标控件创建渲染目标。
		/// </summary>
		/// <param name="control">渲染的目标控件。</param>
		public void CreateRenderTarget(Control control)
		{
			if (SupportD3D)
			{
				// 创建 Direct3D SwapChain。
				SwapChainDescription swapChainDesc = new SwapChainDescription()
				{
					BufferCount = 1,
					Usage = Usage.RenderTargetOutput,
					OutputHandle = control.Handle,
					IsWindowed = true,
					ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format),
					SampleDescription = new SampleDescription(1, 0),
					SwapEffect = SwapEffect.Discard
				};
				this.swapChain = new SwapChain(dxgiDevice.GetParent<Adapter>().GetParent<DXGIFactory>(),
					d3DDevice, swapChainDesc);
				this.backBuffer = Surface.FromSwapChain(this.swapChain, 0);
				this.targetBitmap = new Bitmap1(this.d2DContext, backBuffer);
				this.renderTarget = new DeviceContext(this.d2DDevice, DeviceContextOptions.None);
				((DeviceContext)this.renderTarget).Target = targetBitmap;
			}
			else
			{
				// 创建 Direct2D 工厂。
				// 渲染参数。
				RenderTargetProperties renderProps = new RenderTargetProperties
				{
					PixelFormat = D2PixelFormat,
					Usage = RenderTargetUsage.None,
					Type = RenderTargetType.Default
				};
				// 渲染目标属性。
				HwndRenderTargetProperties hwndProps = new HwndRenderTargetProperties()
				{
					Hwnd = control.Handle,
					PixelSize = new Size2(control.ClientSize.Width, control.ClientSize.Height),
					PresentOptions = PresentOptions.None
				};
				// 渲染目标。
				this.renderTarget = new WindowRenderTarget(d2DFactory, renderProps, hwndProps)
				{
					AntialiasMode = AntialiasMode.PerPrimitive
				};
			}
		}
コード例 #33
0
ファイル: MeshEditor.cs プロジェクト: Artentus/GameUtils
 void Resize()
 {
     d2dDeviceContext.Target = null;
     d2dSurface.Dispose();
     swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);
     Surface1 dxgiSurface = swapChain.GetBackBuffer<Surface1>(0);
     var props = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
         d2dDeviceContext.DotsPerInch.Width,
         d2dDeviceContext.DotsPerInch.Height,
         BitmapOptions.Target | BitmapOptions.CannotDraw);
     d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props);
     dxgiSurface.Dispose();
     d2dDeviceContext.Target = d2dSurface;
 }
コード例 #34
0
        /// <summary>
        /// Creates the D2D render target from the associated swap chain.
        /// </summary>
        private void CreateD2DRenderTarget()
        {
            var renderTarget = _presenter.BackBuffer;

            var dpi = DisplayProperties.LogicalDpi;

            // 1. Use same format as the underlying render target with premultiplied alpha mode
            // 2. Use correct DPI
            // 3. Deny drawing direct calls and specify that this is a render target.
            var bitmapProperties = new D2D.BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(renderTarget.Format, D2D.AlphaMode.Premultiplied),
                                                             dpi,
                                                             dpi,
                                                             D2D.BitmapOptions.CannotDraw | D2D.BitmapOptions.Target);

            // create the bitmap render target and assign it to the device context
            _bitmapTarget = _disposeCollector.Collect(new D2D.Bitmap1(_d2dDeviceContext, renderTarget, bitmapProperties));
            _d2dDeviceContext.Target = _bitmapTarget;
        }
コード例 #35
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

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

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

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

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

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

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

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

            // Create a solid color brush.
            solidBrush = new SolidColorBrush(d2dContext, Color.Coral);

            // Create a linear gradient brush.
            // Note that the StartPoint and EndPoint values are set as absolute coordinates of the surface you are drawing to,
            // NOT the geometry we will apply the brush.
            linearGradientBrush = new LinearGradientBrush(d2dContext, new LinearGradientBrushProperties()
                {
                    StartPoint = new Vector2(50, 0),
                    EndPoint = new Vector2(450, 0),
                },
                new GradientStopCollection(d2dContext, new GradientStop[]
                    {
                        new GradientStop()
                        {
                            Color = Color.Blue,
                            Position = 0,
                        },
                        new GradientStop()
                        {
                            Color = Color.Green,
                            Position = 1,
                        }
                    }));

            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new RadialGradientBrush(d2dContext, new RadialGradientBrushProperties()
                {
                    Center = new Vector2(250, 525),
                    RadiusX = 100,
                    RadiusY = 100,
                },
                new GradientStopCollection(d2dContext, new GradientStop[]
                {
                        new GradientStop()
                        {
                            Color = Color.Yellow,
                            Position = 0,
                        },
                        new GradientStop()
                        {
                            Color = Color.Red,
                            Position = 1,
                        }
                }));
        }
コード例 #36
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Create rendertarget for drawing the tiling brush
            brushTarget = new Bitmap1(d2dContext, new Size2((int)(terrainBitmap.Size.Width * 10), (int)terrainBitmap.Size.Height), new BitmapProperties1()
            {
                PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                BitmapOptions = BitmapOptions.Target
            });
        }
コード例 #37
0
ファイル: Program.cs プロジェクト: MaybeMars/SharpDX-Samples
        static void Main()
        {
            // input and output files are supposed to be in the program folder
            var inputPath = "Input.png";
            var outputPath = "Output.png";

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // INITIALIZATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.Debug); // take out the Debug flag for better performance

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var decoder = new wic.PngBitmapDecoder(imagingFactory); // we will load a PNG image
            var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); // open the image file for reading
            decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // load the base image into a D2D Bitmap
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;
            var pixelWidth = inputImageSize.Width;
            var pixelHeight = inputImageSize.Height;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // EFFECT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // Effect 1 : BitmapSource - take decoded image data and get a BitmapSource from it
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // Effect 2 : GaussianBlur - give the bitmapsource a gaussian blurred effect
            var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext);
            gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true);
            gaussianBlurEffect.StandardDeviation = 5f;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // OVERLAY TEXT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); // create the text format of specified font configuration

            // draw a long text to show the automatic line wrapping
            var textToDraw = "Some long text to show the drawing of preformatted "
                             + "glyphs using DirectWrite on the Direct2D surface."
                             + " Notice the automatic wrapping of line if it exceeds desired width.";

            // create the text layout - this improves the drawing performance for static text
            // as the glyph positions are precalculated
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            var textBrush = new d2.SolidColorBrush(d2dContext, Color.LightGreen);

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.DrawImage(gaussianBlurEffect);
            d2dContext.DrawTextLayout(new Vector2(5f, 5f), textLayout, textBrush);
            d2dContext.EndDraw();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // delete the output file if it already exists
            if (System.IO.File.Exists(outputPath)) System.IO.File.Delete(outputPath);

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write);

            // select the image encoding format HERE
            var encoder = new wic.PngBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(pixelWidth, pixelHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight));

            bitmapFrameEncode.Commit();
            encoder.Commit();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            textBrush.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();
            formatConverter.Dispose();
            gaussianBlurEffect.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            inputStream.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();

            // show the result
            System.Diagnostics.Process.Start(outputPath);
        }
コード例 #38
0
        public SharpDX.Direct2D1.Bitmap1 CreateRenderTarget(
            float width,
            float height,
            float dpi = DEFAULT_DPI,
            SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied)
        {

            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1()
            {
                BitmapOptions = BitmapOptions.Target,
                DpiX = dpi,
                DpiY = dpi,
                PixelFormat = new SharpDX.Direct2D1.PixelFormat(format, alpha)
            };

            var pixelWidth = SizeDipsToPixels(width, dpi);
            var pixelHeight = SizeDipsToPixels(height, dpi);
            
            var bitmap = new SharpDX.Direct2D1.Bitmap1(d2dResourceCreationDeviceContext,
                new Size2(pixelWidth, pixelHeight), bitmapProperties);

            return bitmap;
        }
コード例 #39
0
        public SharpDX.Direct2D1.DeviceContext1 CreateDrawingContext(
            Bitmap1 renderTarget, 
            DeviceContextOptions options = DeviceContextOptions.None)
        {

            var drawingContext = new SharpDX.Direct2D1.DeviceContext1(d2dDevice, options);
            drawingContext.Target = renderTarget;
            return drawingContext;

        }
コード例 #40
0
        internal static D2D.Bitmap1 CreateRenderTargetBitmap(int width, int height)
        {
            var renderTargetBitmap = new D2D.Bitmap1(
                _d2DDeviceContext,
                new Size2(width, height),
                new D2D.BitmapProperties1(
                    new D2D.PixelFormat(
                        Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                        LogicalDpi,
                        LogicalDpi,
                        D2D.BitmapOptions.Target));

            return renderTargetBitmap;
        }
コード例 #41
0
ファイル: Direct2D.cs プロジェクト: BEEden/GdiBench
        public static MemoryStream Resize(System.IO.Stream source, int maxwidth, int maxheight, Action beforeDrawImage, Action afterDrawImage)
        {
            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Warp,
                                                              d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.SingleThreaded | d3d.DeviceCreationFlags.PreventThreadingOptimizations);

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            var decoder = new wic.BitmapDecoder(imagingFactory,source, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            //Calculate size
            var resultSize = MathUtil.ScaleWithin(inputImageSize.Width,inputImageSize.Height,maxwidth,maxheight);
            var newWidth = resultSize.Item1;
            var newHeight = resultSize.Item2;

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(newWidth, newHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            var bitmapSourceEffect = new d2.Effects.BitmapSourceEffect(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            beforeDrawImage();
            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.Transform = Matrix3x2.Scaling(new Vector2((float)(newWidth / (float)inputImageSize.Width), (float)(newHeight / (float)inputImageSize.Height)));
            d2dContext.DrawImage(bitmapSourceEffect, d2.InterpolationMode.HighQualityCubic);
            d2dContext.EndDraw();
            afterDrawImage();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var ms = new MemoryStream();

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory,ms);

            // select the image encoding format HERE
            var encoder = new wic.JpegBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(newWidth, newHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96,  0, 0, newWidth, newHeight));

            bitmapFrameEncode.Commit();
            encoder.Commit();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            formatConverter.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();
            return ms;
        }
コード例 #42
0
        /// <summary>
        /// 使用 DirectX 在該表面上繪圖
        /// 只會在 updateRect 參數中指定的更新區域進行繪圖。
        /// </summary>
        /// <param name="updateRect"></param>
        public void BeginDraw(Windows.Foundation.Rect updateRect)
        {
            // Express target area as a native RECT type.
            var updateRectNative = new Rectangle
            {
                Left = (int)updateRect.Left,
                Top = (int)updateRect.Top,
                Right = (int)updateRect.Right,
                Bottom = (int)updateRect.Bottom
            };

            // Query for ISurfaceImageSourceNative interface.
            using (var sisNative = ComObject.QueryInterface<ISurfaceImageSourceNative>(this))
            {
                // Begin drawing - returns a target surface and an offset to use as the top left origin when drawing.
                try
                {
                    Point offset;
                    using (var surface = sisNative.BeginDraw(updateRectNative, out offset))
                    {
                        var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                            new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                            96,
                            96,
                            SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

                        // Create render target.
                        using (var bitmap = new Bitmap1(d2dContext, surface, bitmapProperties))
                        {
                            // Set context's render target.
                            d2dContext.Target = bitmap;
                        }

                        // Begin drawing using D2D context.
                        d2dContext.BeginDraw();

                        // Apply a clip and transform to constrain updates to the target update area.
                        // This is required to ensure coordinates within the target surface remain
                        // consistent by taking into account the offset returned by BeginDraw, and
                        // can also improve performance by optimizing the area that is drawn by D2D.
                        // Apps should always account for the offset output parameter returned by 
                        // BeginDraw, since it may not match the passed updateRect input parameter's location.
                        d2dContext.PushAxisAlignedClip(
                            new RectangleF(
                                (offset.X),
                                (offset.Y),
                                (offset.X + (float)updateRect.Width),
                                (offset.Y + (float)updateRect.Height)
                                ),
                            AntialiasMode.Aliased
                            );

                        d2dContext.Transform = Matrix3x2.Translation(offset.X, offset.Y);
                    }
                }
                catch (SharpDXException ex)
                {
                    if (ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceRemoved ||
                        ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceReset)
                    {
                        // If the device has been removed or reset, attempt to recreate it and continue drawing.
                        CreateDeviceResources();
                        BeginDraw(updateRect);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
コード例 #43
0
		/// <summary>
		/// 创建具有指定角度凸起效果的图像。
		/// </summary>
		/// <param name="imageBrush">原始的拼图图像笔刷。</param>
		/// <param name="source">用于生成图像的源位图。</param>
		/// <param name="blacks">黑色图形集合。</param>
		/// <param name="whites">白色图形集合。</param>
		/// <param name="ct">取消任务的通知。</param>
		/// <returns>具有指定角度凸起效果的图像。</returns>
		private Bitmap CreateImage(Brush imageBrush, Bitmap1 source,
			IList<Geometry> blacks, IList<Geometry> whites, CancellationToken ct)
		{
			ct.ThrowIfCancellationRequested();
			Bitmap1 target = null;
			try
			{
				target = DeviceManager.CreateBitmap(imageSize);
				// 一次性绘制所有不相邻的拼图碎片。
				ct.ThrowIfCancellationRequested();
				this.CreateImage(imageBrush, source, target, blacks, ct);
				ct.ThrowIfCancellationRequested();
				this.CreateImage(imageBrush, source, target, whites, ct);
				return target;
			}
			catch
			{
				if (target != null)
				{
					target.Dispose();
				}
				throw;
			}
		}
コード例 #44
0
ファイル: BufferManager.cs プロジェクト: JoshGrooms/Tesseract
        /// <summary>
        /// Create the swap chain and render targets, which depend on the size of the window.
        /// </summary>
        /// <param name="window"></param>
        private void CreateSizeResources(Tesseract gameEngine)
        {
            // Get the 2D context reference
            var context2D = gameEngine.DeviceManager.Context2D;

            // Release all buffers before resizing the swap chain
            RemoveAndDispose(ref BackBuffer);
            RemoveAndDispose(ref RenderTargetView);
            RemoveAndDispose(ref DepthStencilView);
            RemoveAndDispose(ref DepthBuffer);
            RemoveAndDispose(ref RenderTarget);
            context2D.Target = null;

            // If a swap chain already exists, resize it instead of creating a new one
            int scHeight = (int)(gameEngine.WindowManager.WindowBounds.Height * gameEngine.DeviceManager.DPI / 96);
            int scWidth = (int)(gameEngine.WindowManager.WindowBounds.Width * gameEngine.DeviceManager.DPI / 96);
            if (SwapChain != null)
            {
                SwapChain.ResizeBuffers(
                    SwapChain.Description1.BufferCount,
                    scWidth,
                    scHeight,
                    SwapChain.Description.ModeDescription.Format,
                    SwapChain.Description.Flags);
            }
            // Otherwise, create a new swap chain
            else { CreateSwapChain(gameEngine.WindowManager.Window.Handle, scWidth, scHeight); }

            // Create a back buffer, which will be used as the final 3D render target
            BackBuffer = ToDispose(Texture2D.FromSwapChain<Texture2D>(SwapChain, 0));
            var bbDescription = BackBuffer.Description;

            // Set up render target resources
            RenderTargetView = ToDispose(new RenderTargetView(Device3D, BackBuffer));
            RenderTargetBounds = new Rectangle(0, 0, bbDescription.Width, bbDescription.Height);

            // Create a viewport descriptor of the render size
            Viewport = new ViewportF(RenderTargetBounds);
            Context3D.Rasterizer.SetViewport(Viewport);

            // Create a decription structure for the depth/stencil buffer
            DepthBuffer = ToDispose(new Texture2D(Device3D, new Texture2DDescription()
                {
                    ArraySize			= 1,
                    BindFlags			= BindFlags.DepthStencil,
                    Format				= Format.D32_Float_S8X24_UInt,
                    Height				= RenderTargetBounds.Height,
                    MipLevels			= 1,
                    SampleDescription	= SwapChain.Description.SampleDescription,
                    Width				= RenderTargetBounds.Width,
                }));

            // Create a view interface for the depth/stencil buffer
            DepthStencilView = ToDispose(new DepthStencilView(
                Device3D,
                DepthBuffer,
                new DepthStencilViewDescription()
                {
                    Dimension = (SwapChain.Description.SampleDescription.Count > 1 || SwapChain.Description.SampleDescription.Quality > 0) ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D
                }));
            Context3D.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            // Set up the Direct2D render target, which will render to the swap chain associated with the window
            var bitmapProperties = new BitmapProperties1(
                new PixelFormat(SwapChain.Description.ModeDescription.Format, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                gameEngine.DeviceManager.DPI,
                gameEngine.DeviceManager.DPI,
                BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get a Direct2D surface from the DXGI back buffer to use as the render target
            using (var dxgiBackBuffer = SwapChain.GetBackBuffer<Surface>(0)) { RenderTarget = ToDispose(new Bitmap1(context2D, dxgiBackBuffer, bitmapProperties)); }

            // Set the render target
            context2D.Target = RenderTarget;

            // Set the text anti-aliasing mode to grayscale to ensure proper rendering of text on intermediate surfaces
            context2D.TextAntialiasMode = TextAntialiasMode.Grayscale;
        }
コード例 #45
0
		/// <summary>
		/// 从指定的形状创建具有凸起效果的图像。
		/// </summary>
		/// <param name="imageBrush">原始的拼图图像笔刷。</param>
		/// <param name="source">源位图。</param>
		/// <param name="target">目标位图。</param>
		/// <param name="geoms">形状列表。</param>
		/// <param name="ct">取消任务的通知。</param>
		private void CreateImage(Brush imageBrush, Bitmap1 source, Bitmap1 target,
			IList<Geometry> geoms, CancellationToken ct)
		{
			this.DeviceContext.Target = source;
			this.DeviceContext.BeginDraw();
			this.DeviceContext.Clear(Color.Transparent);
			int cnt = geoms.Count;
			for (int i = 0; i < cnt; i++)
			{
				if (ct.IsCancellationRequested)
				{
					break;
				}
				this.DeviceContext.FillGeometry(geoms[i], imageBrush);
			}
			this.DeviceContext.EndDraw();
			// 将添加特效后的拼图碎片绘制到位图上。
			ct.ThrowIfCancellationRequested();
			this.DeviceContext.Target = target;
			this.DeviceContext.BeginDraw();
			this.DeviceContext.DrawImage(bevelEffect);
			this.DeviceContext.EndDraw();
		}
コード例 #46
0
ファイル: WorldProcessor.cs プロジェクト: rantingmong/blocm
        public void Start()
        {
            if (ProcessStarted != null)
                ProcessStarted();

            int index           = 0;
            var rendererUtil    = new RendererUtil();

            // obtain file list
            var regionList      = Directory.GetFiles(Path.Combine(worldLocation, "region"), "*.mca").ToList();
            var regionEntries   = new List<RegionEntry>();

            foreach (string region in regionList)
            {
                try
                {
                    // load the region
                    using (RegionFile regionFile = RegionFile.OpenRegion(File.OpenRead(region)))
                    {
                        var renderedChunks = new List<ChunkEntry>();

                        if (RegionLoaded != null)
                            RegionLoaded(regionFile);

                        Debug.WriteLine("Rendering region");

                        DateTime sTime = DateTime.Now;

                        #region Chunk render

                        using (var renderTarget = new BitmapRenderTarget(rendererUtil.D2DDeviceContext, CompatibleRenderTargetOptions.None, new DrawingSizeF(16, 16), new DrawingSize(16, 16), new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)))
                        {
                            foreach (var anvilChunk in regionFile.Content.Select(chunk => new Anvil(chunk)))
                            {
                                ChunkEntry entry;
                                RenderSegment(anvilChunk, renderTarget, out entry);

                                renderedChunks.Add(entry);
                            }
                        }

                        #endregion

                        #region Region compositor

                        using (var renderTarget = new BitmapRenderTarget(rendererUtil.D2DDeviceContext, CompatibleRenderTargetOptions.None, new DrawingSizeF(512, 512), new DrawingSize(512, 512), new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)))
                        {
                            renderTarget.BeginDraw();

                            renderTarget.Clear(Color.Transparent);

                            // compose the images
                            foreach (ChunkEntry chunk in renderedChunks)
                            {
                                int cxPos = chunk.XPos % 32;
                                int czPos = chunk.ZPos % 32;

                                if (cxPos < 0)
                                    cxPos = 32 + cxPos;

                                if (czPos < 0)
                                    czPos = 32 + czPos;

                                int xPos = cxPos * 16;
                                int zPos = czPos * 16;

                                renderTarget.Transform = Matrix3x2.Translation(xPos, zPos);
                                renderTarget.DrawBitmap(chunk.RenderedChunk, 1, BitmapInterpolationMode.Linear);
                            }

                            // ReSharper disable PossibleNullReferenceException
                            string[] info = Path.GetFileNameWithoutExtension(region).Split('.');
                            // ReSharper restore PossibleNullReferenceException

                            regionEntries.Add(new RegionEntry
                            {
                                RenderedRegion  = renderTarget.Bitmap,
                                XPos            = Convert.ToInt32(info[1]),
                                ZPos            = Convert.ToInt32(info[2])
                            });

                            renderTarget.EndDraw();
                        }

                        #endregion

                        Debug.WriteLine("Render time is: " + (DateTime.Now - sTime).Seconds + " seconds.");

                        if (RegionRendered != null)
                            RegionRendered();

                        #region Cleanup

                        foreach (ChunkEntry chunk in renderedChunks)
                            chunk.RenderedChunk.Dispose();

                        renderedChunks.Clear();

                        #endregion
                    }
                }
                catch (Exception exception)
                {
                    if (ProcessFailed != null)
                        ProcessFailed(exception.Message + "\nAt:\n" + exception);
                }

                if (ProgressChanged != null)
                    ProgressChanged(++index / (float)regionList.Count);
            }

            #region Extrema processor

            int xMin = 0;
            int zMin = 0;

            int xMax = 0;
            int zMax = 0;

            foreach (RegionEntry entry in regionEntries)
            {
                if (xMin > entry.XPos)
                    xMin = entry.XPos;

                if (xMax < entry.XPos)
                    xMax = entry.XPos;

                if (zMin > entry.ZPos)
                    zMin = entry.ZPos;

                if (zMax < entry.ZPos)
                    zMax = entry.ZPos;
            }

            int wSizeX = (xMax - xMin) * 512 + 512;
            int wSizeZ = (zMax - zMin) * 512 + 512;

            xMin = Math.Abs(xMin);
            zMin = Math.Abs(zMin);

            #endregion

            #region World compositor

            var ResultingBitmap = new Bitmap1(rendererUtil.D2DDeviceContext,
                                              new DrawingSize(wSizeX, wSizeZ),
                                              new BitmapProperties1
                                              {
                                                  BitmapOptions = BitmapOptions.Target,
                                                  PixelFormat   = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)
                                              });

            rendererUtil.D2DDeviceContext.Target = ResultingBitmap;

            rendererUtil.D2DDeviceContext.BeginDraw();

            rendererUtil.D2DDeviceContext.Clear(Color.Transparent);

            foreach (RegionEntry entry in regionEntries)
            {
                int xPos = ((xMin + entry.XPos) * 512);
                int zPos = ((zMin + entry.ZPos) * 512);

                rendererUtil.D2DDeviceContext.Transform = Matrix3x2.Translation(xPos, zPos);
                rendererUtil.D2DDeviceContext.DrawBitmap(entry.RenderedRegion, 1, BitmapInterpolationMode.Linear);
            }

            rendererUtil.D2DDeviceContext.EndDraw();

            #endregion

            #region File save

            FileStream file = File.OpenWrite(Path.GetFileName(worldLocation) + ".png");

            var encoder = new PngBitmapEncoder(rendererUtil.ImagingFactory);
            encoder.Initialize(file);

            var frameEncode = new BitmapFrameEncode(encoder);
            frameEncode.Initialize();

            var imageEncoder = new ImageEncoder(rendererUtil.ImagingFactory, rendererUtil.D2DDevice);
            imageEncoder.WriteFrame(ResultingBitmap,
                                    frameEncode,
                                    new ImageParameters(
                                        new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
                                        96,
                                        96,
                                        0,
                                        0,
                                        wSizeX,
                                        wSizeZ));

            frameEncode.Commit();
            encoder.Commit();

            #endregion

            #region Cleanup

            file.Close();
            file.Dispose();

            foreach (RegionEntry bitmap in regionEntries)
            {
                bitmap.RenderedRegion.Dispose();
            }

            regionEntries.Clear();

            rendererUtil.Dispose();
            theBlocks.Dispose();

            ResultingBitmap.Dispose();

            #endregion

            if (ProcessComplete != null)
                ProcessComplete();
        }
コード例 #47
0
		/// <summary>
		/// 调整渲染目标的尺寸。
		/// </summary>
		/// <param name="control">渲染的目标控件。</param>
		public void ResizeRenderTarget(Control control)
		{
			if (this.swapChain == null)
			{
				((WindowRenderTarget)this.renderTarget).Resize(
					new Size2(control.ClientSize.Width, control.ClientSize.Height));
			}
			else
			{
				((DeviceContext)this.renderTarget).Target = null;
				this.backBuffer.Dispose();
				this.targetBitmap.Dispose();
				this.swapChain.ResizeBuffers(1, 0, 0, Format, SwapChainFlags.None);
				this.backBuffer = Surface.FromSwapChain(this.swapChain, 0);
				this.targetBitmap = new Bitmap1(this.d2DContext, backBuffer);
				((DeviceContext)this.renderTarget).Target = targetBitmap;
			}
		}
コード例 #48
0
ファイル: MeshEditor.cs プロジェクト: Artentus/GameUtils
        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));
        }
コード例 #49
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

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

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

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

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

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

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

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

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

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

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

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

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush = new SolidColorBrush(d2dContext, Color.Black);
        }