Пример #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TileBrushImpl"/> class.
        /// </summary>
        /// <param name="brush"></param>
        /// <param name="target"></param>
        /// <param name="targetSize"></param>
        public TileBrushImpl(
            TileBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size targetSize)
        {
            var helper = new TileBrushImplHelper(brush, targetSize);

            if (!helper.IsValid)
            {
                return;
            }

            using (var intermediate = new BitmapRenderTarget(target, CompatibleRenderTargetOptions.None, helper.IntermediateSize.ToSharpDX()))
            {
                using (var ctx = new RenderTarget(intermediate).CreateDrawingContext())
                {
                    intermediate.Clear(null);
                    helper.DrawIntermediate(ctx);
                }

                PlatformBrush = new BitmapBrush(
                    target,
                    intermediate.Bitmap,
                    GetBitmapBrushProperties(brush),
                    GetBrushProperties(brush, helper.DestinationRect));
            }
        }
        private BitmapRenderTarget RenderIntermediate(
            SharpDX.Direct2D1.RenderTarget target,
            BitmapImpl bitmap,
            TileBrushCalculator calc)
        {
            var result = new BitmapRenderTarget(
                target,
                CompatibleRenderTargetOptions.None,
                calc.IntermediateSize.ToSharpDX());

            using (var context = new RenderTarget(result).CreateDrawingContext(null))
            {
                var dpi  = new Vector(target.DotsPerInch.Width, target.DotsPerInch.Height);
                var rect = new Rect(bitmap.PixelSize.ToSizeWithDpi(dpi));

                context.Clear(Colors.Transparent);
                context.PushClip(calc.IntermediateClip);
                context.Transform = calc.IntermediateTransform;

                context.DrawBitmap(RefCountable.CreateUnownedNotClonable(bitmap), 1, rect, rect, _bitmapInterpolationMode);
                context.PopClip();
            }

            return(result);
        }
Пример #3
0
 private void CreateRenderTargets()
 {
     _windowRenderTarget = new WindowRenderTarget
                           (
         _factory,
         new RenderTargetProperties()
     {
         PixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Ignore),
         Type        = RenderTargetType.Default,
         MinLevel    = FeatureLevel.Level_DEFAULT
     },
         new HwndRenderTargetProperties()
     {
         Hwnd           = RenderControl.Handle,
         PixelSize      = new Size2(RenderControl.ClientSize.Width, RenderControl.ClientSize.Height),
         PresentOptions = PresentOptions.Immediately
     }
                           )
     {
         DotsPerInch   = new Size2F(96.0f, 96.0f),
         AntialiasMode = AntialiasMode.Aliased,
     };
     if (BorderVisible)
     {
         CreateCompositeRenderTarget();
     }
     _screenRenderTarget = new BitmapRenderTarget(_windowRenderTarget, CompatibleRenderTargetOptions.None, new Size2F(160, 144), new Size2(160, 144), null);
     RecalculateDrawRectangle();
 }
Пример #4
0
        /// <summary>
        /// Create the grid pattern (squares) brush
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        BitmapBrush CreateGridPatternBrush(RenderTarget target)
        {
            // Create a compatible render target.
            BitmapRenderTarget compatibleRenderTarget =
                target.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, new SizeF(10.0f, 10.0f));

            //// Draw a pattern.
            SolidColorBrush spGridBrush = compatibleRenderTarget.CreateSolidColorBrush(new ColorF(0.93f, 0.94f, 0.96f, 1.0f));

            compatibleRenderTarget.BeginDraw();
            compatibleRenderTarget.FillRectangle(new RectF(0.0f, 0.0f, 10.0f, 1.0f), spGridBrush);
            compatibleRenderTarget.FillRectangle(new RectF(0.0f, 0.1f, 1.0f, 10.0f), spGridBrush);
            compatibleRenderTarget.EndDraw();

            //// Retrieve the bitmap from the render target.
            D2DBitmap spGridBitmap;

            spGridBitmap = compatibleRenderTarget.Bitmap;

            //// Choose the tiling mode for the bitmap brush.
            BitmapBrushProperties brushProperties = new BitmapBrushProperties(ExtendMode.Wrap, ExtendMode.Wrap, BitmapInterpolationMode.Linear);

            //// Create the bitmap brush.
            return(renderTarget.CreateBitmapBrush(spGridBitmap, brushProperties));
        }
        public void Pixel_coordinates_are_relative_to_the_lower_left_corner_of_the_image()
        {
            using(var target = new BitmapRenderTarget(100, 100)) {
                target.SetPixelColor(new Pixel(0, 0), Color.Red);

                Assert.Equal(Color.Red.ToDrawingColor(), target.Bitmap.GetPixel(0, target.Height - 1));
            }
        }
        public void Pixel_coordinates_are_relative_to_the_lower_left_corner_of_the_image()
        {
            using (var target = new BitmapRenderTarget(100, 100)) {
                target.SetPixelColor(new Pixel(0, 0), Color.Red);

                Assert.Equal(Color.Red.ToDrawingColor(), target.Bitmap.GetPixel(0, target.Height - 1));
            }
        }
Пример #7
0
        public VisualBrushImpl(
            VisualBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size targetSize)
        {
            var visual = brush.Visual;

            if (visual == null)
            {
                return;
            }

            var layoutable = visual as ILayoutable;

            if (layoutable?.IsArrangeValid == false)
            {
                layoutable.Measure(Size.Infinity);
                layoutable.Arrange(new Rect(layoutable.DesiredSize));
            }

            var tileMode         = brush.TileMode;
            var sourceRect       = brush.SourceRect.ToPixels(layoutable.Bounds.Size);
            var destinationRect  = brush.DestinationRect.ToPixels(targetSize);
            var scale            = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate        = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var intermediateSize = CalculateIntermediateSize(tileMode, targetSize, destinationRect.Size);
            var brtOpts          = CompatibleRenderTargetOptions.None;

            // TODO: There are times where we don't need to draw an intermediate bitmap. Identify
            // them and directly use 'image' in those cases.
            using (var intermediate = new BitmapRenderTarget(target, brtOpts, intermediateSize))
            {
                Rect drawRect;
                var  transform = CalculateIntermediateTransform(
                    tileMode,
                    sourceRect,
                    destinationRect,
                    scale,
                    translate,
                    out drawRect);
                var renderer = new RenderTarget(intermediate);

                using (var ctx = renderer.CreateDrawingContext())
                    using (ctx.PushClip(drawRect))
                        using (ctx.PushPostTransform(transform))
                        {
                            intermediate.Clear(new Color4(0));
                            ctx.Render(visual);
                        }

                this.PlatformBrush = new BitmapBrush(
                    target,
                    intermediate.Bitmap,
                    GetBitmapBrushProperties(brush),
                    GetBrushProperties(brush, destinationRect));
            }
        }
