internal void ReleaseDevices()
 {
     IsRendererSuppressed = true;
     RenderTarget.Dispose();
     Backbuffer.Dispose();
     RenderTargetSurface.Dispose();
     RenderTargetView.Dispose();
     D2DDeviceContext.Dispose();
     D2DDevice.Dispose();
     D2DFactory.Dispose();
     DXGIDevice.Dispose();
     D3DDevice.Dispose();
     D3DDefaultDevice.Dispose();
     SwapChain.Dispose();
     SwapChain           = null;
     RenderTarget        = null;
     RenderTargetSurface = null;
     Backbuffer          = null;
     RenderTargetView    = null;
     D2DDeviceContext    = null;
     D2DFactory          = null;
     D2DDevice           = null;
     DXGIDevice          = null;
     D3DDevice           = null;
     D3DDefaultDevice    = null;
 }
Esempio n. 2
0
 public static BitmapBrush1 GetBrush(D2D.DeviceContext context, Bitmap1 bitmap, ExtendMode mode)
 {
     return(new BitmapBrush1(context, bitmap)
     {
         ExtendModeX = mode, ExtendModeY = mode
     });
 }
// ReSharper restore InconsistentNaming

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

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

            var dxgiDevice = ComObject.As<SharpDX.DXGI.Device>(d3DDevice.NativePointer);
                //new SharpDX.DXGI.Device2(d3DDevice.NativePointer);
            var d2DDevice = new SharpDX.Direct2D1.Device(dxgiDevice);
            _d2DFactory = d2DDevice.Factory;
            _d2DDeviceContext = new SharpDX.Direct2D1.DeviceContext(d2DDevice, D2D.DeviceContextOptions.None);
            _d2DDeviceContext.DotsPerInch = new Size2F(LogicalDpi, LogicalDpi);
        }
Esempio n. 4
0
        public void Shutdown()
        {
            if (_deviceContext != null)
            {
                _deviceContext.Dispose();
                _deviceContext = null;
            }

            if (_device2D != null)
            {
                _device2D.Dispose();
                _device2D = null;
            }

            if (_dxgiDevice != null)
            {
                _dxgiDevice.Dispose();
                _dxgiDevice = null;
            }

            if (_default3DDevice1 != null)
            {
                _default3DDevice1.Dispose();
                _default3DDevice1 = null;
            }

            if (_default3DDevice != null)
            {
                _default3DDevice.Dispose();
                _default3DDevice = null;
            }
        }
Esempio n. 5
0
    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);
    }
Esempio n. 6
0
// ReSharper restore InconsistentNaming

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

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

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

            _d2DFactory                   = d2DDevice.Factory;
            _d2DDeviceContext             = new SharpDX.Direct2D1.DeviceContext(d2DDevice, D2D.DeviceContextOptions.None);
            _d2DDeviceContext.DotsPerInch = new DrawingSizeF(
                Windows.Graphics.Display.DisplayProperties.LogicalDpi,
                Windows.Graphics.Display.DisplayProperties.LogicalDpi);
        }
 public DeviceManager()
 {
     try
     {
         // 创建 Dierect3D 设备。
         this.d3DDevice  = new D3D11Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport);
         this.dxgiDevice = d3DDevice.QueryInterface <D3D11Device1>().QueryInterface <DXGIDevice>();
         // 创建 Direct2D 设备和工厂。
         this.d2DDevice  = new D2D1Device(dxgiDevice);
         this.d2DContext = new DeviceContext(d2DDevice, DeviceContextOptions.None);
         this.d2DFactory = this.d2DContext.Factory;
         this.wicFactory = new ImagingFactory2();
     }
     catch
     {
         this.ClearResources();
         try
         {
             // 创建 D3D 设备异常,则尝试 Direct2D 单线程工厂。
             this.d2DFactory = new Factory(FactoryType.SingleThreaded);
             this.wicFactory = new ImagingFactory();
         }
         catch
         {
             this.ClearResources();
         }
     }
     if (this.d2DFactory != null)
     {
         Dpi          = d2DFactory.DesktopDpi;
         BitmapProps1 = new BitmapProperties1(D2PixelFormat, Dpi.Width, Dpi.Height, BitmapOptions.Target);
     }
 }
Esempio n. 8
0
        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;
        }
Esempio n. 9
0
        /// <summary>
        ///     指定したサイズの、空の描画可能画像を作成する。
        /// </summary>
        public 描画可能画像(SharpDX.Direct3D11.Device1 d3dDevice1, SharpDX.Direct2D1.DeviceContext d2dDeviceContext, Size2F サイズ, BindFlags bindFlags = BindFlags.ShaderResource)
            : base(d3dDevice1, サイズ, bindFlags | BindFlags.RenderTarget)
        {
            //using var _ = new LogBlock( Log.現在のメソッド名 );

            this.Bitmap = this._作成したテクスチャとデータを共有するビットマップターゲットを作成する(d2dDeviceContext);
        }
Esempio n. 10
0
            public Core()
            {
                using (var dxgiDevice =
                           ImageFramework.DirectX.Device.Get().Handle.QueryInterface <SharpDX.DXGI.Device>())
                {
#if DEBUG
                    var debugLevel = DebugLevel.Information;
#else
                    var debugLevel = DebugLevel.None;
#endif
                    var factory = new SharpDX.Direct2D1.Factory1(FactoryType.MultiThreaded, debugLevel);
                    Factory = factory;
                    Handle  = new SharpDX.Direct2D1.Device(factory, dxgiDevice);
                    Context = new SharpDX.Direct2D1.DeviceContext(Handle, DeviceContextOptions.None);
                }

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

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

                ImageFramework.DirectX.Device.Get().DeviceDispose += (sender, args) => Dispose();
            }
