Ejemplo n.º 1
0
        public static D2D.Bitmap LoadD2DBitmapFromBytes(this D2D.RenderTarget renderTarget, byte[] data)
        {
            using var stream = new MemoryStream(data);
            stream.Seek(0, SeekOrigin.Begin);
            // Loads from file using System.Drawing.Image
            using var bitmap = (Drawing2.Bitmap)Image.FromStream(stream);
            var sourceArea       = new Drawing2.Rectangle(0, 0, bitmap.Width, bitmap.Height);
            var bitmapProperties = new D2D.BitmapProperties(new D2D.PixelFormat(DXGI.Format.R8G8B8A8_Typeless, D2D.AlphaMode.Premultiplied));
            var size             = new Drawing2.Size(bitmap.Width, bitmap.Height);
            // Transform pixels from BGRA to RGBA
            int stride = bitmap.Width * sizeof(int);

            using var tempStream = new DataStream(bitmap.Height * stride, true, true);
            // Lock System.Drawing.Bitmap
            var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, Drawing2.Imaging.PixelFormat.Format32bppPArgb);

            // Convert all pixels
            for (int y = 0; y < bitmap.Height; y++)
            {
                int offset = bitmapData.Stride * y;
                for (int x = 0; x < bitmap.Width; x++)
                {
                    // Not optimized
                    byte B    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte G    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte R    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte A    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    int  rgba = R | (G << 8) | (B << 16) | (A << 24);
                    tempStream.Write(rgba);
                }
            }
            bitmap.UnlockBits(bitmapData);
            tempStream.Position = 0;
            return(new D2D.Bitmap(renderTarget, new Size2(size.Width, size.Height), tempStream, stride, bitmapProperties));
        }
Ejemplo n.º 2
0
        private static Direct2D.Bitmap LoadFromFile(string filename, Direct2D.RenderTarget Direct2DTarget)
        {
            var factory = new WIC.ImagingFactory();
            // Decode image
            var decoder     = new WIC.BitmapDecoder(factory, filename, WIC.DecodeOptions.CacheOnLoad);
            var frameDecode = decoder.GetFrame(0);
            var source      = new WIC.BitmapSource(frameDecode.NativePointer);
            var fc          = new WIC.FormatConverter(factory);

            fc.Initialize(
                source,
                SharpDX.WIC.PixelFormat.Format32bppPBGRA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0f,
                SharpDX.WIC.BitmapPaletteType.Custom
                );
            double dpX = 96.0f;
            double dpY = 96.0f;

            fc.GetResolution(out dpX, out dpY);
            Direct2D.BitmapProperties props = new Direct2D.BitmapProperties(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
            WIC.Bitmap bmp = new WIC.Bitmap(factory, fc, WIC.BitmapCreateCacheOption.CacheOnLoad);
            // Формируем изображения
            var Direct2DBitmap = SharpDX.Direct2D1.Bitmap.FromWicBitmap(Direct2DTarget, fc, props);

            // Cleanup
            factory.Dispose();
            decoder.Dispose();
            source.Dispose();
            fc.Dispose();
            return(Direct2DBitmap);
        }
Ejemplo n.º 3
0
 public BitmapImage(int width, int height, BitmapProperties properties)
 {
     mWidth = width;
     mHeight = height;
     mProperties = properties;
     mData = new DataStream(width * height * 4, true, true);
 }
Ejemplo n.º 4
0
        private SharpDX.Direct2D1.Bitmap SDXBitmapFromSysBitmap(WindowRenderTarget device, System.Drawing.Bitmap bitmap)
        {
            var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
            var bitmapProperties = new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
            var size = new Size2(bitmap.Width, bitmap.Height);

            // Transform pixels from BGRA to RGBA
            int stride = bitmap.Width * sizeof(int);
            using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
            {
                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                // Convert all pixels 
                for (int y = 0; y < bitmap.Height; y++)
                {
                    int offset = bitmapData.Stride * y;
                    for (int x = 0; x < bitmap.Width; x++)
                    {
                        // Not optimized 
                        byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = R | (G << 8) | (B << 16) | (A << 24);
                        tempStream.Write(rgba);
                    }

                }
                bitmap.UnlockBits(bitmapData);
                tempStream.Position = 0;

                return new SharpDX.Direct2D1.Bitmap(device, size, tempStream, stride, bitmapProperties);
            }
        }
Ejemplo n.º 5
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
 
            // Direct2D
            var renderTargetProperties = new RenderTargetProperties()
            {
                PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore)
            };
            var hwndRenderTargetProperties = new HwndRenderTargetProperties()
            {
                Hwnd = this.Handle,
                PixelSize = new Size2(bounds.Width, bounds.Height),
                PresentOptions = PresentOptions.Immediately,
            };
            renderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties);

            var bitmapProperties = new BitmapProperties()
            {
                PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore)
            };
            bitmap = new SharpDX.Direct2D1.Bitmap(renderTarget, new Size2(bounds.Width, bounds.Height), bitmapProperties);

            textFormat = new TextFormat(directWriteFacrtory, "Arial", FontWeight.Normal, SharpDX.DirectWrite.FontStyle.Normal, 96.0f);
            textFormat.ParagraphAlignment = ParagraphAlignment.Center;
            textFormat.TextAlignment = TextAlignment.Center;

            solidColorBrush = new SolidColorBrush(renderTarget, Color4.White);
        }