Пример #8
0
        protected BitmapSence(string id = "", [MustNotEqualNull] Control control = null)
            : base(id, control)
        {
            BufferBitmapRenderTarget = new BitmapRenderTarget(SurfaceRenderTarget,
                                                              CompatibleRenderTargetOptions.None);

            _backgroundBitmap = new Bitmap(string.Empty, control.Width, control.Height, PixelFormat.Bgra32);
            _foregroundBitmap = new Bitmap(string.Empty, control.Width, control.Height, PixelFormat.Bgra32);
        }
Пример #9
0
 public D2DRenderTargetBitmapImpl(
     ImagingFactory imagingFactory,
     DirectWriteFactory dwriteFactory,
     BitmapRenderTarget target)
     : base(imagingFactory, target.Bitmap)
 {
     _dwriteFactory = dwriteFactory;
     _target        = target;
 }
Пример #10
0
        public VisualBrushImpl(
            VisualBrush brush,
            RenderTarget target,
            Size targetSize)
        {
            var visual     = brush.Visual;
            var layoutable = visual as ILayoutable;

            if (layoutable?.IsArrangeValid == false)
            {
                layoutable.Measure(Size.Infinity);
                layoutable.Arrange(new Rect(layoutable.DesiredSize));
            }

            var sourceRect      = brush.SourceRect.ToPixels(layoutable.Bounds.Size);
            var destinationRect = brush.DestinationRect.ToPixels(targetSize);
            var bitmapSize      = brush.TileMode == TileMode.None ? targetSize : destinationRect.Size;
            var scale           = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate       = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var options         = CompatibleRenderTargetOptions.None;

            using (var brt = new BitmapRenderTarget(target, options, bitmapSize.ToSharpDX()))
            {
                var renderer  = new Renderer(brt);
                var transform = Matrix.CreateTranslation(-sourceRect.Position) *
                                Matrix.CreateScale(scale) *
                                Matrix.CreateTranslation(translate);

                Rect drawRect;

                if (brush.TileMode == TileMode.None)
                {
                    drawRect   = destinationRect;
                    transform *= Matrix.CreateTranslation(destinationRect.Position);
                }
                else
                {
                    drawRect = new Rect(0, 0, destinationRect.Width, destinationRect.Height);
                }

                renderer.Render(visual, null, transform, drawRect);

                var result = new BitmapBrush(brt, brt.Bitmap);
                result.ExtendModeX = (brush.TileMode & TileMode.FlipX) != 0 ? ExtendMode.Mirror : ExtendMode.Wrap;
                result.ExtendModeY = (brush.TileMode & TileMode.FlipY) != 0 ? ExtendMode.Mirror : ExtendMode.Wrap;

                if (brush.TileMode != TileMode.None)
                {
                    result.Transform = SharpDX.Matrix3x2.Translation(
                        (float)destinationRect.X,
                        (float)destinationRect.Y);
                }

                PlatformBrush = result;
            }
        }
Пример #11
0
        /// <summary>
        /// Initialize the device on the control.
        /// </summary>
        /// <param name="control"></param>
        public void Initialize(Control control)
        {
            padding = control.Padding;
            size    = control.Size;
            var renderTargetProperties = new RenderTargetProperties()
            {
                DpiX     = 96,
                DpiY     = 96,
                MinLevel = FeatureLevel.Level_9,
                Type     = RenderTargetType.Hardware,
                Usage    = RenderTargetUsage.None
            };

            var windowsRenderTargetPropertiesPointer = new HwndRenderTargetProperties()
            {
                Hwnd           = control.Handle,
                PixelSize      = new SharpDX.Size2(control.ClientSize.Width, control.ClientSize.Height),
                PresentOptions = PresentOptions.Immediately
            };

            if (renderTarget != null)
            {
                ((WindowRenderTarget)renderTarget).Resize(new SharpDX.Size2(control.ClientSize.Width, control.ClientSize.Height));
                for (int i = 0; i < layers.Count; i++)
                {
                    if (layers[i] != null)
                    {
                        layers[i].Dispose();
                    }
                    if (i == 5)
                    {
                        float w = control.ClientSize.Width - control.Padding.Left - control.Padding.Right;
                        float h = control.ClientSize.Height - control.Padding.Top - control.Padding.Bottom;
                        if (w < 1)
                        {
                            w = 50;
                        }
                        if (h < 1)
                        {
                            h = 50;
                        }
                        layers[i] = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.None,
                                                           new SharpDX.Size2F(w, h));
                    }
                    else
                    {
                        layers[i] = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.None);
                    }
                }
            }
            else
            {
                windowsRenderTargetPropertiesPointer.PixelSize = new SharpDX.Size2(control.ClientSize.Width, control.ClientSize.Height);
                renderTarget = new WindowRenderTarget(factory, renderTargetProperties, windowsRenderTargetPropertiesPointer);
            }
        }
 private void RenderImage(string fileName, RenderInvoker render)
 {
     using (var bmp = new Bitmap(256, 256, PixelFormat.Format32bppArgb))
         using (var target = new BitmapRenderTarget(bmp))
         {
             target.Fill(new RopeSnake.Graphics.Color(0, 0, 0, 0));
             render(target);
             bmp.Save(fileName);
         }
 }
Пример #13
0
 private void CreateCompositeRenderTarget()
 {
     if (_compositeRenderTarget == null)
     {
         _compositeRenderTarget = new BitmapRenderTarget(_windowRenderTarget, CompatibleRenderTargetOptions.None, new Size2F(256, 224), new Size2(256, 224), new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Ignore))
         {
             DotsPerInch   = new Size2F(96.0f, 96.0f),
             AntialiasMode = AntialiasMode.Aliased,
         };
     }
 }
Пример #14
0
        public static D2DRenderTargetBitmapImpl CreateCompatible(
            SharpDX.Direct2D1.RenderTarget renderTarget,
            Size size)
        {
            var bitmapRenderTarget = new BitmapRenderTarget(
                renderTarget,
                CompatibleRenderTargetOptions.None,
                new Size2F((float)size.Width, (float)size.Height));

            return(new D2DRenderTargetBitmapImpl(bitmapRenderTarget));
        }
Пример #15
0
 protected override void DrawElement(RenderTarget rt)
 {
     if (bitmapRt == null || bitmapRt.Size != rt.Size)
     {
         bitmapRt?.Dispose();
         bitmapRt = rt.CreateCompatibleRenderTarget(new CompatibleRenderTargetOptions(), rt.Size);
     }
     bitmapRt.Transform = rt.Transform;
     DrawLayerOnBitmap();
     DrawLayerToTarget(rt);
     return;
 }