Esempio n. 11
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;
        }
        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));
        }
Esempio n. 13
0
        public WindowedDirect2dRenderEnvironment(string formName, bool debug)
        {
            form = new RenderForm(formName);

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

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

            d2dFactory        = new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded, debug ? DebugLevel.Warning : DebugLevel.None);
            d2dDevice         = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice);
            d2dContext        = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.None);
            bitmap            = new Bitmap1(d2dContext, dxgiSurface, null);
            d2dContext.Target = bitmap;
        }
Esempio n. 14
0
        public DrawableText(string t, string name, float size, DeviceContext DC) : base(DC)
        {
            text    += t;
            wfactory = new SharpDX.DirectWrite.Factory();
            wformat  = new SharpDX.DirectWrite.TextFormat(wfactory, name, size);

            this.AddUpdateProcess(() =>
            {
                drawtime += 1;
                if (drawtime > 60)
                {
                    drawtime = 0;
                }

                int fpt = 60 / Speed;

                if (bufferChars.Count != 0 && drawtime % fpt == 0)
                {
                    text += bufferChars[0];
                    bufferChars.RemoveAt(0);
                }

                return(true);
            });
        }
        private RadialGradientBrush CreateRadialGradientBrush(DeviceContext context, float width, float height, Color4 color1, Color4 color2, float color1Position, float color2Position)
        {

            GradientStop[] stops = new GradientStop[2];
            //stops[0] = new GradientStop() { Color = new Color4(0.85f, 0, 0, 1.0f), Position = 0.0f };
            //stops[1] = new GradientStop() { Color = new Color4(0.22f, 0, 0, 1.0f), Position = 1.0f };
            stops[0] = new GradientStop() { Color = color1, Position = color1Position };
            stops[1] = new GradientStop() { Color = color2, Position = color2Position };


            GradientStopCollection gsc = new GradientStopCollection(context, stops, ExtendMode.Clamp);

            RadialGradientBrush brush = new RadialGradientBrush(
                context,
                new RadialGradientBrushProperties()
                {
                    RadiusX = width / 1.3f,
                    RadiusY = height / 1.3f,
                    Center = new Vector2(width / 2.0f, height / 2.0f),
                    GradientOriginOffset = new Vector2(0, 0)
                },
                gsc);


            return brush;
        }
Esempio n. 16
0
 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);
 }
Esempio n. 17
0
 public CustomTextRenderer(SharpDX.Direct2D1.Factory factory, SharpDX.Direct2D1.DeviceContext renderTarget, SolidColorBrush outline, SolidColorBrush fill)
 {
     _d2DFactory   = factory;
     _dc           = renderTarget;
     _outlineBrush = outline;
     _fillBrush    = fill;
 }
Esempio n. 18
0
        public void Reset(D2DDeviceContext d2dContext)
        {
            blackBrush?.Dispose();
            whiteBrush?.Dispose();
            bmToolBarBox?.Dispose();
            bmToolBarSelect?.Dispose();
            // textFormat?.Dispose();

            d2dDeviceContext = d2dContext;

            blackBrush = new SolidColorBrush(d2dContext, Color.Black);
            whiteBrush = new SolidColorBrush(d2dContext, Color.White);

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

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

            BitmapProperties1 properties = new BitmapProperties1(
                new PixelFormat(
                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied),
                dpi,
                dpi,
                BitmapOptions.Target | BitmapOptions.CannotDraw);
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);
            d2dTarget        = new Bitmap1(_RenderTarget2D, backBuffer, properties);
            this.TextFont    = font;
            this.TextSize    = size;
            _FactoryDWrite   = new SharpDX.DirectWrite.Factory();
            _SceneColorBrush = new SolidColorBrush(_RenderTarget2D, color);
            InitTextFormat();
            _RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;
        }
Esempio n. 20
0
 public BackGroundLayer(Size size, UIElement window, RawRectangleF Output, DeviceContext DC) : base(DC)
 {
     this.Size         = new Size2(size.Width, size.Height);
     base.OutPutRange  = Output;
     window.MouseMove += MoveListener;
     _window           = window;
 }
Esempio n. 21
0
        public ClosedGemo(Point[] Path, RawColor4 cBorder, RawColor4 cFiller, DeviceContext DC) : base(DC)
        {
            this.Path = (Point[])Path.Clone();

            Border = new RawColor4(cBorder.R, cBorder.G, cBorder.B, cBorder.A);
            Filler = new RawColor4(cFiller.R, cFiller.G, cFiller.B, cFiller.A);
        }
Esempio n. 22
0
            void CreateDeviceResources()
            {
                var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

                var device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();

                var dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>();

                var dxgiAdapter = dxgiDevice2.Adapter;

                SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

                var desc = new SwapChainDescription1();

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

                this.swapChain = new SwapChain1(dxgiFactory2, device, new ComObject(mWindow), ref desc);

                var d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);

                this.d2dDeviceContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.None);

                var backBuffer = this.swapChain.GetBackBuffer <Surface>(0);

                var displayInfo = DisplayInformation.GetForCurrentView();

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

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

                // 10.5改変
                this.playerShotManager = new PlayerShotManager(this.d2dDeviceContext);

                this.updateList.Add(this.playerShotManager);

                this.fighterDisplay = new Fighter(this.d2dDeviceContext, playerShotManager);
                this.fighterDisplay.SetPosition(540, 240);

                this.displayList = new List <IDrawable>();
                this.displayList.Add(this.fighterDisplay);
                this.displayList.Add(this.playerShotManager);

                this.targetManager = new RectTargetManager(this.d2dDeviceContext, this.playerShotManager);
                this.displayList.Add(this.targetManager);
                this.updateList.Add(this.targetManager);

                this.enemyShotManager = new EnemyShotManager(this.d2dDeviceContext, this.targetManager, this.fighterDisplay);
                this.displayList.Add(this.enemyShotManager);
                this.updateList.Add(this.enemyShotManager);
            }