Ejemplo n.º 6
0
        public static D2D.Bitmap LoadBitmap(D2D.RenderTarget renderTarget, string imagePath)
        {
            FileInfo fi = new FileInfo(imagePath);

            if (!fi.Exists)
            {
                var    ext    = fi.Extension;
                string newExt = "";
                if (ext == ".jpg")
                {
                    newExt = ".png";
                }
                else if (ext == ".png")
                {
                    newExt = ".jpg";
                }
                string newName = fi.FullName.Remove(fi.FullName.Length - 4, 4);
                imagePath = newName + newExt;
            }

            D2D.Bitmap bmp;
            if (Cached.ContainsKey(imagePath))
            {
                bmp = Cached[imagePath];
                if (bmp.IsDisposed)
                {
                    Cached.TryRemove(imagePath, out _);
                }
                else
                {
                    return(bmp);
                }
            }

            WIC.ImagingFactory    imagingFactory = new WIC.ImagingFactory();
            DXIO.NativeFileStream fileStream     = new DXIO.NativeFileStream(imagePath,
                                                                             DXIO.NativeFileMode.Open, DXIO.NativeFileAccess.Read);

            WIC.BitmapDecoder bitmapDecoder =
                new WIC.BitmapDecoder(imagingFactory, fileStream, WIC.DecodeOptions.CacheOnDemand);
            WIC.BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

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

            var bitmapProperties =
                new D2D.BitmapProperties(new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied));

            //Size2 size = new Size2(frame.Size.Width, frame.Size.Height);

            bmp = D2D.Bitmap.FromWicBitmap(renderTarget, converter, bitmapProperties);

            if (!Cached.ContainsKey(imagePath))
            {
                Cached.TryAdd(imagePath, bmp);
                //LogUtil.LogInfo("Created cache.");
            }

            return(bmp);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new DirectXTexture class.
        /// </summary>
        /// <param name="bmp">The Bitmap.</param>
        internal DirectXTexture(System.Drawing.Bitmap bmp)
        {
            RawBitmap = (System.Drawing.Bitmap) bmp.Clone();
            _width = bmp.Width;
            _height = bmp.Height;
            var sourceArea = new Rectangle(0, 0, bmp.Width, bmp.Height);
            var bitmapProperties = new BitmapProperties(
                new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96);
            var size = new Size2(bmp.Width, bmp.Height);

            int stride = bmp.Width*sizeof (int);
            using (var tempStream = new DataStream(bmp.Height*stride, true, true))
            {
                BitmapData bitmapData = bmp.LockBits(sourceArea, ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                for (int y = 0; y < bmp.Height; y++)
                {
                    int offset = bitmapData.Stride*y;
                    for (int x = 0; x < bmp.Width; x++)
                    {
                        byte b = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte g = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte r = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte a = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = r | (g << 8) | (b << 16) | (a << 24);
                        tempStream.Write(rgba);
                    }
                }
                bmp.UnlockBits(bitmapData);
                tempStream.Position = 0;
                _bmp = new Bitmap(DirectXHelper.RenderTarget, size, tempStream, stride, bitmapProperties);
            }
        }
Ejemplo n.º 8
0
        private void CreateResources()
        {
            this.backBuffer           = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(this.swapChain, 0);
            this.backBuffer.DebugName = "BackBuffer";

            using (var surface = this.backBuffer.QueryInterface <DXGI.Surface>())
            {
                var properties = new D2D.BitmapProperties(
                    new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                    this.factory2d.DesktopDpi.Width,
                    this.factory2d.DesktopDpi.Height);

                this.backBitmap = new D2D.Bitmap(this.deviceContext2D, surface, properties);

                if (this.renderBitmap != null)
                {
                    this.backBitmap.CopyFromBitmap(this.renderBitmap);
                }
            }

            if (this.renderBitmap != null)
            {
                this.renderBitmap.Dispose();
                this.renderBuffer.Dispose();
            }

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

            var pixelSize = Helpers.GetPixelSize(this.backBitmap.Size, this.factory2d.DesktopDpi);

            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,
            };

            this.renderBuffer = new D3D11.Texture2D(this.device, desc);
            using (var surface = this.renderBuffer.QueryInterface <DXGI.Surface>())
            {
                this.renderBitmap = new D2D.Bitmap1(this.deviceContext2D, surface, p);
            }

            this.renderBitmap.CopyFromBitmap(this.backBitmap);
        }
Ejemplo n.º 9
0
        public void ConstructRenderAndResource(double width, double height)
        {
            float dpiX, dpiY;

            this.GetDpi(out dpiX, out dpiY);
            D2D.RenderTargetProperties prop = new D2D.RenderTargetProperties(
                D2D.RenderTargetType.Default,
                new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                dpiX,
                dpiY,
                D2D.RenderTargetUsage.None,
                D2D.FeatureLevel.Level_DEFAULT);

            D3D11.Texture2DDescription desc = new D3D11.Texture2DDescription();
            desc.Width             = (int)width;
            desc.Height            = (int)height;
            desc.MipLevels         = 1;
            desc.ArraySize         = 1;
            desc.Format            = DXGI.Format.B8G8R8A8_UNorm;
            desc.SampleDescription = new DXGI.SampleDescription(1, 0);
            desc.Usage             = D3D11.ResourceUsage.Default;
            desc.BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource;
            desc.CpuAccessFlags    = D3D11.CpuAccessFlags.None;
            desc.OptionFlags       = D3D11.ResourceOptionFlags.Shared;
            this.d3d11Texture      = new D3D11.Texture2D(this.device, desc);

            this.surface = this.d3d11Texture.QueryInterface <DXGI.Surface>();

            DXGI.Resource resource = this.d3d11Texture.QueryInterface <DXGI.Resource>();
            IntPtr        handel   = resource.SharedHandle;

            D3D9.Texture texture = new D3D9.Texture(
                this.device9,
                this.d3d11Texture.Description.Width,
                this.d3d11Texture.Description.Height,
                1,
                D3D9.Usage.RenderTarget,
                D3D9.Format.A8R8G8B8,
                D3D9.Pool.Default,
                ref handel);
            this.surface9 = texture.GetSurfaceLevel(0);
            resource.Dispose();
            texture.Dispose();

            D2D.BitmapProperties bmpProp = new D2D.BitmapProperties();
            bmpProp.DpiX        = dpiX;
            bmpProp.DpiY        = dpiY;
            bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            this.bmpd2d         = new D2D.Bitmap(this.render, this.surface, bmpProp);
            this.cachedBitMap   = new D2D.Bitmap(this.render, new Size2((int)width, (int)height), bmpProp);
            this.hasCache       = false;

            this.render.Target = this.bmpd2d;

            this.renderSize = new Size(width, height);
        }
Ejemplo n.º 10
0
        public void ConstructRenderAndResource(double width, double height)
        {
            float dpiX, dpiY;

            this.GetDpi(out dpiX, out dpiY);

            var desc = new DXGI.SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new DXGI.ModeDescription((int)width, (int)height,
                                                           new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = TextBox.Handle,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                SwapEffect        = DXGI.SwapEffect.Discard,
                Usage             = DXGI.Usage.RenderTargetOutput
            };

            this.swapchain = new DXGI.SwapChain(factory_dxgi, device, desc);

            this.device2d = new D2D.Device1(this._factory.D2DFactory, device_dxgi);

            this.render = new D2D.DeviceContext1(this.device2d, D2D.DeviceContextOptions.None);

            D2D.BitmapProperties bmpProp = new D2D.BitmapProperties();
            bmpProp.DpiX        = dpiX;
            bmpProp.DpiY        = dpiY;
            bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            this.bmp_d2d        = new D2D.Bitmap(this.render, DXGI.Surface.FromSwapChain(swapchain, 0), bmpProp);
            this.cachedBitMap   = new D2D.Bitmap(this.render, new SharpDX.Size2((int)width, (int)height), bmpProp);
            this.hasCache       = false;

            this.render.Target = this.bmp_d2d;

            this.textRender = new CustomTextRenderer(this._factory, this.Foreground);

            this.renderSize = new Size(width, height);

            //デフォルト値を反映させる
            this.Foreground        = ToColor4(this.TextBox.Foreground);
            this.Background        = ToColor4(this.TextBox.Background);
            this.ControlChar       = ToColor4(this.TextBox.ControlChar);
            this.Url               = ToColor4(this.TextBox.Url);
            this.Keyword1          = ToColor4(this.TextBox.Keyword1);
            this.Keyword2          = ToColor4(this.TextBox.Keyword2);
            this.Literal           = ToColor4(this.TextBox.Literal);
            this.Comment           = ToColor4(this.TextBox.Comment);
            this.Hilight           = ToColor4(this.TextBox.Hilight);
            this.LineMarker        = ToColor4(this.TextBox.LineMarker);
            this.InsertCaret       = ToColor4(this.TextBox.InsertCaret);
            this.OverwriteCaret    = ToColor4(this.TextBox.OverwriteCaret);
            this.UpdateArea        = ToColor4(this.TextBox.UpdateArea);
            this.HilightForeground = ToColor4(this.TextBox.HilightForeground);
        }