Пример #16
0
 private void DisposeRenderTargets()
 {
     if (_compositeRenderTarget != null)
     {
         _compositeRenderTarget.Dispose();
     }
     _compositeRenderTarget = null;
     if (_windowRenderTarget != null)
     {
         _windowRenderTarget.Dispose();
     }
     _windowRenderTarget = null;
 }
Пример #17
0
        public static D2DRenderTargetBitmapImpl CreateCompatible(
            ImagingFactory imagingFactory,
            DirectWriteFactory dwriteFactory,
            SharpDX.Direct2D1.RenderTarget renderTarget,
            Size size)
        {
            var bitmapRenderTarget = new BitmapRenderTarget(
                renderTarget,
                CompatibleRenderTargetOptions.None,
                new Size2F((float)size.Width, (float)size.Height));

            return(new D2DRenderTargetBitmapImpl(imagingFactory, dwriteFactory, bitmapRenderTarget));
        }
Пример #18
0
        public ImageBrushImpl(
            ImageBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size targetSize)
        {
            if (brush.Source == null)
            {
                return;
            }

            var image            = ((BitmapImpl)brush.Source.PlatformImpl).GetDirect2DBitmap(target);
            var imageSize        = new Size(brush.Source.PixelWidth, brush.Source.PixelHeight);
            var tileMode         = brush.TileMode;
            var sourceRect       = brush.SourceRect.ToPixels(imageSize);
            var destinationRect  = brush.DestinationRect.ToPixels(targetSize);
            var scale            = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate        = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var intermediateSize = CalculateIntermediateSize(tileMode, targetSize, destinationRect.Size);
            var brtOpts          = CompatibleRenderTargetOptions.None;

            // TODO: There are times where we don't need to draw an intermediate bitmap. Identify
            // them and directly use 'image' in those cases.
            using (var intermediate = new BitmapRenderTarget(target, brtOpts, intermediateSize))
            {
                Rect drawRect;
                var  transform = CalculateIntermediateTransform(
                    tileMode,
                    sourceRect,
                    destinationRect,
                    scale,
                    translate,
                    out drawRect);

                intermediate.BeginDraw();
                intermediate.PushAxisAlignedClip(drawRect.ToDirect2D(), AntialiasMode.Aliased);
                intermediate.Transform = transform.ToDirect2D();
                intermediate.DrawBitmap(image, 1, BitmapInterpolationMode.Linear);
                intermediate.PopAxisAlignedClip();
                intermediate.EndDraw();

                this.PlatformBrush = new BitmapBrush(
                    target,
                    intermediate.Bitmap,
                    GetBitmapBrushProperties(brush),
                    GetBrushProperties(brush, destinationRect));
            }
        }
Пример #19
0
        protected override void Render(RenderTarget rt)
        {
            if (image == null)
            {
                base.Render(rt);
                return;
            }
            rt.Clear(this.SceneColorBrush.Color);

            rt.Transform = Matrix3x2.Identity;

            Size2 imageSize = this.image.PixelSize;

            double scale       = Math.Min((double)(ClientSize.Width - ImagePadding) / imageSize.Width, (double)(ClientSize.Height - ImagePadding) / imageSize.Height);
            int    imageWidth  = (int)(imageSize.Width * scale);
            int    imageHeight = (int)(imageSize.Height * scale);

            var rcBounds = new RectangleF(0, 0, imageSize.Width, imageSize.Height);
            var rcImage  = new RectangleF((ClientSize.Width - imageWidth) / 2, (ClientSize.Height - imageHeight) / 2, imageWidth, imageHeight);

            bool isBGRAImage = image.PixelFormat.Format == SharpDX.DXGI.Format.B8G8R8A8_UNorm;

            if (!isBGRAImage)
            {
                var sz = new Size2F(imageSize.Width, imageSize.Height);
                var rc = new RectangleF(0, 0, imageSize.Width, imageSize.Height);

                if (bgraImageRenderer == null || bgraImageRenderer.Size != sz)
                {
                    SharpDX.Utilities.Dispose(ref bgraImageRenderer);
                    bgraImageRenderer = new BitmapRenderTarget(RenderTarget2D, CompatibleRenderTargetOptions.None, sz);
                }

                bgraImageRenderer.BeginDraw();
                bgraImageRenderer.Clear(Color.Black);
                bgraImageRenderer.AntialiasMode = AntialiasMode.Aliased;
                bgraImageRenderer.FillOpacityMask(this.image, whiteBrush, OpacityMaskContent.Graphics, rc, rc);
                bgraImageRenderer.EndDraw();
            }

            rt.DrawBitmap(isBGRAImage ? image : bgraImageRenderer.Bitmap, rcImage, 1, BitmapInterpolationMode.NearestNeighbor, rcBounds);

            if (ImagePadding != 0)
            {
                rt.DrawRectangle(rcImage, whiteBrush, 1);
            }
        }
Пример #20
0
 protected override void OnResize(EventArgs e)
 {
     lock (renderSyncObject)
     {
         if (RenderTarget != null)
         {
             // Resize the render targrt to the actual host size
             var size = new SizeU((uint)ClientSize.Width, (uint)ClientSize.Height);
             if (hwndRenderTarget != null)
             {
                 hwndRenderTarget.Resize(size); //need to resize hwndRenderTarget to make its size same as the window's size
             }
             if (renderMode == RenderModes.BitmapRenderTargetOnPaint)
             {
                 bitmapRenderTarget.Dispose();
                 bitmapRenderTarget = dcRenderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.GdiCompatible, new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                 bitmap             = null; //the bitmap created in dc render target can't be used in hwnd render target
                 foreach (var shape in drawingShapes)
                 {
                     shape.Bitmap       = Bitmap;
                     shape.RenderTarget = RenderTarget;
                 }
                 RefreshAll();
             }
             else if (renderMode == RenderModes.BitmapRenderTargetRealTime)
             {
                 Debug.Assert(hwndRenderTarget != null);//this should never be null considering the above
                 bitmapRenderTarget.Dispose();
                 bitmapRenderTarget = hwndRenderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.GdiCompatible, new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                 bitmap             = null; //the bitmap created in dc render target can't be used in hwnd render target
                 foreach (var shape in drawingShapes)
                 {
                     shape.Bitmap       = Bitmap;
                     shape.RenderTarget = RenderTarget;
                 }
                 RefreshAll();
             }
         }
     }
     base.OnResize(e);
 }