Esempio n. 23
0
        public override void initContent(SurfaceImageSourceTarget target, DrawingSize pixelSize)
        {
            this.size = pixelSize;

            context = target.DeviceManager.ContextDirect2D;
            pixelBrush = new SolidColorBrush(context, color);
            dimmingBrush = new SolidColorBrush(context, new Color(0, 0, 0, 10));
        }
Esempio n. 24
0
        public RenderableImage(ImageSource im, DeviceContext DC) : base(DC)
        {
            Source     = im;
            _Pelete    = Source.Output;
            this._Size = new Size2(this._Pelete.Size.Width, this._Pelete.Size.Height);

            RotationPoint = new Point(this._Pelete.Size.Width / 2, this._Pelete.Size.Height / 2);
        }
Esempio n. 25
0
        static public RenderableImage CreateFromWIC(DeviceContext dc, WICBitmap im)
        {
            RenderableImage rt = new RenderableImage(dc, im);



            return(rt);
        }
 public BitmapFrameD2D1(BouncingBallRenderer renderer, D2D1.DeviceContext context2D)
     : base(renderer)
 {
     using (var surface = Texture.QueryInterface <SharpDX.DXGI.Surface>())
     {
         Bitmap = new D2D1.Bitmap1(context2D, surface);
     }
 }
Esempio n. 27
0
        internal void Initialise()
        {
            RemoveAndDispose(ref _d2dFactory);
            RemoveAndDispose(ref _dwFactory);

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

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


            //var desc = CreateSwapChainDescription();

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

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



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

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

            InitialiseResources();

            RemoveAndDispose(ref _fpsCounter);

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

            OnInitialize?.Invoke(this);
        }
Esempio n. 28
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;
 }
Esempio n. 29
0
 protected override void OnDraw(SharpDX.Direct2D1.DeviceContext ctx)
 {
     ctx.Clear(Color.Transparent);
     foreach (var snow in _snows.Values)
     {
         snow.Draw(XResource.Bitmaps, ctx);
     }
     ctx.Transform = Matrix3x2.Identity;
 }
Esempio n. 30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Graphics2D"/> class.
        /// </summary>
        /// <param name="device">The hardware device which is used for rendering.</param>
        /// <param name="renderTarget">The render target which is used by this graphics object.</param>
        /// <param name="screenSize">The size of the screen in device independent pixels.</param>
        internal Graphics2D(EngineDevice device, D2D.RenderTarget renderTarget, Size2F screenSize)
        {
            m_transformSettings = Graphics2DTransformSettings.Default;
            m_transformStack    = new Matrix3x2Stack();

            m_device          = device;
            m_renderTarget    = renderTarget;
            m_screenPixelSize = screenSize;
            m_deviceContext   = m_renderTarget as D2D.DeviceContext;
        }
Esempio n. 31
0
        public static Bitmap1 LoadBitmap(string filename, DeviceContext context)
        {
            var props = new BitmapProperties1
            {
                PixelFormat =
                    new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied)
            };

            return(Bitmap1.FromWicBitmap(context, LoadBitmap(filename), props));
        }
Esempio n. 32
0
 private void CreateDeviceContext()
 {
     using (var surface = SwapChain.GetBackBuffer <Surface>(0))
     {
         DeviceContext = new DeviceContext2D1(Device2D, DeviceContextOptions.None);
         using (var bitmap = new Bitmap1(DeviceContext, surface))
         {
             DeviceContext.Target = bitmap;
         }
     }
 }
Esempio n. 33
0
        /// <summary>
        ///		現在のバックバッファの内容を Bitmap に複写して返す。
        ///		すべての描画が終わったあと、Present() する前に呼び出すこと。
        /// </summary>
        /// <returns>Bitmap。使用後は解放すること。</returns>
        public static Bitmap 取得する(
            SharpDX.Direct3D11.Device1 d3dDevice1,
            SwapChain1 swapchain1,
            RenderTargetView renderTargetView,
            SharpDX.Direct2D1.DeviceContext d2dDeviceContext)
        {
            // バックバッファの情報を取得する。
            Texture2DDescription backBufferDesc;

            using (var backBuffer = swapchain1.GetBackBuffer <Texture2D>(0))
                backBufferDesc = backBuffer.Description;

            // CPUがアクセス可能な Texture2D バッファをGPU上に作成する。
            using var captureTexture = new Texture2D(
                      d3dDevice1,
                      new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,    // CPUからアクセスできる。
                Format            = backBufferDesc.Format,
                Height            = backBufferDesc.Height,
                Width             = backBufferDesc.Width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Staging, // GPU から CPU への copy ができる。
            });

            // RenderTarget から Texture2D バッファに、GPU上で画像データをコピーする。
            using (var resource = renderTargetView.Resource)
                d3dDevice1.ImmediateContext.CopyResource(resource, captureTexture);

            // Texture2D の本体(DXGIサーフェス)から Bitmap を生成する。
            using var dxgiSurface = captureTexture.QueryInterface <Surface>();
            var dataRect = dxgiSurface.Map(SharpDX.DXGI.MapFlags.Read, out DataStream dataStream);

            try
            {
                return(new Bitmap(
                           d2dDeviceContext,
                           new Size2(captureTexture.Description.Width, captureTexture.Description.Height),
                           new DataPointer(dataStream.DataPointer, (int)dataStream.Length),
                           dataRect.Pitch,
                           new BitmapProperties(
                               new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore),
                               d2dDeviceContext.DotsPerInch.Width,
                               d2dDeviceContext.DotsPerInch.Width)));
            }
            finally
            {
                dxgiSurface.Unmap();
            }
        }