Ejemplo n.º 11
0
    public SharpDX.Direct2D1.Bitmap GetD2DBitmap(SharpDX.Direct2D1.DeviceContext dc, ImagingFactory factory)
    {
        using (var fc = new FormatConverter(factory))
        {
            fc.Initialize(WICBitmapSource, SharpDX.WIC.PixelFormat.Format32bppPBGRA,
                          SharpDX.WIC.BitmapDitherType.None, null, 0.0f,
                          SharpDX.WIC.BitmapPaletteType.Custom);

            var bmpProps = new SharpDX.Direct2D1.BitmapProperties(dc.PixelFormat, dc.Factory.DesktopDpi.Width, dc.Factory.DesktopDpi.Height);

            return(SharpDX.Direct2D1.Bitmap1.FromWicBitmap(dc, fc, bmpProps));
        }
    }
Ejemplo n.º 12
0
        public static D2D.Bitmap LoadBitmap(this D2D.RenderTarget renderTarget, string imagePath)
        {
            lock (LockObj)
            {
                Sw.Start();
                D2D.Bitmap bmp;
                if (Cached.ContainsKey(imagePath))
                {
                    Cached[imagePath].Time = DateTime.Now;
                    bmp = Cached[imagePath].Bitmap;

                    Sw.Stop();
                    LogUtil.LogInfo($"Cache: {Sw.ElapsedMilliseconds}ms.");
                }
                else
                {
                    WIC.ImagingFactory    imagingFactory = new WIC.ImagingFactory();
                    DXIO.NativeFileStream fileStream     = new DXIO.NativeFileStream(imagePath,
                                                                                     DXIO.NativeFileMode.Open, DXIO.NativeFileAccess.Read);

                    WIC.BitmapDecoder     bitmapDecoder = new WIC.BitmapDecoder(imagingFactory, fileStream, WIC.DecodeOptions.CacheOnDemand);
                    WIC.BitmapFrameDecode frame         = bitmapDecoder.GetFrame(0);

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

                    var bitmapProperties =
                        new D2D.BitmapProperties(new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied));
                    //Size2 size = new Size2(frame.Size.Width, frame.Size.Height);

                    bmp = D2D.Bitmap.FromWicBitmap(renderTarget, converter, bitmapProperties);

                    Sw.Stop();
                    LogUtil.LogInfo($"Load: {Sw.ElapsedMilliseconds}ms.");
                }

                if (!Cached.ContainsKey(imagePath) && Sw.ElapsedMilliseconds > 50)
                {
                    Cached.TryAdd(imagePath, new CacheInfo(DateTime.Now, bmp));
                    LogUtil.LogInfo("Created cache.");
                    if (Cached.Count > 50)
                    {
                        Cached.TryRemove(Cached.OrderByDescending(c => c.Value.Time).First().Key, out _);
                        LogUtil.LogInfo("Removed unused cache.");
                    }
                }
                Sw.Reset();

                return(bmp);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Copy a rect of bitmap into a new one.
        /// </summary>
        /// <param name="renderTarget">The render target, e.g. device context.</param>
        /// <param name="bitmap">Original bitmap.</param>
        /// <param name="rect">The area to be copied.</param>
        /// <param name="dpi">Dpi.</param>
        /// <returns>The new copied bitmap.</returns>
        public static D2D.Bitmap CopyBitmap(D2D.RenderTarget renderTarget, D2D.Bitmap bitmap, RawRectangleF rect, Size2F dpi)
        {
            var bitmapProperties = new D2D.BitmapProperties(
                bitmap.PixelFormat,
                dpi.Width,
                dpi.Height);

            var pixelRect = GetRawRectangle(rect, dpi);
            var pixelSize = new Size2(pixelRect.Right - pixelRect.Left, pixelRect.Bottom - pixelRect.Top);
            var newBitmap = new D2D.Bitmap(renderTarget, pixelSize, bitmapProperties);

            newBitmap.CopyFromBitmap(bitmap, new RawPoint(0, 0), pixelRect);
            return(newBitmap);
        }
Ejemplo n.º 14
0
        public static D2D.Bitmap LoadBitmap(this D2D.RenderTarget renderTarget, GdiP.Bitmap bitmap)
        {
            lock (LockObj)
            {
                Sw.Restart();
                try
                {
                    var sourceArea       = new GdiP.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                    var bitmapProperties =
                        new D2D.BitmapProperties(new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied));
                    Size2 size = new Size2(bitmap.Width, bitmap.Height);

                    // Transform pixels from BGRA to RGBA
                    int stride = bitmap.Width * sizeof(int);
                    using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
                    {
                        // Lock System.Drawing.Bitmap
                        var bitmapData = bitmap.LockBits(sourceArea, GdiPimaging.ImageLockMode.ReadOnly,
                                                         GdiPimaging.PixelFormat.Format32bppPArgb);

                        // Convert all pixels
                        for (int y = 0; y < bitmap.Height; y++)
                        {
                            int offset = bitmapData.Stride * y;
                            for (int x = 0; x < bitmap.Width; x++)
                            {
                                // Not optimized
                                byte b    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte g    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte r    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte a    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                int  rgba = r | (g << 8) | (b << 16) | (a << 24);
                                tempStream.Write(rgba);
                            }
                        }

                        bitmap.UnlockBits(bitmapData);
                        tempStream.Position = 0;

                        return(new D2D.Bitmap(renderTarget, size, tempStream, stride, bitmapProperties));
                    }
                }
                finally
                {
                    Sw.Stop();
                    //LogUtil.LogInfo($"[FromGdi] Load: {Sw.ElapsedMilliseconds}ms.");
                }
            }
        }
Ejemplo n.º 15
0
        public void UpdateMap(string mapName)
        {
            mWdlFile = new IO.Files.Terrain.WdlFile();
            try
            {
                mWdlFile.Load(mapName);
                if(mWdlFile.HasEntries == false)
                {
                    UpdateMapNoWdl(mapName);
                    return;
                }
            }
            catch(Exception)
            {
                UpdateMapNoWdl(mapName);
                return;
            }

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

            var textureData = new uint[Width * Height];
            for(var i = 0; i < 64; ++i)
            {
                for(var j = 0; j < 64; ++j)
                {
                    if (mWdlFile.HasEntry(j, i) == false)
                        continue;

                    var entry = mWdlFile.GetEntry(j, i);
                    LoadEntry(entry, textureData, ref i, ref j);
                }
            }

            var bmpProps =
                new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore));

            using (var dataStream = new DataStream(Width * Height * 4, true, true))
            {
                dataStream.WriteRange(textureData);
                dataStream.Position = 0;

                mImage = new Bitmap(InterfaceManager.Instance.Surface.RenderTarget, new Size2(Width, Height),
                    new DataPointer(dataStream.DataPointer, Width * Height * 4), Width * 4, bmpProps);
            }
        }