Пример #21
0
        protected BaseContour(Direct3DSurface surface)
        {
            if (surface == null)
            {
                throw new ArgumentNullException("Surface", "Surface is null. Cannot create render target for contour.");
            }

            _surface = surface;

            var desc = new Texture2DDescription
            {
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.R8G8B8A8_UNorm,
                Height            = MM_Repository.OverallDisplay.MapTileSize.Height,
                Width             = MM_Repository.OverallDisplay.MapTileSize.Width,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.None,
                CpuAccessFlags    = CpuAccessFlags.None,
                ArraySize         = 1
            };

            _tileTexture2D = new Texture2D(_surface.Device, desc);


            _dxgiSurface = _tileTexture2D.QueryInterface <Surface>();


            _renderTarget2D     = new RenderTarget(_surface.Factory2D, _dxgiSurface, new RenderTargetProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)));
            _bitmapRenderTarget = new BitmapRenderTarget(_renderTarget2D, CompatibleRenderTargetOptions.None)
            {
                AntialiasMode = _surface.AntialiasMode
            };

            _renderTargetView = new RenderTargetView(_surface.Device, _tileTexture2D);

            InitializeShader();
        }
Пример #22
0
        private BitmapRenderTarget RenderIntermediate(
            SharpDX.Direct2D1.RenderTarget target,
            BitmapImpl bitmap,
            TileBrushCalculator calc)
        {
            var result = new BitmapRenderTarget(
                target,
                CompatibleRenderTargetOptions.None,
                calc.IntermediateSize.ToSharpDX());

            using (var context = new RenderTarget(result).CreateDrawingContext(null))
            {
                var rect = new Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight);

                context.Clear(Colors.Transparent);
                context.PushClip(calc.IntermediateClip);
                context.Transform = calc.IntermediateTransform;
                context.DrawImage(bitmap, 1, rect, rect);
                context.PopClip();
            }

            return(result);
        }
Пример #23
0
        /// <summary>
        /// Dispose of resources (IDisposable implementation)
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && !disposed)
            {
                lock (renderSyncObject)
                {
                    render = null;

                    lock (sharedSyncObject)
                    {
                        if (sharedD2DFactory != null && d2DFactory == sharedD2DFactory)
                            sharedRefCount--;

                        if (d2DFactory != null && d2DFactory != sharedD2DFactory)
                            d2DFactory.Dispose();
                        d2DFactory = null;

                        if (dwriteFactory != null && dwriteFactory != sharedDwriteFactory)
                            dwriteFactory.Dispose();
                        dwriteFactory = null;

                        if (wicFactory != null && wicFactory != sharedWicFactory)
                            wicFactory.Dispose();
                        wicFactory = null;

                        if (sharedRefCount == 0)
                        {
                            if (sharedD2DFactory != null)
                                sharedD2DFactory.Dispose();
                            sharedD2DFactory = null;

                            if (sharedDwriteFactory != null)
                                sharedDwriteFactory.Dispose();
                            sharedDwriteFactory = null;

                            if (sharedWicFactory != null)
                                sharedWicFactory.Dispose();
                            sharedWicFactory = null;
                        }
                    }

                    foreach (DrawingShape shape in drawingShapes)
                    {
                        shape.Dispose();
                    }

                    if (bitmap != null)
                        bitmap.Dispose();
                    bitmap = null;

                    if (dcRenderTarget != null)
                        dcRenderTarget.Dispose();
                    dcRenderTarget = null;
                    if (bitmapRenderTarget != null)
                        bitmapRenderTarget.Dispose();
                    bitmapRenderTarget = null;
                    if (hwndRenderTarget != null)
                        hwndRenderTarget.Dispose();
                    hwndRenderTarget = null;


                    disposed = true;
                }
            }
            base.Dispose(disposing);
        }
        /// <summary>
        /// Creates a Direct2D brush wrapper for a Avalonia brush.
        /// </summary>
        /// <param name="brush">The avalonia brush.</param>
        /// <param name="destinationSize">The size of the brush's target area.</param>
        /// <returns>The Direct2D brush wrapper.</returns>
        public BrushImpl CreateBrush(IBrush brush, Size destinationSize)
        {
            var solidColorBrush     = brush as ISolidColorBrush;
            var linearGradientBrush = brush as ILinearGradientBrush;
            var radialGradientBrush = brush as IRadialGradientBrush;
            var imageBrush          = brush as IImageBrush;
            var visualBrush         = brush as IVisualBrush;

            if (solidColorBrush != null)
            {
                return(new SolidColorBrushImpl(solidColorBrush, _deviceContext));
            }
            else if (linearGradientBrush != null)
            {
                return(new LinearGradientBrushImpl(linearGradientBrush, _deviceContext, destinationSize));
            }
            else if (radialGradientBrush != null)
            {
                return(new RadialGradientBrushImpl(radialGradientBrush, _deviceContext, destinationSize));
            }
            else if (imageBrush?.Source != null)
            {
                return(new ImageBrushImpl(
                           imageBrush,
                           _deviceContext,
                           (BitmapImpl)imageBrush.Source.PlatformImpl.Item,
                           destinationSize));
            }
            else if (visualBrush != null)
            {
                if (_visualBrushRenderer != null)
                {
                    var intermediateSize = _visualBrushRenderer.GetRenderTargetSize(visualBrush);

                    if (intermediateSize.Width >= 1 && intermediateSize.Height >= 1)
                    {
                        // We need to ensure the size we're requesting is an integer pixel size, otherwise
                        // D2D alters the DPI of the render target, which messes stuff up. PixelSize.FromSize
                        // will do the rounding for us.
                        var dpi       = new Vector(_deviceContext.DotsPerInch.Width, _deviceContext.DotsPerInch.Height);
                        var pixelSize = PixelSize.FromSizeWithDpi(intermediateSize, dpi);

                        using (var intermediate = new BitmapRenderTarget(
                                   _deviceContext,
                                   CompatibleRenderTargetOptions.None,
                                   pixelSize.ToSizeWithDpi(dpi).ToSharpDX()))
                        {
                            using (var ctx = new RenderTarget(intermediate).CreateDrawingContext(_visualBrushRenderer))
                            {
                                intermediate.Clear(null);
                                _visualBrushRenderer.RenderVisualBrush(ctx, visualBrush);
                            }

                            return(new ImageBrushImpl(
                                       visualBrush,
                                       _deviceContext,
                                       new D2DBitmapImpl(intermediate.Bitmap),
                                       destinationSize));
                        }
                    }
                }
                else
                {
                    throw new NotSupportedException("No IVisualBrushRenderer was supplied to DrawingContextImpl.");
                }
            }

            return(new SolidColorBrushImpl(null, _deviceContext));
        }