Esempio n. 34
0
        public InfoText(SharpDX.Direct3D11.Device device)
        {
            _immediateContext = device.ImmediateContext;
            rect.Size = new Size2F(Width, Height);

            var factoryWic = new SharpDX.WIC.ImagingFactory();
            _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic, _width, _height, pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad);
            var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None,
                    SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);
            factoryWic.Dispose();

            var factory2D = new SharpDX.Direct2D1.Factory();
            _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties);
            _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default;
            factory2D.Dispose();

            var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);
            _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20);
            factoryDWrite.Dispose();

            _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color);
            clearColor = color;
            clearColor.Alpha = 0;

            _renderTexture = new Texture2D(device, new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.Write,
                Format = Format.R8G8B8A8_UNorm,
                Height = _height,
                Width = _width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Dynamic
            });

            OverlayBufferRes = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription()
            {
                Format = _renderTexture.Description.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            });
        }
Esempio n. 35
0
        public RendererUtil()
        {
            var defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport);

            d3dDevice = defaultDevice.QueryInterface<D3D11.Device1>();
            dxgiDevice = d3dDevice.QueryInterface<Device>();

            d2dFactory = new D2D.Factory(D2D.FactoryType.MultiThreaded);

            d2dDevice = new D2D.Device(dxgiDevice);
            d2dDeviceContext = new D2D.DeviceContext(d2dDevice, D2D.DeviceContextOptions.None);

            imagingFactory = new ImagingFactory2();
        }
Esempio n. 36
0
        // Initialize hardware-dependent resources.
        private void CreateDeviceResources()
        {
            // Unlike the original C++ sample, we don't have smart pointers so we need to
            // dispose Direct3D objects explicitly
            Utilities.Dispose(ref d3dDevice);
            Utilities.Dispose(ref d2dDevice);
            Utilities.Dispose(ref d2dContext);

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

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

            // This array defines the set of DirectX hardware feature levels this app will support.
            // Note the ordering should be preserved.
            // Don't forget to declare your application's minimum required feature level in its
            // description.  All applications are assumed to support 9.1 unless otherwise stated.
            FeatureLevel[] featureLevels =
            {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3,
                FeatureLevel.Level_9_2,
                FeatureLevel.Level_9_1,
            };

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

            // Get the Direct3D 11.1 API device.
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
            {
                // Create the Direct2D device object and a corresponding context.
                d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice);

                d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.EnableMultithreadedOptimizations);

                // Query for ISurfaceImageSourceNative interface.
                using (var sisNative = ComObject.QueryInterface<ISurfaceImageSourceNative>(this))
                    sisNative.Device = dxgiDevice;
            }
        }
        public override void initContent(SurfaceImageSourceTarget target, DrawingSize pixelSize)
        {
            this.drawingSize = pixelSize;
            this.size = new DrawingSize((int) (pixelSize.Width/scaling), (int) (pixelSize.Height/scaling));
            context = target.DeviceManager.ContextDirect2D;

            Mandelbrot engine = new BasicMandelbrot(iters);
            view = new TrajectoryMandelbrotView(engine, trajectory, size.Width, size.Height);

            data = new int[size.Width * size.Height];

            PixelFormat format = new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore);
            BitmapProperties props = new BitmapProperties(format);

            buf = Bitmap.New<int>(context, size, data, props);
        }
Esempio n. 38
0
        public virtual void Update(DeviceContext context, TargetBase target, DeviceManager deviceManager, Point screenSize, float dt, float elapsedTime)
        {
            context.DrawRectangle(screenSize.ApplyTo(GamesParams.Margin0.ToRectangleWith(GamesParams.Margin1)), GamesParams.ObstaclesColor, 2);

            _gameTime += dt;

            if (!_gameManager.IsTraining)
            {
                const float u = 1.00f;
                if (_gameTime < u && !AfterStartFreeze)
                {
                    var op = 1 - _gameTime / u;
                    var hideBrush = new SolidColorBrush(deviceManager.ContextDirect2D, Colors.White,
                                                        new BrushProperties { Opacity = op });
                    context.FillRectangle(screenSize.ApplyTo(new RectangleF(0, 0, 1, 1)), hideBrush);
                }
                else
                {
                    AfterStartFreeze = true;
                }

                if (_gameTime > _gameMaxTime - u)
                {
                    var op = 1 - (_gameMaxTime - _gameTime) / u;
                    var hideBrush = new SolidColorBrush(deviceManager.ContextDirect2D, Colors.White,
                                                        new BrushProperties { Opacity = op });
                    context.FillRectangle(screenSize.ApplyTo(new RectangleF(0, 0, 1, 1)), hideBrush);
                }

                float bar;
                bar = _gameManager.IsTraining ? 1 : _gameTime / _gameMaxTime;
                _gameManager.Page.SetTimeRectangleWidth(bar);
                _gameManager.RedrawPointsAndLifes();

                if (_gameTime > _gameMaxTime)
                    _gameManager.Win(100);
            }
        }
        /// <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,
                        }
                }));
        }