Ejemplo n.º 16
0
 public static D2D.Bitmap LoadD2DBitmapFromFile(this D2D.RenderTarget renderTarget, string file, float scaleX = 1, float scaleY = 1)
 {
     try
     {
         using (var bitmap = (Bitmap)Image.FromFile(file))
         {
             var g = Graphics.FromImage(bitmap);
             g.ScaleTransform(scaleX, scaleY);
             g.Flush();
             g.Save();
             g.Dispose();
             var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
             var bitmapProperties = new D2D.BitmapProperties(new D2D.PixelFormat(DXGI.Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied));
             var size             = new Size2(bitmap.Width, bitmap.Height);
             // Transform pixels from BGRA to RGBA
             int stride = bitmap.Width * sizeof(int);
             using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
             {
                 // Lock System.Drawing.Bitmap
                 var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, Drawing2.Imaging.PixelFormat.Format32bppPArgb);
                 // Convert all pixels
                 for (int y = 0; y < bitmap.Height; y++)
                 {
                     int offset = bitmapData.Stride * y;
                     for (int x = 0; x < bitmap.Width; x++)
                     {
                         // Not optimized
                         byte B    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                         byte G    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                         byte R    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                         byte A    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                         int  rgba = R | (G << 8) | (B << 16) | (A << 24);
                         tempStream.Write(rgba);
                     }
                 }
                 bitmap.UnlockBits(bitmapData);
                 tempStream.Position = 0;
                 return(new D2D.Bitmap(renderTarget, size, tempStream, stride, bitmapProperties));
             }
         }
     }
     catch (SharpDXException)
     {
         throw;
     }
 }
Ejemplo n.º 17
0
        /// <summary>
        ///     从指定的路径中加载bitmap
        /// </summary>
        /// <param name="file">路径</param>
        /// <returns>TextureId</returns>
        public int LoadBitmapFromFile(string file)
        {
            var fileName = Path.GetFileName(file);
            Debug.Assert(fileName != null, "fileName != null");
            if (bitmapNameDictionary.ContainsKey(fileName)) {
                return bitmapNameDictionary[fileName];
            }
            // Loads from file using System.Drawing.Image
            using (var bitmap = (System.Drawing.Bitmap)Image.FromFile(file)) {
                var sourceArea = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                var bitmapProperties =
                    new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                var size = new Size(bitmap.Width, bitmap.Height);

                // Transform pixels from BGRA to RGBA
                var stride = bitmap.Width * sizeof(int);
                using (var tempStream = new DataStream(bitmap.Height * stride, true, true)) {
                    // Lock System.Drawing.Bitmap
                    var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly,
                                                     System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                    // Convert all pixels
                    for (var y = 0; y < bitmap.Height; y++) {
                        var offset = bitmapData.Stride * y;
                        for (var x = 0; x < bitmap.Width; x++) {
                            // Not optimized
                            var b = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            var g = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            var r = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            var a = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            var rgba = r | (g << 8) | (b << 16) | (a << 24);
                            tempStream.Write(rgba);
                        }
                    }
                    bitmap.UnlockBits(bitmapData);
                    tempStream.Position = 0;

                    bitmapList.Add(new Bitmap(renderTarget,
                                              new Size2(size.Width, size.Height), tempStream, stride,
                                              bitmapProperties));
                    bitmapNameDictionary.Add(fileName, index);
                    return index++;
                }
            }
        }
Ejemplo n.º 18
0
        private static Bitmap BitmapToImage(RenderTarget renderTarget, System.Drawing.Bitmap bitmap)
        {
            var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties(
                new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
            var size = new Size2(bitmap.Width, bitmap.Height);

            // Transform pixels from BGRA to RGBA
            var stride = bitmap.Width * sizeof(int);

            using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
            {
                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly,
                                                 System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                // ReSharper disable TooWideLocalVariableScope
                int    r, g, b, a, rgba, offset;
                IntPtr zerothPixel;
                // ReSharper restore TooWideLocalVariableScope

                // Convert all pixels
                for (var y = 0; y < bitmap.Height; y++)
                {
                    offset = bitmapData.Stride * y;
                    for (var x = 0; x < bitmap.Width; x++)
                    {
                        zerothPixel = bitmapData.Scan0;
                        b           = Marshal.ReadByte(zerothPixel, offset++);
                        g           = Marshal.ReadByte(zerothPixel, offset++);
                        r           = Marshal.ReadByte(zerothPixel, offset++);
                        a           = Marshal.ReadByte(zerothPixel, offset++);
                        rgba        = r | (g << 8) | (b << 16) | (a << 24);
                        tempStream.Write(rgba);
                    }
                }
                bitmap.UnlockBits(bitmapData);
                tempStream.Position = 0;

                return(new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties));
            }
        }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Загрузка рисунка из ресурса
            /// </summary>
            /// <param name="resource_name">Имя ресурса</param>
            /// <returns>Рисунок Direct2D</returns>
            //---------------------------------------------------------------------------------------------------------
            public static Direct2D.Bitmap LoadFromResource(String resource_name)
            {
                Object image = null;                // Properties.Resources.ResourceManager.GetObject(resource_name);

                System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)image;

                System.Drawing.Imaging.BitmapData lock_data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                                                                              System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                Direct2D.BitmapProperties bp = new Direct2D.BitmapProperties();
                bp.DpiX        = 96;
                bp.DpiY        = 96;
                bp.PixelFormat = new Direct2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied);
                Direct2D.Bitmap bitmap_d2d = new Direct2D.Bitmap(D2DRenderTarget, new Size2(bitmap.Width, bitmap.Height), bp);
                bitmap_d2d.CopyFromMemory(lock_data.Scan0, lock_data.Stride);

                bitmap.UnlockBits(lock_data);

                return(bitmap_d2d);
            }
Ejemplo n.º 20
0
        public D2D1.Bitmap ConvertToSharpDXBitmap(D2D1.DeviceContext context, System.Drawing.Bitmap bmp)
        {
            D2D1.Bitmap Image = null;
            try
            {
                BitmapData bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);

                dataStream = new DataStream(bmpData.Scan0, bmpData.Stride * bmpData.Height, true, false);
                D2D1.BitmapProperties d2dBitmapProperties = new D2D1.BitmapProperties();
                d2dBitmapProperties.PixelFormat = D2PixelFormat;

                Image = new D2D1.Bitmap(context, new Size2(bmpData.Width, bmpData.Height), dataStream, bmpData.Stride, d2dBitmapProperties);
                dataStream.Dispose();
                bmp.UnlockBits(bmpData);
                bmp.Dispose();
            }
            catch (Exception ex)
            {
                Logger.LogFile(ex.Message, "", "ConvertToSlimDXBitmap", ex.LineNumber(), "GraphicUtilDX");
            }
            return(Image);
        }