Пример #25
0
        void CreateDeviceResources()
        {
            uint width  = (uint)host.ActualWidth;
            uint height = (uint)host.ActualHeight;

            // If we don't have a device, need to create one now and all
            // accompanying D3D resources.
            CreateDevice();

            Factory dxgiFactory = Factory.Create();

            SwapChainDescription swapDesc = new SwapChainDescription
            {
                BufferDescription = new ModeDescription
                {
                    Width       = width, Height = height,
                    Format      = Format.R8G8B8A8UNorm,
                    RefreshRate = new Rational {
                        Numerator = 60, Denominator = 1
                    }
                },
                SampleDescription = new SampleDescription {
                    Count = 1, Quality = 0
                },
                BufferUsage        = UsageOptions.RenderTargetOutput,
                BufferCount        = 1,
                OutputWindowHandle = host.Handle,
                Windowed           = true
            };

            swapChain = dxgiFactory.CreateSwapChain(
                device, swapDesc);

            // Create rasterizer state object
            RasterizerDescription rsDesc = new RasterizerDescription();

            rsDesc.AntiAliasedLineEnable = false;
            rsDesc.CullMode              = CullMode.None;
            rsDesc.DepthBias             = 0;
            rsDesc.DepthBiasClamp        = 0;
            rsDesc.DepthClipEnable       = true;
            rsDesc.FillMode              = D3D10.FillMode.Solid;
            rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9
            rsDesc.MultisampleEnable     = false;
            rsDesc.ScissorEnable         = false;
            rsDesc.SlopeScaledDepthBias  = 0;

            rasterizerState = device.CreateRasterizerState(
                rsDesc);

            device.RS.State = rasterizerState;

            // If we don't have a D2D render target, need to create all of the resources
            // required to render to one here.
            // Ensure that nobody is holding onto one of the old resources
            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { null });

            InitializeDepthStencil(width, height);

            // Create views on the RT buffers and set them on the device
            RenderTargetViewDescription renderDesc = new RenderTargetViewDescription();

            renderDesc.Format        = Format.R8G8B8A8UNorm;
            renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D;

            Texture2DRenderTargetView renderView = renderDesc.Texture2D;

            renderView.MipSlice  = 0;
            renderDesc.Texture2D = renderView;

            using (D3DResource spBackBufferResource = swapChain.GetBuffer <D3DResource>(0))
            {
                renderTargetView = device.CreateRenderTargetView(
                    spBackBufferResource,
                    renderDesc);
            }

            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView);

            SetViewport(width, height);


            // Create a D2D render target which can draw into the surface in the swap chain
            RenderTargetProperties props =
                new RenderTargetProperties(
                    RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
                    96, 96, RenderTargetUsages.None, FeatureLevel.Default);

            // Allocate a offscreen D3D surface for D2D to render our 2D content into
            Texture2DDescription tex2DDescription = new Texture2DDescription
            {
                ArraySize                    = 1,
                BindingOptions               = BindingOptions.RenderTarget | BindingOptions.ShaderResource,
                CpuAccessOptions             = CpuAccessOptions.None,
                Format                       = Format.R8G8B8A8UNorm,
                Height                       = 4096,
                Width                        = 512,
                MipLevels                    = 1,
                MiscellaneousResourceOptions = MiscellaneousResourceOptions.None,
                SampleDescription            = new SampleDescription {
                    Count = 1, Quality = 0
                },
                Usage = Usage.Default
            };

            offscreenTexture = device.CreateTexture2D(tex2DDescription);

            using (Surface dxgiSurface = offscreenTexture.GraphicsSurface)
            {
                // Create a D2D render target which can draw into our offscreen D3D surface
                renderTarget = d2DFactory.CreateGraphicsSurfaceRenderTarget(
                    dxgiSurface,
                    props);
            }

            PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8UNorm, AlphaMode.Premultiplied);

            opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None,
                                                                            alphaOnlyFormat);

            // Load pixel shader
            // Open precompiled vertex shader
            // This file was compiled using DirectX's SDK Shader compilation tool:
            // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx
            shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo");

            // Obtain the technique
            technique = shader.GetTechniqueByName("Render");

            // Obtain the variables
            worldMatrixVariable     = shader.GetVariableByName("World").AsMatrix;
            viewMatrixVariable      = shader.GetVariableByName("View").AsMatrix;
            projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix;
            diffuseVariable         = shader.GetVariableByName("txDiffuse").AsShaderResource;

            // Create the input layout
            PassDescription passDesc = new PassDescription();

            passDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                inputLayoutDescriptions,
                passDesc.InputAssemblerInputSignature,
                passDesc.InputAssemblerInputSignatureSize
                );

            // Set the input layout
            device.IA.InputLayout = vertexLayout;

            IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance));

            Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true);

            BufferDescription bd = new BufferDescription();

            bd.Usage                        = Usage.Default;
            bd.ByteWidth                    = (uint)Marshal.SizeOf(VertexArray.VerticesInstance);
            bd.BindingOptions               = BindingOptions.VertexBuffer;
            bd.CpuAccessOptions             = CpuAccessOptions.None;
            bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;

            SubresourceData InitData = new SubresourceData {
                SystemMemory = verticesDataPtr
            };

            vertexBuffer = device.CreateBuffer(bd, InitData);

            Marshal.FreeHGlobal(verticesDataPtr);

            // Set vertex buffer
            uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex));
            uint offset = 0;

            device.IA.SetVertexBuffers(
                0,
                new D3DBuffer[] { vertexBuffer },
                new uint[] { stride },
                new uint[] { offset }
                );

            IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance));

            Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true);

            bd.Usage                        = Usage.Default;
            bd.ByteWidth                    = (uint)Marshal.SizeOf(VertexArray.IndicesInstance);
            bd.BindingOptions               = BindingOptions.IndexBuffer;
            bd.CpuAccessOptions             = CpuAccessOptions.None;
            bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;

            InitData.SystemMemory = indicesDataPtr;

            facesIndexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(indicesDataPtr);

            // Set primitive topology
            device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // Convert the D2D texture into a Shader Resource View
            textureResourceView = device.CreateShaderResourceView(
                offscreenTexture);

            // Initialize the world matrices
            worldMatrix = Matrix4x4F.Identity;

            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f);
            Vector3F At  = new Vector3F(0.0f, -3.5f, 45.0f);
            Vector3F Up  = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = Camera.MatrixPerspectiveFovLH(
                (float)Math.PI * 0.1f,
                width / (float)height,
                0.1f,
                100.0f);

            // Update Variables that never change
            viewMatrixVariable.Matrix = viewMatrix;

            projectionMarixVariable.Matrix = projectionMatrix;

            GradientStop[] gradientStops =
            {
                new GradientStop(0.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Yellow))),
                new GradientStop(1.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Black)))
            };

            GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection(
                gradientStops, Gamma.StandardRgb, ExtendMode.Clamp);

            // Create a linear gradient brush for text
            textBrush = renderTarget.CreateLinearGradientBrush(
                new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)),
                spGradientStopCollection
                );
        }