Esempio n. 40
0
 /// <summary>
 /// Creates a Bitmap from a wic bitmap.
 /// </summary>
 /// <param name="deviceContext">The render target.</param>
 /// <param name="wicBitmapSource">A reference to a <see cref="SharpDX.WIC.BitmapSource"/> wic bitmap.</param>
 /// <returns></returns>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapFromWicBitmap([In] IWICBitmapSource* wicBitmapSource,[In, Optional] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out] ID2D1Bitmap1** bitmap)</unmanaged>	
 public static Bitmap1 FromWicBitmap(DeviceContext deviceContext, WIC.BitmapSource wicBitmapSource)
 {
     Bitmap1 bitmap;
     deviceContext.CreateBitmapFromWicBitmap(wicBitmapSource, null, out bitmap);
     return bitmap;
 }
Esempio n. 41
0
        // Initialize hardware-dependent resources.
        // Device-independent resources, such as ID2D1Geometry, are kept on the CPU.
        // Device-dependent resources, such as ID2D1RenderTarget and ID2D1LinearGradientBrush, directly map to resources on the GPU 
        // (when hardware acceleration is available). 
        // Rendering calls are performed by combining vertex and coverage information from a geometry with texturing information produced by the device-dependent resources.
        private void CreateDeviceResources()
        {
            // http://msdn.microsoft.com/zh-tw/library/windows/apps/dn481540.aspx

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

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

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

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

            // This array defines the set of DirectX hardware feature levels this app will support.
            // Note the ordering should be preserved.
            // Don't forget to declare your application's minimum required feature level in its
            // description.  All applications are assumed to support 9.1 unless otherwise stated.
            FeatureLevel[] featureLevels =
            {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3,
                FeatureLevel.Level_9_2,
                FeatureLevel.Level_9_1,
            };

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

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

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

                // Query for ISurfaceImageSourceNative interface.
                using (var sisNative = ComObject.QueryInterface<ISurfaceImageSourceNative>(this))
                    sisNative.Device = dxgiDevice;
            }
            setPrimitiveBlend();
        }
Esempio n. 42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandList"/> class.
 /// </summary>
 /// <param name="deviceContext">The device context.</param>
 public CommandList(DeviceContext deviceContext) : base(IntPtr.Zero)
 {
     deviceContext.CreateCommandList(this);
 }
Esempio n. 43
0
        static void Main()
        {
            #region Предварительная настройка
            RuntimeTypeModel.Default.Add(typeof(Vector3), false).Add("X", "Y", "Z");
            RuntimeTypeModel.Default.Add(typeof(Matrix), false).Add("M11", "M12", "M13", "M14",
                                                                    "M21", "M22", "M23", "M24",
                                                                    "M31", "M32", "M33", "M34",
                                                                    "M41", "M42", "M43", "M44");
            RuntimeTypeModel.Default.Add(typeof(Quaternion), false).Add("X", "Y", "Z", "W");
            RuntimeTypeModel.Default.Add(typeof(DVector3), false).Add("X", "Y", "Z");
            RuntimeTypeModel.Default.Add(typeof(DMatrix), false).Add("M11", "M12", "M13", "M14",
                                                                     "M21", "M22", "M23", "M24",
                                                                     "M31", "M32", "M33", "M34",
                                                                     "M41", "M42", "M43", "M44");
            RuntimeTypeModel.Default.Add(typeof(DQuaternion), false).Add("X", "Y", "Z", "W");
            Process thisProc = Process.GetCurrentProcess();
            thisProc.PriorityClass = ProcessPriorityClass.High;
            #endregion

            using (StartForm Input_form = new StartForm())
            {
                Application.Run(Input_form);
            }

            featureLevel = Device.GetSupportedFeatureLevel();
            //featureLevel = FeatureLevel.Level_10_0;

            if (Global.Settings.Run && featureLevel >= FeatureLevel.Level_10_0)
            {
                HiTimer = new HiResTimer();
                IntPreTime = HiTimer.Value;

                form = new RenderForm()
                {
                    ClientSize = new System.Drawing.Size(Global.Settings.Width, Global.Settings.Height),
                    Text = "Model Viewer"
                };
                //form.FormBorderStyle = FormBorderStyle.None;
                form.StartPosition = FormStartPosition.CenterScreen;

                InputManager.Init();

                var description = new SwapChainDescription()
                {
                    BufferCount = 2,
                    Usage = Usage.RenderTargetOutput,
                    OutputHandle = form.Handle,
                    IsWindowed = true,
                    ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    SampleDescription = new SampleDescription(1, 0), //8, 32
                    //Flags = SwapChainFlags.AllowModeSwitch,
                    SwapEffect = SwapEffect.Discard
                };

                FeatureLevel[] f_level = new FeatureLevel[] { (featureLevel > FeatureLevel.Level_10_0) ? FeatureLevel.Level_10_1 : FeatureLevel.Level_10_0 };
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, f_level, description, out device, out swapChain);
                // setting a viewport is required if you want to actually see anything
                context = device.ImmediateContext;
                viewport = new Viewport(0, 0, Global.Settings.Width, Global.Settings.Height);
                context.Rasterizer.SetViewports(viewport);

                // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms

                var factory_ = swapChain.GetParent<Factory>();
                    factory_.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

                // handle alt+enter ourselves
                form.KeyDown += FormOnKeyDown;
                // handle form size changes
                form.UserResized += Resize;

                ////Scene inizialize
                MyScene.Inizialize(device, viewport, description, context, swapChain);

                SharpDX.DXGI.Surface surface = Surface.FromSwapChain(swapChain, 0);

                DrawHelper.Init(device);
                DebugDraw.Init(device);
                QuadScreen.Init(device, (int)viewport.Width, (int)viewport.Height);

                MyScene.LoadContent(device);

                swapChain.IsFullScreen = Global.Settings.FullScr;

               // RenderLoop.UseCustomDoEvents = false;
                RenderLoop.Run(form, () =>
                {
                    //RenderLoop.UseCustomDoEvents = false;
                    //Application.DoEvents();
                    TimeUpdate = HiTimer.Tick2Mili(HiTimer.Value - IntPreTime);
                    IntPreTime = HiTimer.Value;

                    InputManager.Update(TimeUpdate);

                    MyScene.Update(TimeUpdate);

                    MyScene.Draw(TimeUpdate, device, context);

                    swapChain.Present(Global.Settings.VSync, PresentFlags.None);

                    TimeGC += TimeUpdate;
                    if (TimeGC > 300)
                    {
                        TimeGC = 0;
                        System.GC.Collect(1);
                    }

                });

                if (swapChain.IsFullScreen) swapChain.IsFullScreen = false;
                //MyScene.Dispose();

                DrawHelper.FreeResource();
                ContentManager.FreeResources();
                InputManager.FreeResource();
                DebugDraw.FreeResource();
                QuadScreen.FreeResource();
                factory_.Dispose();
                swapChain.Dispose();
                device.Dispose();
                context.Dispose();
            }
        }
        /// <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
            });
        }