Ejemplo n.º 21
0
        public static d2d.Bitmap LoadBitmap(d2d.RenderTarget renderTarget, gdi.Bitmap gdiBmp)
        {
            d2d.Bitmap result = null;

            //Lock the gdi resource
            BitmapData drawingBitmapData = gdiBmp.LockBits(
                new gdi.Rectangle(0, 0, gdiBmp.Width, gdiBmp.Height),
                ImageLockMode.ReadOnly, gdi.Imaging.PixelFormat.Format32bppPArgb);

            try
            {
                //Prepare loading the image from gdi resource
                DataStream dataStream = new DataStream(
                    drawingBitmapData.Scan0,
                    drawingBitmapData.Stride * drawingBitmapData.Height,
                    true, false);
                d2d.BitmapProperties properties = new d2d.BitmapProperties();
                properties.PixelFormat = new SharpDX.Direct2D1.PixelFormat(
                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    d2d.AlphaMode.Premultiplied);

                //Load the image from the gdi resource
                result = new d2d.Bitmap(
                    renderTarget,
                    new Size2(gdiBmp.Width, gdiBmp.Height),
                    dataStream, drawingBitmapData.Stride,
                    properties);

                //Unlock the gdi resource
                gdiBmp.UnlockBits(drawingBitmapData);
            }
            catch (Exception e)
            {
                gdiBmp.UnlockBits(drawingBitmapData);
                throw e;
            }

            return(result);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Loads a Direct2D Bitmap from a file using System.Drawing.Image.FromFile(...)
        /// </summary>
        /// <param name="renderTarget">The render target.</param>
        /// <param name="file">The file.</param>
        /// <returns>A D2D1 Bitmap</returns>
        public static Bitmap LoadFromFile(RenderTarget renderTarget, string file)
        {
            // Loads from file using System.Drawing.Image
            using (var bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromFile(file))
            {
                var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                var size = new Size2(bitmap.Width, bitmap.Height);

                // Transform pixels from BGRA to RGBA
                int stride = bitmap.Width * sizeof(int);
                using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
                {
                    // Lock System.Drawing.Bitmap
                    var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                    // Convert all pixels 
                    for (int y = 0; y < bitmap.Height; y++)
                    {
                        int offset = bitmapData.Stride*y;
                        for (int x = 0; x < bitmap.Width; x++)
                        {
                            // Not optimized 
                            byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            int rgba = R | (G << 8) | (B << 16) | (A << 24);
                            tempStream.Write(rgba);
                        }
                        
                    }
                    bitmap.UnlockBits(bitmapData);
                    tempStream.Position = 0;

                    return new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties);
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LogoControl"/> class.
        /// </summary>
        /// <param name="parent">The parent control.</param>
        public LogoControl(IElement parent)
            : base(parent)
        {
            var image            = Properties.Resources.neovim_logo_flat;
            var size             = new Rectangle(0, 0, image.Width, image.Height);
            var bitmapProperties = new D2D.BitmapProperties()
            {
                DpiX        = this.Factory.DesktopDpi.Width,
                DpiY        = this.Factory.DesktopDpi.Height,
                PixelFormat = new D2D.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
            };

            var bitmapData = image.LockBits(size, ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);

            this.bitmap = new D2D.Bitmap(
                this.DeviceContext,
                new Size2(image.Width, image.Height),
                new DataPointer(bitmapData.Scan0, bitmapData.Stride * bitmapData.Height),
                bitmapData.Stride,
                bitmapProperties);
            image.UnlockBits(bitmapData);

            this.ratio = (float)image.Width / image.Height;
        }
        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);
        }
Ejemplo n.º 25
0
        private void UpdateMapNoWdl(string continent)
        {
            var wdtPath = string.Format(@"World\Map\{0}\{0}.wdt", continent);
            var hasWdt = FileManager.Instance.Provider.Exists(wdtPath);
            if(hasWdt == false)
            {
                UpdateMapFallback(continent);
                return;
            }

            using(var strm = FileManager.Instance.Provider.OpenFile(wdtPath))
            {
                var reader = new BinaryReader(strm);
                var hasWdtData = false;
                while (true)
                {
                    try
                    {
                        var id = reader.ReadUInt32();
                        var size = reader.ReadInt32();
                        if (id == 0x4D41494E)
                        {
                            var adtFlags = reader.ReadArray<ulong>(size / 8);
                            var textureData = new uint[Width * Height];
                            for(var i = 0; i < 64; ++i)
                            {
                                for(var j = 0; j < 64; ++j)
                                {
                                    var idx = i * 64 + j;
                                    var exists = (adtFlags[idx] & 1) != 0;
                                    if(exists)
                                    {
                                        hasWdtData = true;
                                        for(var k = 0; k < 17; ++k)
                                        {
                                            for(var l = 0; l < 17; ++l)
                                                textureData[(i * 17 + k) * (64 * 17) + j * 17 + l] = 0xFFFFFFFF;
                                        }
                                    }
                                }
                            }

                            var bmpProps =
                                new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                    AlphaMode.Ignore));

                            using (var dataStream = new DataStream(Width * Height * 4, true, true))
                            {
                                dataStream.WriteRange(textureData);
                                dataStream.Position = 0;

                                mImage = new Bitmap(InterfaceManager.Instance.Surface.RenderTarget, new Size2(Width, Height),
                                    new DataPointer(dataStream.DataPointer, Width * Height * 4), Width * 4, bmpProps);
                            }

                            break;
                        }

                        reader.ReadBytes(size);
                    }
                    catch (Exception)
                    {
                        UpdateMapFallback(continent);
                        return;
                    }
                }

                if (hasWdtData == false)
                    UpdateMapFallback(continent);
            }
        }