Пример #26
0
        void CreateDeviceResources()
        {
            uint width = (uint) host.ActualWidth;
            uint height = (uint) host.ActualHeight;

            // If we don't have a device, need to create one now and all
            // accompanying D3D resources.
            CreateDevice();

            DXGIFactory dxgiFactory = DXGIFactory.CreateFactory();

            SwapChainDescription swapDesc = new SwapChainDescription();
            swapDesc.BufferDescription.Width = width;
            swapDesc.BufferDescription.Height = height;
            swapDesc.BufferDescription.Format = Format.R8G8B8A8_UNORM;
            swapDesc.BufferDescription.RefreshRate.Numerator = 60;
            swapDesc.BufferDescription.RefreshRate.Denominator = 1;
            swapDesc.SampleDescription.Count = 1;
            swapDesc.SampleDescription.Quality = 0;
            swapDesc.BufferUsage = UsageOption.RenderTargetOutput;
            swapDesc.BufferCount = 1;
            swapDesc.OutputWindowHandle = host.Handle;
            swapDesc.Windowed = true;

            swapChain = dxgiFactory.CreateSwapChain(
                device, swapDesc);

            // Create rasterizer state object
            RasterizerDescription rsDesc = new RasterizerDescription();
            rsDesc.AntialiasedLineEnable = false;
            rsDesc.CullMode = CullMode.None;
            rsDesc.DepthBias = 0;
            rsDesc.DepthBiasClamp = 0;
            rsDesc.DepthClipEnable = true;
            rsDesc.FillMode = D3D10.FillMode.Solid;
            rsDesc.FrontCounterClockwise = false; // Must be FALSE for 10on9
            rsDesc.MultisampleEnable = false;
            rsDesc.ScissorEnable = false;
            rsDesc.SlopeScaledDepthBias = 0;

            rasterizerState = device.CreateRasterizerState(
                rsDesc);

            device.RS.SetState(
                rasterizerState
                );

            // If we don't have a D2D render target, need to create all of the resources
            // required to render to one here.
            // Ensure that nobody is holding onto one of the old resources
            device.OM.SetRenderTargets(new RenderTargetView[] {null});

            InitializeDepthStencil(width, height);

            // Create views on the RT buffers and set them on the device
            RenderTargetViewDescription renderDesc = new RenderTargetViewDescription();
            renderDesc.Format = Format.R8G8B8A8_UNORM;
            renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D;
            renderDesc.Texture2D.MipSlice = 0;

            using (D3DResource spBackBufferResource = swapChain.GetBuffer<D3DResource>(0))
            {
                renderTargetView = device.CreateRenderTargetView(
                    spBackBufferResource,
                    renderDesc);
            }

            device.OM.SetRenderTargets(new RenderTargetView[] {renderTargetView}, depthStencilView);

            SetViewport(width, height);


            // Create a D2D render target which can draw into the surface in the swap chain
            RenderTargetProperties props =
                new RenderTargetProperties(
                    RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
                    96, 96, RenderTargetUsage.None, FeatureLevel.Default);

            // Allocate a offscreen D3D surface for D2D to render our 2D content into
            Texture2DDescription tex2DDescription;
            tex2DDescription.ArraySize = 1;
            tex2DDescription.BindFlags = BindFlag.RenderTarget | BindFlag.ShaderResource;
            tex2DDescription.CpuAccessFlags = CpuAccessFlag.Unspecified;
            tex2DDescription.Format = Format.R8G8B8A8_UNORM;
            tex2DDescription.Height = 4096;
            tex2DDescription.Width = 512;
            tex2DDescription.MipLevels = 1;
            tex2DDescription.MiscFlags = 0;
            tex2DDescription.SampleDescription.Count = 1;
            tex2DDescription.SampleDescription.Quality = 0;
            tex2DDescription.Usage = Usage.Default;

            offscreenTexture = device.CreateTexture2D(tex2DDescription);

            using (Surface dxgiSurface = offscreenTexture.GetDXGISurface())
            {
                // Create a D2D render target which can draw into our offscreen D3D surface
                renderTarget = d2DFactory.CreateDxgiSurfaceRenderTarget(
                    dxgiSurface,
                    props);
            }

            PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8_UNORM, AlphaMode.Premultiplied);

            opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None,
                                                                            alphaOnlyFormat);

            // Load pixel shader
            // Open precompiled vertex shader
            // This file was compiled using DirectX's SDK Shader compilation tool: 
            // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx
            shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo");

            // Obtain the technique
            technique = shader.GetTechniqueByName("Render");

            // Obtain the variables
            worldMatrixVariable = shader.GetVariableByName("World").AsMatrix();
            viewMatrixVariable = shader.GetVariableByName("View").AsMatrix();
            projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix();
            diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource();

            // Create the input layout
            PassDescription passDesc = new PassDescription();
            passDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                inputLayoutDescriptions,
                passDesc.InputAssemblerInputSignature,
                passDesc.InputAssemblerInputSignatureSize
                );

            // Set the input layout
            device.IA.SetInputLayout(
                vertexLayout
                );

            IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance));
            Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true);

            BufferDescription bd = new BufferDescription();
            bd.Usage = Usage.Default;
            bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.VerticesInstance);
            bd.BindFlags = BindFlag.VertexBuffer;
            bd.CpuAccessFlags = CpuAccessFlag.Unspecified;
            bd.MiscFlags = ResourceMiscFlag.Undefined;

            SubresourceData InitData = new SubresourceData()
                                           {
                                               SysMem = verticesDataPtr
                                           };


            vertexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(verticesDataPtr);

            // Set vertex buffer
            uint stride = (uint) Marshal.SizeOf(typeof (SimpleVertex));
            uint offset = 0;

            device.IA.SetVertexBuffers(
                0,
                new D3DBuffer[] {vertexBuffer},
                new uint[] {stride},
                new uint[] {offset}
                );

            IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance));
            Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true);

            bd.Usage = Usage.Default;
            bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.IndicesInstance);
            bd.BindFlags = BindFlag.IndexBuffer;
            bd.CpuAccessFlags = 0;
            bd.MiscFlags = 0;

            InitData.SysMem = indicesDataPtr;

            facesIndexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(indicesDataPtr);

            // Set primitive topology
            device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList);

            // Convert the D2D texture into a Shader Resource View
            textureResourceView = device.CreateShaderResourceView(
                offscreenTexture);

            // Initialize the world matrices
            worldMatrix = Matrix4x4F.Identity;

            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f);
            Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f);
            Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = Camera.MatrixPerspectiveFovLH(
                (float) Math.PI*0.1f,
                width/(float) height,
                0.1f,
                100.0f);

            // Update Variables that never change
            viewMatrixVariable.Matrix = viewMatrix;

            projectionMarixVariable.Matrix = projectionMatrix;

            GradientStop[] gradientStops =
                {
                    new GradientStop(0.0f, new ColorF(Colors.Yellow)),
                    new GradientStop(1.0f, new ColorF(Colors.Black))
                };

            GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection(
                gradientStops,
                Gamma.Gamma_22,
                ExtendMode.Clamp);

            // Create a linear gradient brush for text
            textBrush = renderTarget.CreateLinearGradientBrush(
                new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)),
                spGradientStopCollection
                );
        }