Esempio n. 45
0
 /// <summary>	
 /// Creates an <see cref="SharpDX.Direct2D1.Bitmap"/> whose data is shared with another resource.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="surface">An <see cref="SharpDX.DXGI.Surface"/> that contains the data to share with the new ID2D1Bitmap. For more information, see the Remarks section.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapFromDxgiSurface([In] IDXGISurface* surface,[In, Optional] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap1)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, Surface surface)
     : base(IntPtr.Zero)
 {
     deviceContext.CreateBitmapFromDxgiSurface(surface, null, this);
 }
Esempio n. 46
0
 /// <summary>	
 /// Creates an <see cref="SharpDX.Direct2D1.BitmapBrush"/> from the specified bitmap.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "DeviceContext" /></param>
 /// <param name="bitmap">The bitmap contents of the new brush.</param>
 /// <param name="bitmapBrushProperties">The extend modes and interpolation mode of the new brush, or NULL. If this parameter is NULL, the brush defaults to the <see cref="SharpDX.Direct2D1.ExtendMode.Clamp"/> horizontal and vertical extend modes and the <see cref="SharpDX.Direct2D1.BitmapInterpolationMode.Linear"/> interpolation mode. </param>
 /// <param name="brushProperties">The opacity and transform of the new brush, or NULL. If this parameter is NULL, the brush defaults to an opacity of 1.0f and its transform is the identity matrix.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapBrush([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D1_BITMAP_BRUSH_PROPERTIES1* bitmapBrushProperties,[In, Optional] const D2D1_BRUSH_PROPERTIES* brushProperties,[Out, Fast] ID2D1BitmapBrush1** bitmapBrush)</unmanaged>	
 public BitmapBrush1(DeviceContext deviceContext, SharpDX.Direct2D1.Bitmap1 bitmap, SharpDX.Direct2D1.BitmapBrushProperties1? bitmapBrushProperties, SharpDX.Direct2D1.BrushProperties? brushProperties)
     : base(IntPtr.Zero)
 {
     deviceContext.CreateBitmapBrush(bitmap, bitmapBrushProperties, brushProperties, this);
 }         
Esempio n. 47
0
 /// <summary>	
 /// Creates an <see cref="SharpDX.Direct2D1.BitmapBrush"/> from the specified bitmap.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "DeviceContext" /></param>
 /// <param name="bitmap">The bitmap contents of the new brush.</param>
 /// <param name="brushProperties">The opacity and transform of the new brush, or NULL. If this parameter is NULL, the brush defaults to an opacity of 1.0f and its transform is the identity matrix.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapBrush([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D1_BITMAP_BRUSH_PROPERTIES1* bitmapBrushProperties,[In, Optional] const D2D1_BRUSH_PROPERTIES* brushProperties,[Out, Fast] ID2D1BitmapBrush1** bitmapBrush)</unmanaged>	
 public BitmapBrush1(DeviceContext deviceContext, SharpDX.Direct2D1.Bitmap1 bitmap, SharpDX.Direct2D1.BrushProperties brushProperties)
     : this(deviceContext, bitmap, null, brushProperties)
 {
 }
Esempio n. 48
0
 /// <summary>	
 /// Creates an <see cref="SharpDX.Direct2D1.BitmapBrush"/> from the specified bitmap.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "DeviceContext" /></param>
 /// <param name="bitmap">The bitmap contents of the new brush.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapBrush([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D1_BITMAP_BRUSH_PROPERTIES1* bitmapBrushProperties,[In, Optional] const D2D1_BRUSH_PROPERTIES* brushProperties,[Out, Fast] ID2D1BitmapBrush1** bitmapBrush)</unmanaged>	
 public BitmapBrush1(DeviceContext deviceContext, SharpDX.Direct2D1.Bitmap1 bitmap)
     : this(deviceContext, bitmap, null, null)
 {
 }