Ejemplo n.º 26
0
        /* CONSTRUCTOR & DESTRUCTOR METHODS */
        /// <summary>
        /// Constructs a renderable 2D image from a stored image file.
        /// </summary>
        /// <param name="window">A reference to a Direct3D-capable rendering window.</param>
        /// <param name="fileName">An absolute or relative image file path.</param>
        public ImageDX(Window3D window, string fileName)
            : base(window)
        {
            using (SystemBitmap image = (SystemBitmap)SystemBitmap.FromFile(fileName))
            {
                Height = image.Height;
                Width = image.Width;

                var szImage = new System.Drawing.Rectangle(0, 0, image.Width, image.Height);
                int byteSize = image.Height * image.Width * sizeof(int);

                using (DataStream bmpStream = new DataStream(byteSize, true, true))
                {
                    var sysPixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb;
                    BitmapData bmpData = image.LockBits(szImage, ImageLockMode.ReadWrite, sysPixelFormat);

                    for (int y = 0; y < image.Height; y++)
                    {
                        int offset = y * bmpData.Stride;
                        for (int x = 0; x < image.Width; x++)
                        {
                            // System bitmaps store pixel values as BGRA byte arrays
                            byte b = Marshal.ReadByte(bmpData.Scan0, offset++);
                            byte g = Marshal.ReadByte(bmpData.Scan0, offset++);
                            byte r = Marshal.ReadByte(bmpData.Scan0, offset++);
                            byte a = Marshal.ReadByte(bmpData.Scan0, offset++);

                            // Convert BGRA to RGBA (stored as a 32 bit = 4 byte integer)
                            int rgba = r | (g << 8) | (b << 16) | (a << 24);

                            // Write the RGBA value to the data buffer
                            bmpStream.Write(rgba);
                        }
                    }

                    image.UnlockBits(bmpData);
                    bmpStream.Position = 0;

                    BitmapProperties bmpProps = new BitmapProperties(RenderTarget.PixelFormat);
                    Bitmap = new Bitmap(RenderTarget, new Size2(image.Width, image.Height), bmpStream, bmpData.Stride, bmpProps);
                    Crop = new RectangleF(0, 0, Width, Height);
                }
            }
        }
            private unsafe void DrawCursor(SharpDX.Direct2D1.RenderTarget renderTarger, CursorInfo cursor)
            {
                var position = cursor.Position;

                var shapeBuff = cursor.PtrShapeBuffer;
                var shapeInfo = cursor.ShapeInfo;

                int width  = shapeInfo.Width;
                int height = shapeInfo.Height;
                int pitch  = shapeInfo.Pitch;

                int left   = position.X;
                int top    = position.Y;
                int right  = position.X + width;
                int bottom = position.Y + height;

                //logger.Debug(left + " " + top + " " + right + " " + bottom);

                if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR)
                {
                    var data       = new DataPointer(shapeBuff, height * pitch);
                    var prop       = new Direct2D.BitmapProperties(new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied));
                    var size       = new Size2(width, height);
                    var cursorBits = new Direct2D.Bitmap(renderTarger, size, data, pitch, prop);
                    try
                    {
                        var cursorRect = new RawRectangleF(left, top, right, bottom);

                        renderTarger.DrawBitmap(cursorBits, cursorRect, 1.0f, Direct2D.BitmapInterpolationMode.Linear);
                    }
                    finally
                    {
                        cursorBits?.Dispose();
                    }
                }
                else if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME)
                {
                    height = height / 2;

                    left   = position.X;
                    top    = position.Y;
                    right  = position.X + width;
                    bottom = position.Y + height;
                    pitch  = width * 4;

                    Texture2D desktopRegionTex = null;
                    try
                    {
                        desktopRegionTex = new Texture2D(device,
                                                         new Texture2DDescription
                        {
                            CpuAccessFlags    = CpuAccessFlags.Read,
                            BindFlags         = BindFlags.None,
                            Format            = Format.B8G8R8A8_UNorm,
                            Width             = width,
                            Height            = height,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            SampleDescription = { Count = 1, Quality = 0 },
                            Usage             = ResourceUsage.Staging,
                            OptionFlags       = ResourceOptionFlags.None,
                        });

                        var region           = new ResourceRegion(left, top, 0, right, bottom, 1);
                        var immediateContext = device.ImmediateContext;
                        immediateContext.CopySubresourceRegion(screenTexture, 0, region, desktopRegionTex, 0);

                        var dataBox = immediateContext.MapSubresource(desktopRegionTex, 0, MapMode.Read, MapFlags.None);
                        try
                        {
                            var desktopBuffer = new byte[width * height * 4];
                            Marshal.Copy(dataBox.DataPointer, desktopBuffer, 0, desktopBuffer.Length);

                            var shapeBufferLenght = width * height * 4;
                            var shapeBuffer       = new byte[shapeBufferLenght];

                            var maskBufferLenght = width * height / 8;
                            var andMaskBuffer    = new byte[maskBufferLenght];
                            Marshal.Copy(shapeBuff, andMaskBuffer, 0, andMaskBuffer.Length);

                            var xorMaskBuffer = new byte[maskBufferLenght];
                            Marshal.Copy(shapeBuff + andMaskBuffer.Length, xorMaskBuffer, 0, xorMaskBuffer.Length);

                            for (var row = 0; row < height; ++row)
                            {
                                byte mask = 0x80;

                                for (var col = 0; col < width; ++col)
                                {
                                    var maskIndex = row * width / 8 + col / 8;

                                    var andMask = ((andMaskBuffer[maskIndex] & mask) == mask) ? 0xFF : 0;
                                    var xorMask = ((xorMaskBuffer[maskIndex] & mask) == mask) ? 0xFF : 0;

                                    int pos = row * width * 4 + col * 4;
                                    for (int i = 0; i < 3; i++)
                                    {// RGB
                                        shapeBuffer[pos] = (byte)((desktopBuffer[pos] & andMask) ^ xorMask);
                                        pos++;
                                    }
                                    // Alpha
                                    shapeBuffer[pos] = (byte)((desktopBuffer[pos] & 0xFF) ^ 0);

                                    if (mask == 0x01)
                                    {
                                        mask = 0x80;
                                    }
                                    else
                                    {
                                        mask = (byte)(mask >> 1);
                                    }
                                }
                            }


                            Direct2D.Bitmap cursorBits = null;
                            try
                            {
                                fixed(byte *ptr = shapeBuffer)
                                {
                                    var data = new DataPointer(ptr, height * pitch);
                                    var prop = new Direct2D.BitmapProperties(new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied));
                                    var size = new Size2(width, height);

                                    cursorBits = new Direct2D.Bitmap(renderTarger, size, data, pitch, prop);
                                };

                                var shapeRect = new RawRectangleF(left, top, right, bottom);

                                renderTarger.DrawBitmap(cursorBits, shapeRect, 1.0f, Direct2D.BitmapInterpolationMode.Linear);
                            }
                            finally
                            {
                                cursorBits?.Dispose();
                            }
                        }
                        finally
                        {
                            immediateContext.UnmapSubresource(desktopRegionTex, 0);
                        }
                    }
                    finally
                    {
                        desktopRegionTex?.Dispose();
                    }
                }
                else if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR)
                {
                    logger.Warn("Not supported cursor type " + ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR);
                }
            }