Пример #27
0
 protected override void OnResize(EventArgs e)
 {
     lock (renderSyncObject)
     {
         if (RenderTarget != null)
         {
             // Resize the render targrt to the actual host size
             var size = new SizeU((uint)ClientSize.Width, (uint)ClientSize.Height);
             if (hwndRenderTarget != null)
                 hwndRenderTarget.Resize(size); //need to resize hwndRenderTarget to make its size same as the window's size
             if (renderMode == RenderModes.BitmapRenderTargetOnPaint)
             {
                 bitmapRenderTarget.Dispose();
                 bitmapRenderTarget = dcRenderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.GdiCompatible, new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                 bitmap = null; //the bitmap created in dc render target can't be used in hwnd render target
                 foreach (var shape in drawingShapes)
                 {
                     shape.Bitmap = Bitmap;
                     shape.RenderTarget = RenderTarget;
                 }
                 RefreshAll();
             }
             else if (renderMode == RenderModes.BitmapRenderTargetRealTime)
             {
                 Debug.Assert(hwndRenderTarget != null);//this should never be null considering the above
                 bitmapRenderTarget.Dispose();
                 bitmapRenderTarget = hwndRenderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.GdiCompatible, new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                 bitmap = null; //the bitmap created in dc render target can't be used in hwnd render target
                 foreach (var shape in drawingShapes)
                 {
                     shape.Bitmap = Bitmap;
                     shape.RenderTarget = RenderTarget;
                 }
                 RefreshAll();
             }
         }
     }
     base.OnResize(e);
 }
Пример #28
0
        public static BitmapBrush makeBitmapBrush(RenderTarget renderTarget, string imgName, bool blankImage = false)
        {
            string imageSrc = Program.spriteFileDir + imgName;

            if (blankImage)
            {
                var pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied,
                    Format    = Format.B8G8R8A8_UNorm
                };

                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, pf);
                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            if (File.Exists(imageSrc))
            {
                ImagingFactory   imagingFactory = new ImagingFactory();
                NativeFileStream fileStream     = new NativeFileStream(imageSrc,
                                                                       NativeFileMode.Open, NativeFileAccess.Read);
                BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand);

                BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

                FormatConverter converter = new FormatConverter(imagingFactory);
                converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

                Bitmap bitmap = Bitmap.FromWicBitmap(renderTarget, converter);

                Utilities.Dispose(ref bitmapDecoder);
                Utilities.Dispose(ref fileStream);
                Utilities.Dispose(ref imagingFactory);
                Utilities.Dispose(ref converter);

                return(new BitmapBrush(renderTarget, bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            else
            {
                Console.WriteLine("{0} missing", imageSrc);

                var pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied,
                    Format    = Format.B8G8R8A8_UNorm
                };
                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, new Size2F(30f, 30f), new Size2(1, 1), pf);

                pallete.BeginDraw();
                pallete.Clear(Color.Purple);
                pallete.EndDraw();

                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
        }
Пример #29
0
 public D2DRenderTargetBitmapImpl(BitmapRenderTarget renderTarget)
     : base(renderTarget.Bitmap)
 {
     _renderTarget = renderTarget;
 }
Пример #30
0
        /// <summary>
        /// Creates a Direct2D brush wrapper for a Avalonia brush.
        /// </summary>
        /// <param name="brush">The avalonia brush.</param>
        /// <param name="destinationSize">The size of the brush's target area.</param>
        /// <returns>The Direct2D brush wrapper.</returns>
        public BrushImpl CreateBrush(IBrush brush, Size destinationSize)
        {
            var solidColorBrush     = brush as ISolidColorBrush;
            var linearGradientBrush = brush as ILinearGradientBrush;
            var radialGradientBrush = brush as IRadialGradientBrush;
            var imageBrush          = brush as IImageBrush;
            var visualBrush         = brush as IVisualBrush;

            if (solidColorBrush != null)
            {
                return(new SolidColorBrushImpl(solidColorBrush, _renderTarget));
            }
            else if (linearGradientBrush != null)
            {
                return(new LinearGradientBrushImpl(linearGradientBrush, _renderTarget, destinationSize));
            }
            else if (radialGradientBrush != null)
            {
                return(new RadialGradientBrushImpl(radialGradientBrush, _renderTarget, destinationSize));
            }
            else if (imageBrush != null)
            {
                return(new ImageBrushImpl(
                           imageBrush,
                           _renderTarget,
                           (BitmapImpl)imageBrush.Source.PlatformImpl,
                           destinationSize));
            }
            else if (visualBrush != null)
            {
                if (_visualBrushRenderer != null)
                {
                    var intermediateSize = _visualBrushRenderer.GetRenderTargetSize(visualBrush);

                    if (intermediateSize.Width >= 1 && intermediateSize.Height >= 1)
                    {
                        using (var intermediate = new BitmapRenderTarget(
                                   _renderTarget,
                                   CompatibleRenderTargetOptions.None,
                                   intermediateSize.ToSharpDX()))
                        {
                            using (var ctx = new RenderTarget(intermediate).CreateDrawingContext(_visualBrushRenderer))
                            {
                                intermediate.Clear(null);
                                _visualBrushRenderer.RenderVisualBrush(ctx, visualBrush);
                            }

                            return(new ImageBrushImpl(
                                       visualBrush,
                                       _renderTarget,
                                       new D2DBitmapImpl(_imagingFactory, intermediate.Bitmap),
                                       destinationSize));
                        }
                    }
                }
                else
                {
                    throw new NotSupportedException("No IVisualBrushRenderer was supplied to DrawingContextImpl.");
                }
            }

            return(new SolidColorBrushImpl(null, _renderTarget));
        }
Пример #31
0
 internal D2dBitmapGraphics(BitmapRenderTarget renderTarget)
     : base(renderTarget)
 {
 }