Esempio n. 49
0
        public override void Update(DeviceContext context, TargetBase target, DeviceManager deviceManager, Point screenSize, float dt, float elapsedTime)
        {
            if (AfterStartFreeze)
            {
                // Player moving
                _playerPos =
                    _playerPos.Add(_playerDir.Mul(_playerSpd).Mul(dt)).Clamp(GamesParams.Margin0.Add(_padSize.Half()),
                                                                             GamesParams.Margin1.Sub(_padSize.Half()));

                // Ball moving
                _ballPos = _ballPos.Add(_ballDir.Mul(_ballSpd).Mul(dt));

                // Ball collision with borders
                if (!_ballPos.IsInside(GamesParams.Margin0.Add(_ballSize.Half()),
                                       GamesParams.Margin1.Sub(_ballSize.Half())))
                {
                    _ballDir.Y = -_ballDir.Y;

                    if (_ballPos.X < GamesParams.MarginX0 + 0.001f)
                    {
                        NewGame();
                        _gameManager.Die();
                        return;
                    }

                    if (_ballPos.X > GamesParams.MarginX1 - 0.001f)
                    {
                        _gameManager.Win(500);
                        _ballPos = new Point(0.5f, 0.5f);
                        _ballDir = new Point(1.0f, 0.0f).AddNoise().Normalise();
                        return;
                    }
                }

                _ballPos = _ballPos.Clamp(GamesParams.Margin0.Add(_ballSize.Half()),
                                          GamesParams.Margin1.Sub(_ballSize.Half()));

                // Ball collision with player pad
                if (_ballPos.IsInside(_playerPos.Sub(_padSize.Half()).Sub(_ballSize.Half()),
                                      _playerPos.Add(_padSize.Half()).Add(_ballSize.Half())))
                {
                    _ballDir.X = 1;
                    _ballDir.Y = _ballPos.Sub(_playerPos).Y/_padSize.Half().Y;
                    _ballDir = _ballDir.Normalise();

                    _ballSpd += _ballSpdInc;

                    _gameManager.AddPoints(75);
                }

                // Ball collision with enemy pad
                if (_ballPos.IsInside(_enemyPos.Sub(_padSize.Half()).Sub(_ballSize.Half()),
                                      _enemyPos.Add(_padSize.Half()).Add(_ballSize.Half())))
                {
                    _ballDir.X = -1;
                    _ballDir.Y = _ballPos.Sub(_enemyPos).Y/_padSize.Half().Y;
                    _ballDir = _ballDir.Normalise();

                    _ballSpd += _ballSpdInc;
                }

                // Enemy moving
                if (Math.Abs(_ballPos.Y - _enemyPos.Y) < _padSize.Div(3).Y)
                {
                    _enemyDir.Y = 0;
                }
                else
                {
                    if (_ballPos.Y > _enemyPos.Y)
                        _enemyDir.Y = 1;
                    else
                        _enemyDir.Y = -1;

                    _enemyPos =
                        _enemyPos.Add(_enemyDir.Mul(_enemySpd).Mul(dt)).Clamp(GamesParams.Margin0.Add(_padSize.Half()),
                                                                              GamesParams.Margin1.Sub(_padSize.Half()));
                }
            }

            // Drawing
            var playerBox = _playerPos.ToBox(_padSize);
            var enemyBox = _enemyPos.ToBox(_padSize);
            var ballBox = _ballPos.ToBox(_ballSize);

            context.FillRectangle(screenSize.ApplyTo(playerBox), GamesParams.PlayerColor);
            context.FillRectangle(screenSize.ApplyTo(enemyBox), GamesParams.EnemyColor);

            context.FillRectangle(screenSize.ApplyTo(ballBox), GamesParams.AdditionalColor);

            base.Update(context, target, deviceManager, screenSize, dt, elapsedTime);
        }
Esempio n. 50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GradientStopCollection1"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="straightAlphaGradientStops">An array of color values and offsets.</param>
        /// <param name="preInterpolationSpace">Specifies both the input color space and the space in which the color interpolation occurs.</param>
        /// <param name="postInterpolationSpace">The color space that colors will be converted to after interpolation occurs.</param>
        /// <param name="bufferPrecision">The precision of the texture used to hold interpolated values.</param>
        /// <param name="extendMode">Defines how colors outside of the range defined by the stop collection are determined.</param>
        /// <param name="colorInterpolationMode">The new gradient stop collection.</param>
        /// <unmanaged>HRESULT ID2D1DeviceContext::CreateGradientStopCollection([In, Buffer] const D2D1_GRADIENT_STOP* straightAlphaGradientStops,[In] unsigned int straightAlphaGradientStopsCount,[In] D2D1_COLOR_SPACE preInterpolationSpace,[In] D2D1_COLOR_SPACE postInterpolationSpace,[In] D2D1_BUFFER_PRECISION bufferPrecision,[In] D2D1_EXTEND_MODE extendMode,[In] D2D1_COLOR_INTERPOLATION_MODE colorInterpolationMode,[Out, Fast] ID2D1GradientStopCollection1** gradientStopCollection1)</unmanaged>
        /// <remarks>
        /// This method linearly interpolates between the color stops. An optional color space conversion is applied after interpolation. Whether and how this gamma conversion is applied is determined before and after interpolation. This method will fail if the device context does not support the requested buffer precision.Additional ReferencesD2D1_GRADIENT_STOP, D2D1_GAMMA_CONVERSION, <see cref="SharpDX.Direct2D1.BufferPrecision"/>, <see cref="SharpDX.Direct2D1.ExtendMode"/>, <see cref="SharpDX.Direct2D1.GradientStopCollection"/>RequirementsMinimum supported operating systemSame as Interface / Class Highest IRQL levelN/A (user mode) Callable from DlllMain()No Callable from services and session 0Yes Callable from UI threadYes?
        /// </remarks>
        public GradientStopCollection1(DeviceContext context, SharpDX.Direct2D1.GradientStop[] straightAlphaGradientStops, SharpDX.Direct2D1.ColorSpace preInterpolationSpace, SharpDX.Direct2D1.ColorSpace postInterpolationSpace, SharpDX.Direct2D1.BufferPrecision bufferPrecision, SharpDX.Direct2D1.ExtendMode extendMode, SharpDX.Direct2D1.ColorInterpolationMode colorInterpolationMode)
            : base(IntPtr.Zero)
        {
            context.CreateGradientStopCollection(straightAlphaGradientStops, straightAlphaGradientStops.Length, preInterpolationSpace, postInterpolationSpace, bufferPrecision, extendMode, colorInterpolationMode, this);

        }