Ejemplo n.º 28
0
        public void UpdateInternalImage(Matrix.FxMatrixF mat, ColorMap map, bool useInvMap = false)
        {
            // link the extran matrix with the internal
            internalMatrix = mat;

            // check if we need to create a new internal buffer
            if (mat.Width != Width || mat.Height != Height)
            {
                lock (this)
                {
                    // set the properties of the image
                    BitmapProperties bitmapProps = new BitmapProperties();
                    bitmapProps.PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);

                    // set the size of the image
                    Width = mat.Width;
                    Height = mat.Height;

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

                    // make the bitmap for Direct2D1
                    mImageBitmap = new SharpDX.Direct2D1.Bitmap(this.Parent.RenderVariables.renderTarget,
                                                                new Size2(Width, Height),
                                                                bitmapProps);
                }
            }

            unsafe
            {
                try
                {
                    int size = Width * Height;
                    fixed (byte* dst = internalImage)
                    {
                        fixed (float* src = mat.Data)
                        {
                            byte* pDst = dst;
                            float* pSrc = src;

                            if (useInvMap)
                            {
            #if false
                                float* pSrcEnd = pSrc + mat.Size;
                                for (; pSrc < pSrcEnd; pSrc++)
                                {
                                    byte id = (byte)(255 - *(pSrc) * 255);
                                    *(pDst++) = map[id, 2];
                                    *(pDst++) = map[id, 1];
                                    *(pDst++) = map[id, 0];
                                    *(pDst++) = 255;
                                }
            #else
                                int step = size / 8;
                                Parallel.For(0, 8, (s) =>
                                {
                                    int end = (s + 1) * step;
                                    for (int i = s * step; i < end; i++)
                                    {
                                        byte id = (byte)(255 - *(pSrc + i) * 255);
                                        int i4 = i * 4;
                                        *(pDst + i4) = map[id, 2];
                                        *(pDst + i4 + 1) = map[id, 1];
                                        *(pDst + i4 + 2) = map[id, 0];
                                        *(pDst + i4 + 3) = 255;

                                    }
                                });
            #endif
                            }
                            else
                            {
            #if false

                                float* pSrcEnd = pSrc + mat.Size;
                                for(; pSrc < pSrcEnd; pSrc++) {
                                    byte id = (byte)(*(pSrc) * 255);
                                    *(pDst++) = map[id, 2];
                                    *(pDst++) = map[id, 1];
                                    *(pDst++) = map[id, 0];
                                    *(pDst++) = 255;
                                }
            #else
                                int step = size / 8;
                                Parallel.For(0, 8, (s) =>
                                {
                                    int end = (s + 1) * step;
                                    for (int i = s * step; i < end; i++)
                                    {
                                        byte id = (byte)(*(pSrc + i) * 255);
                                        int i4 = i * 4;
                                        *(pDst + i4) = map[id, 2];
                                        *(pDst + i4 + 1) = map[id, 1];
                                        *(pDst + i4 + 2) = map[id, 0];
                                        *(pDst + i4 + 3) = 255;

                                    }
                                });
            #endif
                            }
                        }
                    }

                    // write to the specific bitmap not create a new one
                    mImageBitmap.CopyFromMemory(internalImage, Width * 4);
                }
                catch (Exception ex) { Console.WriteLine(ex.Message); }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Constructs a renderable 2D image from a color structure array.
        /// </summary>
        /// <param name="window">A reference to the Direct3D-capable window in which this texture will be rendered.</param>
        /// <param name="image">An array of size [HEIGHT, WIDTH] where each element represents a color formatted from RGBA bytes.</param>
        public ImageDX(Window3D window, Color[,] image)
            : base(window)
        {
            Height = image.GetLength(0);
            Width = image.GetLength(1);
            int byteSize = (int)Height * (int)Width * sizeof(int);

            using (DataStream bmpStream = new DataStream(byteSize, true, true))
            {
                foreach (Color color in image) { bmpStream.Write((int)color); }
                bmpStream.Position = 0;
                BitmapProperties bmpProps = new BitmapProperties(RenderTarget.PixelFormat);
                int stride = (int)Width * sizeof(int);
                Bitmap = new Bitmap(RenderTarget, new Size2((int)Width, (int)Height), bmpStream, stride, bmpProps);
                Crop = new RectangleF(0, 0, Width, Height);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Converts a <see cref="System.Drawing.Bitmap"/> object into a <see cref="SharpDX.Direct2D1.Bitmap"/> object for rendering.
        /// </summary>
        /// <param name="renderTarget">The <see cref="SharpDX.Direct2D1.RenderTarget"/> object that images are drawn on.</param>
        /// <param name="bmp">The .NET native bitmap image.</param>
        /// <returns>A <see cref="SharpDX.Direct2D1.Bitmap"/> containing the image data retrieved from the <see cref="System.Drawing.Bitmap"/> object.</returns>
        public static Bitmap FromSysBMP(RenderTarget renderTarget, SystemBitmap bmp)
        {
            var imageArea = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
            var bmpProps = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));

            // Unmanaged buffer needs proper disposal
            using (var dataStream = new DataStream(bmp.ByteSize(), true, true))
            {
                var bmpData = bmp.LockBits(imageArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                for (int y = 0; y < bmp.Height; y++)
                {
                    int offset = y * bmpData.Stride;
                    for (int x = 0; x < bmp.Width; x++)
                    {
                        // System bitmaps store pixel values as BGRA byte arrays
                        byte b = Marshal.ReadByte(bmpData.Scan0, offset++);
                        byte g = Marshal.ReadByte(bmpData.Scan0, offset++);
                        byte r = Marshal.ReadByte(bmpData.Scan0, offset++);
                        byte a = Marshal.ReadByte(bmpData.Scan0, offset++);

                        // Convert BGRA to RGBA (stored as a 32 bit = 4 byte integer)
                        int rgba = r | (g << 8) | (b << 16) | (a << 24);

                        // Write the RGBA value to the data buffer
                        dataStream.Write(rgba);
                    }
                }

                // Release the lock on the bitmap & reset the buffer position pointer
                bmp.UnlockBits(bmpData);
                dataStream.Position = 0;

                return new Bitmap(renderTarget, new Size2(bmp.Width, bmp.Height), dataStream, bmpData.Stride, bmpProps);
            }
        }
Ejemplo n.º 31
0
        TextureAsset IAssetManager.LoadTexture(string file)
        {
            Bitmap result = null;
            if (_bitmapResources.TryGetValue(file, out result) && !result.IsDisposed)
                return new TextureAsset(result);

            Stream stream;
            if (File.Exists(RootDirectory + file))
                stream = File.OpenRead(RootDirectory + file);
            else if (File.Exists(file))
                stream = File.OpenRead(file);
            else {
                stream = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                          from name in assembly.GetManifestResourceNames()
                          where String.Compare(file, name, true) != 0
                          select assembly.GetManifestResourceStream(name)).FirstOrDefault();
            }

            if (stream == null) {
                Console.Error.WriteLine("Failed to load bitmap asset: {0}", file);
                // TODO: Have some sort of placeholder texture to feed back, even a single pixel
                return null;
            }

            try {
                using (var newBitmap = new System.Drawing.Bitmap(stream)) {

                    var sourceArea = new System.Drawing.Rectangle(0, 0, newBitmap.Width, newBitmap.Height);
                    var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                    var size = new DrawingSize(newBitmap.Width, newBitmap.Height);

                    // Transform pixels from BGRA to RGBA
                    int stride = newBitmap.Width * sizeof(int);
                    using (var tempStream = new DataStream(newBitmap.Height * stride, true, true)) {
                        // Lock System.Drawing.Bitmap
                        var bitmapData = newBitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                        // Convert all pixels
                        for (int y = 0; y < newBitmap.Height; y++) {
                            int offset = bitmapData.Stride * y;
                            for (int x = 0; x < newBitmap.Width; x++) {
                                // Not optimized
                                byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                int rgba = R | (G << 8) | (B << 16) | (A << 24);
                                tempStream.Write(rgba);
                            }

                        }
                        newBitmap.UnlockBits(bitmapData);
                        tempStream.Position = 0;

                        try {
                            result = new Bitmap(_renderTarget2D, size, tempStream, stride, bitmapProperties);
                        } catch (NullReferenceException) {
                            throw new AssetLoadException("Graphics device uninitialized");
                        }
                    }
                }
            } catch (ArgumentException) {
                Console.Error.WriteLine("Invalid data stream while loading bitmap data");
            } finally {
                stream.Dispose();
            }
            _bitmapResources.AddOrUpdate(file, result, (key, oldValue) => {
                if (!oldValue.IsDisposed)
                    oldValue.Dispose();
                return result;
            });
            return new TextureAsset(result);
        }
Ejemplo n.º 32
0
        internal static Bitmap ToSharpDXBitmap(RenderTarget rt, System.Drawing.Bitmap image, float symbolScale)
        {
            if (image == null)
                throw new ArgumentNullException("image");

            if (image.PixelFormat != GdiPixelFormat.Format32bppPArgb)
                return null;

            var imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly, image.PixelFormat);


            var dataStream = new DataStream(imageData.Scan0, imageData.Stride*imageData.Height, true, false);
            var properties = new BitmapProperties
            {
                PixelFormat = new SharpDX.Direct2D1.PixelFormat
                {
                    Format =   SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    AlphaMode = AlphaMode.Premultiplied
                }
            };

            // ToDo apply scaling here!
            //var scaler = new BitmapScaler(rt.Factory.NativePointer);
            //scaler.

            //Load the image from the gdi resource
            var result = new Bitmap(rt, new Size2(image.Width, image.Height), dataStream, imageData.Stride, properties);

            image.UnlockBits(imageData);

            return result;
        }