Пример #32
0
        private void SetRenderMode(RenderModes rm)
        {
            lock (renderSyncObject)
            {
                renderMode = rm;
                //if (!IsInitialized && !isInitializing)
                //    return;

                //clean up objects that will be invalid after RenderTarget change
                if (dcRenderTarget != null)
                {
                    dcRenderTarget.Dispose();
                    dcRenderTarget = null;
                }
                if (hwndRenderTarget != null)
                {
                    hwndRenderTarget.Dispose();
                    hwndRenderTarget = null;
                }
                if (bitmapRenderTarget != null)
                {
                    bitmapRenderTarget.Dispose();
                    bitmapRenderTarget = null;
                }
                //bitmap = null; //the bitmap created in dc render target can't be used in hwnd render target

                // Create the screen render target
                RECT cRect;
                User32.GetClientRect(fWindowHandle, out cRect);
                
                var size = new SizeU((uint)cRect.Width, (uint)cRect.Height);
                PixelFormat pFormat = new PixelFormat(Format.B8G8R8A8_UNORM, AlphaMode.Ignore);
                var props = new RenderTargetProperties {PixelFormat = pFormat, Usage = RenderTargetUsage.GdiCompatible};

                //if (renderMode == RenderModes.DCRenderTarget || renderMode == RenderModes.BitmapRenderTargetOnPaint)
                //{
                //    dcRenderTarget = d2DFactory.CreateDCRenderTarget(props);
                //    if (renderMode == RenderModes.BitmapRenderTargetOnPaint)
                //    {
                //        bitmapRenderTarget =
                //            dcRenderTarget.CreateCompatibleRenderTarget(
                //            CompatibleRenderTargetOptions.GdiCompatible,
                //            new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                //    }
                //    render = null;
                //}
                //else
                {
                    HwndRenderTargetProperties hProps = new HwndRenderTargetProperties(fWindowHandle, size, PresentOptions.RetainContents);
                    hwndRenderTarget = d2DFactory.CreateHwndRenderTarget(props,  hProps);
                    
                    //if (renderMode == RenderModes.BitmapRenderTargetRealTime)
                    //{
                    //    bitmapRenderTarget =
                    //        hwndRenderTarget.CreateCompatibleRenderTarget(
                    //        CompatibleRenderTargetOptions.GdiCompatible,
                    //        new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                    //}
                    //render = RenderSceneInBackground;
                }
            }
        }
 internal D2dBitmapGraphics(D2dGraphics owner, BitmapRenderTarget renderTarget)
     : base(renderTarget)
 {
     m_owner = owner;
 }
Пример #34
0
 protected BufferSence(IdentityObject parent, string id = "", Control control = null)
     : base(parent, id, control)
 {
     BufferBitmapRenderTarget = new BitmapRenderTarget(SurfaceRenderTarget,
                                                       CompatibleRenderTargetOptions.None);
 }
Пример #35
0
        private void SetRenderMode(RenderModes rm)
        {
            lock (renderSyncObject)
            {
                renderMode = rm;
                if (!IsInitialized && !isInitializing)
                    return;

                //clean up objects that will be invalid after RenderTarget change
                if (dcRenderTarget != null)
                {
                    dcRenderTarget.Dispose();
                    dcRenderTarget = null;
                }
                if (hwndRenderTarget != null)
                {
                    hwndRenderTarget.Dispose();
                    hwndRenderTarget = null;
                }
                if (bitmapRenderTarget != null)
                {
                    bitmapRenderTarget.Dispose();
                    bitmapRenderTarget = null;
                }
                peelings.Clear();
                bitmap = null; //the bitmap created in dc render target can't be used in hwnd render target

                // Create the screen render target
                var size = new SizeU((uint)ClientSize.Width, (uint)ClientSize.Height);
                var props = new RenderTargetProperties
                {
                    PixelFormat = new PixelFormat(
                        Format.B8G8R8A8UNorm,
                        AlphaMode.Ignore),
                    Usage = RenderTargetUsages.GdiCompatible
                };

                if (renderMode == RenderModes.DCRenderTarget || renderMode == RenderModes.BitmapRenderTargetOnPaint)
                {
                    dcRenderTarget = d2DFactory.CreateDCRenderTarget(props);
                    if (renderMode == RenderModes.BitmapRenderTargetOnPaint)
                    {
                        bitmapRenderTarget =
                            dcRenderTarget.CreateCompatibleRenderTarget(
                            CompatibleRenderTargetOptions.GdiCompatible,
                            new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                    }
                    render = null;
                }
                else
                {
                    hwndRenderTarget = d2DFactory.CreateHwndRenderTarget(
                        props,
                        new HwndRenderTargetProperties(Handle, size, Microsoft.WindowsAPICodePack.DirectX.Direct2D1.PresentOptions.RetainContents));
                    if (renderMode == RenderModes.BitmapRenderTargetRealTime)
                    {
                        bitmapRenderTarget =
                            hwndRenderTarget.CreateCompatibleRenderTarget(
                            CompatibleRenderTargetOptions.GdiCompatible,
                            new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                    }
                    render = RenderSceneInBackground;
                }

                //move all shapes to new rendertarget and refresh
                foreach (var shape in drawingShapes)
                {
                    shape.Bitmap = Bitmap;
                    shape.RenderTarget = RenderTarget;
                }
                RefreshAll();
            }
        }
Пример #36
0
        public BitmapBrush makeBitmapBrush(string imgName, RenderTarget renderTarget, bool blankImage = false)
        {
            //TODO : 여기 바꿔라!
            string imageSrc = "";

            if (blankImage)
            {
                SharpDX.Direct2D1.PixelFormat pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = D3DHandler.ALPHA_MODE,
                    Format    = D3DHandler.RENDER_FORMAT
                };

                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, pf);
                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            if (resourceCore.getFile(imgName, out ResFile resFile))
            {
                ImagingFactory imagingFactory = new ImagingFactory();

                /*NativeFileStream fileStream = new NativeFileStream(imageSrc,
                 *  NativeFileMode.Open, NativeFileAccess.Read);*/
                MemoryStream  ms            = new MemoryStream(resFile.rawData);
                BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, ms, DecodeOptions.CacheOnDemand);

                BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

                FormatConverter converter = new FormatConverter(imagingFactory);
                converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

                Bitmap bitmap = Bitmap.FromWicBitmap(renderTarget, converter);

                Utilities.Dispose(ref bitmapDecoder);
                Utilities.Dispose(ref imagingFactory);
                Utilities.Dispose(ref converter);

                return(new BitmapBrush(renderTarget, bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            else
            {
                Console.WriteLine("{0} missing", imageSrc);

                SharpDX.Direct2D1.PixelFormat pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = D3DHandler.ALPHA_MODE,
                    Format    = D3DHandler.RENDER_FORMAT
                };
                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, new Size2F(30f, 30f), new Size2(1, 1), pf);

                pallete.BeginDraw();
                pallete.Clear(Color.Purple);
                pallete.EndDraw();

                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
        }