Esempio n. 51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageBrush"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="image">The image.</param>
 /// <param name="imageBrushProperties">The image brush properties.</param>
 /// <param name="brushProperties">The brush properties.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateImageBrush([In] ID2D1Image* image,[In] const D2D1_IMAGE_BRUSH_PROPERTIES* imageBrushProperties,[In, Optional] const D2D1_BRUSH_PROPERTIES* brushProperties,[Out, Fast] ID2D1ImageBrush** imageBrush)</unmanaged>	
 public ImageBrush(DeviceContext context, SharpDX.Direct2D1.Image image, SharpDX.Direct2D1.ImageBrushProperties imageBrushProperties, SharpDX.Direct2D1.BrushProperties brushProperties)
     : base(IntPtr.Zero)
 {
     context.CreateImageBrush(image, ref imageBrushProperties, brushProperties, this);
 }
        /// <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);
        }
Esempio n. 53
0
        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);
        }
Esempio n. 54
0
 /// <summary>	
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="dataStream">A pointer to the memory location of the image data, or NULL to create an uninitialized bitmap.</param>
 /// <param name="pitch">The byte count of each scanline, which is equal to (the image width in pixels * the number of bytes per pixel) + memory padding. If srcData is NULL, this value is ignored. (Note that pitch is also sometimes called stride.)</param>
 /// <param name="bitmapProperties">The pixel format and dots per inch (DPI) of the bitmap to create.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, DrawingSize size, DataStream dataStream, int pitch, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : base(IntPtr.Zero)
 {
     deviceContext.CreateBitmap(size, dataStream == null ? IntPtr.Zero : dataStream.PositionPointer, pitch, bitmapProperties, this);
 }
Esempio n. 55
0
 /// <summary>	
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, DrawingSize size)
     : this(deviceContext, size, null, 0, new BitmapProperties1(new PixelFormat(Format.Unknown, AlphaMode.Unknown)))
 {
 }
Esempio n. 56
0
 /// <summary>
 /// Creates a Bitmap from a wic bitmap.
 /// </summary>
 /// <param name="deviceContext">The render target.</param>
 /// <param name="wicBitmap">The wic bitmap.</param>
 /// <param name="bitmapProperties">The bitmap properties.</param>
 /// <returns></returns>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapFromWicBitmap([In] IWICBitmapSource* wicBitmapSource,[In, Optional] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out] ID2D1Bitmap1** bitmap)</unmanaged>	
 public static Bitmap FromWicBitmap(DeviceContext deviceContext, WIC.BitmapSource wicBitmap, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
 {
     Bitmap1 bitmap;
     deviceContext.CreateBitmapFromWicBitmap(wicBitmap, bitmapProperties, out bitmap);
     return bitmap;
 }
Esempio n. 57
0
 /// <summary>	
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="bitmapProperties">The pixel format and dots per inch (DPI) of the bitmap to create.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, DrawingSize size, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : this(deviceContext, size, null, 0, bitmapProperties)
 {
 }
Esempio n. 58
0
 /// <summary>	
 /// Creates an <see cref="SharpDX.Direct2D1.Bitmap"/> whose data is shared with another resource.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="surface">An <see cref="SharpDX.DXGI.Surface"/> that contains the data to share with the new ID2D1Bitmap. For more information, see the Remarks section.</param>
 /// <param name="bitmapProperties">The pixel format  and DPI of the bitmap to create . The <see cref="SharpDX.DXGI.Format"/> portion of the pixel format  must match the <see cref="SharpDX.DXGI.Format"/> of data or the method will fail, but the alpha modes don't have to match. To prevent a  mismatch, you can pass NULL or the value obtained from the {{D2D1::PixelFormat}} helper function. The DPI settings do not have to match those of data. If both dpiX and dpiY are  0.0f, the default DPI, 96, is used.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapFromDxgiSurface([In] IDXGISurface* surface,[In, Optional] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap1)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, Surface surface, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : base(IntPtr.Zero)
 {
     deviceContext.CreateBitmapFromDxgiSurface(surface, bitmapProperties, this);
 }
        /// <summary>
        /// Creates device resources. 
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

            // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default
            try
            {
                // Try to create it with Video Support
                // If it is not working, we just use BGRA
                // Force to FeatureLevel.Level_9_1
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            } catch (Exception)
            {
                creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            }
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
Esempio n. 60
0
 /// <summary>	
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="dataStream">A pointer to the memory location of the image data, or NULL to create an uninitialized bitmap.</param>
 /// <param name="pitch">The byte count of each scanline, which is equal to (the image width in pixels * the number of bytes per pixel) + memory padding. If srcData is NULL, this value is ignored. (Note that pitch is also sometimes called stride.)</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, DrawingSize size, DataStream dataStream, int pitch)
     : this(deviceContext, size, dataStream, pitch, new BitmapProperties1(new PixelFormat(Format.Unknown, AlphaMode.Unknown)))
 {
 }