Ejemplo n.º 33
0
        public override void Load(CanvasRenderArguments args)
        {
            // set the properties of the image
            BitmapProperties bitmapProps = new BitmapProperties();
            bitmapProps.PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);

            if (mImageBitmap == null)
            {
                // make the bitmap for Direct2D1
                mImageBitmap = new SharpDX.Direct2D1.Bitmap(args.renderTarget,
                    new Size2(Width, Height),
                    bitmapProps);
            }

            // write to the specific bitmap not create a new one
            mImageBitmap.CopyFromMemory(internalImage, Pitch);
        }
Ejemplo n.º 34
0
        private void UpdateMapFallback(string continent)
        {
            var textureData = new uint[Width * Height];
            for (var i = 0; i < 64; ++i)
            {
                for (var j = 0; j < 64; ++j)
                {
                    var exists = FileManager.Instance.Provider.Exists(string.Format(@"World\Maps\{0}\{0}_{1}_{2}.adt", continent, j, i));
                    if (exists)
                    {
                        for (var k = 0; k < 17; ++k)
                        {
                            for (var l = 0; l < 17; ++l)
                                textureData[(i * 17 + k) * (64 * 17) + j * 17 + l] = 0xFFFFFFFF;
                        }
                    }
                }
            }

            var bmpProps =
                new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    AlphaMode.Ignore));

            using (var dataStream = new DataStream(Width * Height * 4, true, true))
            {
                dataStream.WriteRange(textureData);
                dataStream.Position = 0;

                mImage = new Bitmap(InterfaceManager.Instance.Surface.RenderTarget, new Size2(Width, Height),
                    new DataPointer(dataStream.DataPointer, Width * Height * 4), Width * 4, bmpProps);
            }
        }
Ejemplo n.º 35
0
        private static Bitmap CreateBitmap(RenderTarget renderTarget, string key, Size2 size, Color4 color, Func<int, int, bool> pred)
        {
            if (!ImageCash.ContainsKey(key))
            {
                var imageInt = new int[size.Width * size.Height];

                // Convert all pixels
                for (int y = 0; y < size.Height; y++)
                {
                    for (int x = 0; x < size.Width; x++)
                    {
                        var rgba = pred(y, x) ? FromColor4(color) : 0;
                        imageInt[size.Width * y + x] = rgba;
                    }
                }

                ImageCash.Add(key, imageInt);
            }

            int stride = size.Width * sizeof(int);

            using (var tempStream = new DataStream(stride * size.Height, true, true))
            {
                var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));

                var cash = ImageCash[key];

                foreach (int t in cash) { tempStream.Write(t); }

                tempStream.Position = 0;

                return new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties);
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// System.Drawing.ImageからSharpDX.Direct2D1.Bitmapを作成する
        /// </summary>
        /// <param name="renderTarget"></param>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static Bitmap LoadFromImage(RenderTarget renderTarget, string key, System.Drawing.Bitmap bitmap)
        {
            if (!ImageCash.ContainsKey(key))
            {
                var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);

                var imageint = new int[bitmap.Width * bitmap.Height];

                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly,
                                                 System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                // Convert all pixels
                for (int y = 0; y < bitmap.Height; y++)
                {
                    int offset = bitmapData.Stride * y;
                    for (int x = 0; x < bitmap.Width; x++)
                    {
                        // Not optimized
                        byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = R | (G << 8) | (B << 16) | (A << 24);
                        imageint[bitmap.Width * y + x] = rgba;
                    }

                }
                bitmap.UnlockBits(bitmapData);
                ImageCash.Add(key, imageint);
            }

            // Transform pixels from BGRA to RGBA
            int stride = bitmap.Width * sizeof(int);
            using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
            {
                var bitmapProperties =
                    new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));

                var size = new Size2(bitmap.Width, bitmap.Height);

                var cash = ImageCash[key];

                foreach (var rgba in cash) { tempStream.Write(rgba); }

                tempStream.Position = 0;

                return new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties);
            }
        }
Ejemplo n.º 37
0
 private static void ConfigureBitmap(out BitmapProperties description)
 {
     description.DpiX = 96.0f;
     description.DpiY = 96.0f;
     description.PixelFormat = PixelFormat;
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Run our application until the user quits.
        /// </summary>
        public void Run()
        {
            // Make window active and hide mouse cursor.
            window.PointerCursor = null;
            window.Activate();

            // Infinite loop to prevent the application from exiting.
            while (true)
            {
                // Dispatch all pending events in the queue.
                window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

                // Quit if the users presses Escape key.
                if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
                {
                    return;
                }

                int WIDTH = 1280;
                int HEIGHT = 800;
                Mandelbrot engine = new BasicMandelbrot(64);
                MandelbrotView view = new StaticMandelbrotView(engine, -.875f, 0f, 3f, WIDTH, HEIGHT);

                // Set the Direct2D drawing target.
                d2dContext.Target = d2dTarget;

                int[] data = new int[WIDTH * HEIGHT];
                for (int y = 0; y < HEIGHT; y++)
                {
                    for (int x = 0; x < WIDTH; x++)
                    {
                        float val = view.pixelAt(x, y);
                        int intVal = (int)(255 * val);
                        data[y * WIDTH + x] = 0 | intVal << 16 | intVal << 8 | intVal;
                    }
                }

                DrawingSize size = new DrawingSize(WIDTH, HEIGHT);
                PixelFormat format = new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore);
                BitmapProperties props = new BitmapProperties(format);
                RenderTarget target = d2dContext;
                Bitmap buf = Bitmap.New<int>(target, size, data, props);

                // Clear the target and draw some geometry with the brushes we created. Note that rectangles are
                // created specifying (start-x, start-y, end-x, end-y) coordinates; in XNA we used
                // (start-x, start-y, width, height).
                d2dContext.BeginDraw();
                d2dContext.DrawBitmap(buf, 1, BitmapInterpolationMode.Linear);
                d2dContext.EndDraw();

                // Present the current buffer to the screen.
                swapChain.Present(1, PresentFlags.None);
            }
        }