private Dictionary<string, string> LoadFonts()
		{
			Dictionary<string, string> result = new Dictionary<string, string>();

			var factory = new Factory();
			var fontCollection = factory.GetSystemFontCollection(false);
			var familyCount = fontCollection.FontFamilyCount;

			for (int i = 0; i < familyCount; i++)
			{
				var fontFamily = fontCollection.GetFontFamily(i);
				var familyNames = fontFamily.FamilyNames;
				int index;

				if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out index))
				{
					familyNames.FindLocaleName("en-us", out index);
				}
				string name = familyNames.GetString(index);
				result.Add(name, name);
			}


			return result;
		}
Example #2
0
        private void RecalculateMetrics()
        {
            metrics.Clear();

            using (var factory = new SharpDX.DirectWrite.Factory())
                using (var format = new TextFormat(factory, "Calibri", 20))
                {
                    format.ParagraphAlignment = ParagraphAlignment.Center;
                    format.TextAlignment      = TextAlignment.Center;

                    var rect = new RectangleF(Margin, 5, 0, Size.Y - 10);
                    for (int i = 0; i < Items.Count; i++)
                    {
                        var item = Items[i];
                        using (var layout = new TextLayout(factory, item.Text, format, float.PositiveInfinity, Size.Y))
                        {
                            var width = layout.DetermineMinWidth() + 2 * Margin;
                            rect.Width    = width;
                            metrics[item] = new MenuItemMetrics()
                            {
                                Index    = i,
                                Position = new Vector2(rect.X, rect.Y),
                                Size     = new Vector2((int)rect.Width, (int)rect.Height),
                            };
                            rect.X += rect.Width;
                        }
                    }
                }
        }
Example #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ResourceFontLoader"/> class.
        /// </summary>
        /// <param name="factory">The factory.</param>
        public ResourceFontLoader(Factory factory)
        {
            _factory = factory;
            foreach (var name in typeof(ResourceFontLoader).Assembly.GetManifestResourceNames())
            {
                if (name.EndsWith(".ttf"))
                {
                    var fontBytes = Utilities.ReadStream(typeof (ResourceFontLoader).Assembly.GetManifestResourceStream(name));
                    var stream = new DataStream(fontBytes.Length, true, true);
                    stream.Write(fontBytes, 0, fontBytes.Length);
                    stream.Position = 0;
                    _fontStreams.Add(new ResourceFontFileStream(stream));
                }
            }

            // Build a Key storage that stores the index of the font
            _keyStream = new DataStream(sizeof(int) * _fontStreams.Count, true, true);
            for (int i = 0; i < _fontStreams.Count; i++ )
                _keyStream.Write((int)i);
            _keyStream.Position = 0;

            // Register the 
            _factory.RegisterFontFileLoader(this);
            _factory.RegisterFontCollectionLoader(this);
        }
Example #4
0
 public ResourceFactory(RenderTarget renderTarget)
 {
     _renderTarget = renderTarget;
     _fontFactory  = new FontFactory();
     _textFormats  = new Dictionary <string, TextFormat>();
     _brushes      = new Dictionary <Color, SolidColorBrush>();
 }
Example #5
0
        public void Dispose()
        {
            foreach (var grad in verticalGradientCache.Values)
            {
                grad.Dispose();
            }
            verticalGradientCache.Clear();

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

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

            if (factory != null)
            {
                factory.Dispose();
                factory = null;
            }
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="directWriteFactory"></param>
        /// <param name="caption"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public Button(SharpDX.DirectWrite.Factory directWriteFactory, string caption, float x, float y, float width = BUTTON_STANDARD_WIDTH, float height = BUTTON_STANDARD_HEIGHT)
        {
            Caption = caption;
            X       = x;
            Y       = y;
            Width   = width;
            Height  = height;

            hovered = false;
            pressed = false;

            TextColor = SolidColorBrushes.White;

            roundedRectangle         = new RoundedRectangle();
            roundedRectangle.RadiusX = 8;
            roundedRectangle.RadiusY = 8;

            rect = new RectangleF(x, y, width, height);
            roundedRectangle.Rect = rect;

            textLayout = new TextLayout(directWriteFactory, caption, FormFonts.ButtonNormalFont, width, height);
            TextMetrics textMetrics = textLayout.Metrics;

            textPosition = new Vector2(x + ((width / 2f) - (textMetrics.Width / 2f)), y + ((height / 2f) - (textMetrics.Height / 2f)));
        }
Example #7
0
        public Render(int height, int width)
        {
            this._height = height;

            this._width = width;

            Window = GetWindow();

            _fontFactory = new FontFactory(FactoryType.Isolated);

            _textFormat = new TextFormat(_fontFactory, "Arial", 12); // TODO : Change to collection of fonts

            var renderProperties = new HwndRenderTargetProperties()
            {
                Hwnd           = Window.Handle,
                PixelSize      = new Size2(width, height),
                PresentOptions = PresentOptions.None
            };

            var renderTargetProperties = new RenderTargetProperties()
            {
                PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied),
            };

            _device = new WindowRenderTarget(new Factory(), renderTargetProperties, renderProperties);
        }
Example #8
0
        private void LoadOverlay(object sender, EventArgs e)
        {
            this.DoubleBuffered = true;
            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor | ControlStyles.ResizeRedraw | ControlStyles.Opaque | ControlStyles.UserPaint, true);
            this._factory     = new SharpDX.Direct2D1.Factory();
            this._fontFactory = new SharpDX.DirectWrite.Factory();
            HwndRenderTargetProperties properties = new HwndRenderTargetProperties
            {
                Hwnd           = base.Handle,
                PixelSize      = new Size2(base.Size.Width, base.Size.Height),
                PresentOptions = PresentOptions.None
            };

            this._renderProperties = properties;
            this._device           = new WindowRenderTarget(this._factory, new RenderTargetProperties(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)), this._renderProperties);
            this._brush            = new SolidColorBrush(this._device, new RawColor4((float)Color.Red.R, (float)Color.Red.G, (float)Color.Red.B, (float)Color.Red.A));
            this._font             = new TextFormat(this._fontFactory, "Verdana", FontWeight.Bold, FontStyle.Normal, 12f);
            this._fontSmall        = new TextFormat(this._fontFactory, "Verdana", FontWeight.Bold, FontStyle.Normal, 10f);
            Console.WriteLine("Starting Maler Thread");
            Thread thread1 = new Thread(new ParameterizedThreadStart(this.DirectXThread))
            {
                Priority     = ThreadPriority.Highest,
                IsBackground = true
            };

            this._threadDx = thread1;
            this._running  = true;
            this._threadDx.Start();
        }
Example #9
0
        public Direct2DFactories()
        {
            WICFactory = new WIC.ImagingFactory ();
            DWFactory = new DW.Factory ();

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

            var dxgiDevice = ComObject.As<SharpDX.DXGI.Device> (d3DDevice.NativePointer);
            var d2DDevice = new D2D1.Device (dxgiDevice);
            D2DFactory = d2DDevice.Factory;
            //_d2DDeviceContext = new D2D1.DeviceContext (d2DDevice, D2D1.DeviceContextOptions.None);
            //var dpi = DisplayDpi;
            //_d2DDeviceContext.DotsPerInch = new Size2F (dpi, dpi);
        }
Example #10
0
 public Game(WindowRenderTarget target)
 {
     this.target       = target;
     this.factoryWrite = new SharpDX.DirectWrite.Factory();
     this.brushes      = new Brushes(this);
     this.scene        = new MenuScene(this);
 }
Example #11
0
 public static void CreateIndependentResource()
 {
     d2d1factory  = new Direct2D1.Factory();
     imageFactory = new WIC.ImagingFactory();
     writeFactory = new DirectWrite.Factory();
     Ready        = true;
 }
Example #12
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="Direct2DRenderer" /> class.
        /// </summary>
        /// <param name="hwnd">The HWND.</param>
        /// <param name="limitFps">if set to <c>true</c> [limit FPS].</param>
        public Direct2DRenderer(IntPtr hwnd, bool limitFps)
        {
            _factory = new SharpDX.Direct2D1.Factory();

            _fontFactory = new Factory();

            Native.Rect bounds;
            Native.GetWindowRect(hwnd, out bounds);

            var targetProperties = new HwndRenderTargetProperties
            {
                Hwnd           = hwnd,
                PixelSize      = new Size2(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top),
                PresentOptions = limitFps ? PresentOptions.None : PresentOptions.Immediately
            };

            var prop = new RenderTargetProperties(RenderTargetType.Hardware,
                                                  new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None,
                                                  FeatureLevel.Level_DEFAULT);

            _device = new WindowRenderTarget(_factory, prop, targetProperties)
            {
                TextAntialiasMode = TextAntialiasMode.Aliased,
                AntialiasMode     = AntialiasMode.Aliased
            };
        }
Example #13
0
        public static void WatermarkText(Stream imageStream, Stream outputStream, string watermark, string font = "Times New Roman", float fontSize = 30.0f, int colorARGB = TransparentWhite)
        {
            using (var wic = new WIC.ImagingFactory2())
                using (var d2d = new D2D.Factory())
                    using (var image = CreateWicImage(wic, imageStream))
                        using (var wicBitmap = new WIC.Bitmap(wic, image.Size.Width, image.Size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand))
                            using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()))
                                using (var bmpPicture = D2D.Bitmap.FromWicBitmap(target, image))
                                    using (var dwriteFactory = new DWrite.Factory())
                                        using (var brush = new D2D.SolidColorBrush(target, new Color(colorARGB)))
                                        {
                                            target.BeginDraw();
                                            {
                                                target.DrawBitmap(bmpPicture, new RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, D2D.BitmapInterpolationMode.Linear);
                                                target.DrawRectangle(new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush);
                                                var textFormat = new DWrite.TextFormat(dwriteFactory, font, DWrite.FontWeight.Bold, DWrite.FontStyle.Normal, fontSize)
                                                {
                                                    ParagraphAlignment = DWrite.ParagraphAlignment.Far,
                                                    TextAlignment      = DWrite.TextAlignment.Trailing,
                                                };
                                                target.DrawText(watermark, textFormat, new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush);
                                            }
                                            target.EndDraw();

                                            SaveD2DBitmap(wic, wicBitmap, outputStream);
                                        }
        }
Example #14
0
            public TextLayoutParameters(
                DWrite.Factory factory,
                string name,
                float pointSize,
                bool bold,
                bool italic,
                bool underline,
                bool strikeout,
                Size2F dpi)
            {
                this.FontName  = name;
                this.PointSize = pointSize;
                this.DipSize   = Helpers.GetFontSize(pointSize);
                this.Weight    = bold ? DWrite.FontWeight.Bold : DWrite.FontWeight.Normal;
                this.Style     = italic ? DWrite.FontStyle.Italic : DWrite.FontStyle.Normal;
                this.Underline = underline;
                this.StrikeOut = strikeout;

                using (var textFormat = new DWrite.TextFormat(factory, this.FontName, this.Weight, this.Style, this.DipSize))
                    using (var textLayout = new DWrite.TextLayout(factory, "A", textFormat, 1000, 1000))
                    {
                        this.LineHeight = Helpers.AlignToPixel(textLayout.Metrics.Height, dpi.Height);
                        this.CharWidth  = Helpers.AlignToPixel(textLayout.OverhangMetrics.Left + (1000 + textLayout.OverhangMetrics.Right), dpi.Width);
                    }
            }
Example #15
0
        public Direct2DRenderer(IntPtr hwnd, bool limitFps)
        {
            _factory = new Factory();

            _fontFactory = new FontFactory();

            RECT bounds;//immer 1920x1080. resizing muss durch die Overlay klasse geregelt sein

            NativeMethods.GetWindowRect(hwnd, out bounds);

            var targetProperties = new HwndRenderTargetProperties
            {
                Hwnd           = hwnd,
                PixelSize      = new Size2(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top),
                PresentOptions = limitFps ? PresentOptions.None : PresentOptions.Immediately //Immediatly -> Zeichnet sofort ohne auf 60fps zu locken. None lockt auf 60fps
            };

            var prop = new RenderTargetProperties(RenderTargetType.Hardware, new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);

            _device = new WindowRenderTarget(_factory, prop, targetProperties)
            {
                TextAntialiasMode = TextAntialiasMode.Cleartype,
                AntialiasMode     = AntialiasMode.PerPrimitive
            };
        }
Example #16
0
        // INIT
        private void DrawWindow_Load(object sender, EventArgs e)
        {
            this.TopMost         = true;
            this.Visible         = true;
            this.FormBorderStyle = FormBorderStyle.None;
            //this.WindowState = FormWindowState.Maximized;
            this.Width  = rect.Width;
            this.Height = rect.Height;

            // Window name
            this.Name = Process.GetCurrentProcess().ProcessName + "~Overlay";
            this.Text = Process.GetCurrentProcess().ProcessName + "~Overlay";

            // Init factory
            factory     = new Factory();
            fontFactory = new FontFactory();

            // Render settings
            renderProperties = new HwndRenderTargetProperties()
            {
                Hwnd           = this.Handle,
                PixelSize      = new Size2(rect.Width, rect.Height),
                PresentOptions = PresentOptions.None
            };

            // Init device
            device = new WindowRenderTarget(factory, new RenderTargetProperties(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)), renderProperties);

            // Init brush
            solidColorBrush = new SolidColorBrush(device, Color.White);

            // Init font's
            font      = new TextFormat(fontFactory, fontFamily, fontSize);
            fontSmall = new TextFormat(fontFactory, fontFamily, fontSizeSmall);

            // Open process
            RPM.OpenProcess(process.Id);

            // Init player array
            players     = new List <Player>();
            localPlayer = new Player();

            // Init update thread
            updateStream = new Thread(new ParameterizedThreadStart(Update));
            updateStream.Start();

            // Init window thread (resize / position)
            windowStream = new Thread(new ParameterizedThreadStart(SetWindow));
            windowStream.Start();

            // Init Key Listener
            manager = new KeysManager();
            manager.AddKey(Keys.F5);
            manager.AddKey(Keys.F6);
            manager.AddKey(Keys.F7);
            manager.AddKey(Keys.F8);
            manager.AddKey(Keys.F9);
            //manager.KeyUpEvent += new KeysManager.KeyHandler(KeyUpEvent);
            manager.KeyDownEvent += new KeysManager.KeyHandler(KeyDownEvent);
        }
        public List <InstalledFont> GetFonts() //该方法返回系统的所有字体
        {
            var fontList       = new List <InstalledFont>();
            var factory        = new SharpDX.DirectWrite.Factory(); //引入了SharpDX这个包,,,枚举类型
            var fontCollection = factory.GetSystemFontCollection(false);
            var familyCount    = fontCollection.FontFamilyCount;

            for (int i = 0; i < familyCount; i++)
            {
                var fontFamily  = fontCollection.GetFontFamily(i);
                var familyNames = fontFamily.FamilyNames;
                int index;

                if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out index))
                {
                    if (!familyNames.FindLocaleName("en-us", out index))
                    {
                        index = 0;
                    }
                }

                string name = familyNames.GetString(index);
                fontList.Add(new InstalledFont()
                {
                    Name        = name,
                    FamilyIndex = i,
                    Index       = index //共3个属性,当需要获取系统字体库的时候,只需要Name属性就行了,将该List集合中的所有Name属性添加到ComFont控件中即可
                });
            }

            return(fontList);
        }
Example #18
0
        protected void InitialiseComponents()
        {
            SharpDX.Configuration.EnableObjectTracking = true;

            var description = new DXGI.SwapChainDescription {
                BufferCount     = 1,
                ModeDescription =
                    new DXGI.ModeDescription(Width, Height, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = Handle,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                SwapEffect        = DXGI.SwapEffect.Discard,
                Usage             = DXGI.Usage.RenderTargetOutput
            };

            Direct3D.Device1.CreateWithSwapChain(Direct3D.DriverType.Hardware,
                                                 Direct3D.DeviceCreationFlags.BgraSupport, description, Direct3D.FeatureLevel.Level_10_0,
                                                 out device, out swapChain);

            var dxgiFactory = swapChain.GetParent <DXGI.Factory>();

            dxgiFactory.MakeWindowAssociation(Handle, DXGI.WindowAssociationFlags.IgnoreAll);

            directWriteFactory = new DirectWrite.Factory();

            CreateSizeDependentComponents();
            children.ForEach(c => c.SetContext(this));
        }
Example #19
0
        public void CreateDeviceIndependentResources(hkaSkeleton skeleton)
        {
            this.skeleton = skeleton;

            d2dFactory    = new SharpDX.Direct2D1.Factory();
            dwriteFactory = new SharpDX.DirectWrite.Factory();
        }
Example #20
0
        private void SetupInstance(RendererOptions options)
        {
            _rendererOptions = options;

            if (options.Hwnd == IntPtr.Zero)
            {
                throw new ArgumentNullException(nameof(options.Hwnd));
            }

            if (User32.IsWindow(options.Hwnd) == 0)
            {
                throw new ArgumentException("The window does not exist (hwnd = 0x" + options.Hwnd.ToString("X") + ")");
            }

            RECT bounds = new RECT();

            if (HelperMethods.GetRealWindowRect(options.Hwnd, out bounds) == 0)
            {
                throw new Exception("Failed to get the size of the given window (hwnd = 0x" + options.Hwnd.ToString("X") + ")");
            }

            this.Width  = bounds.Right - bounds.Left;
            this.Height = bounds.Bottom - bounds.Top;

            this.VSync      = options.VSync;
            this.MeasureFPS = options.MeasureFps;

            _deviceProperties = new HwndRenderTargetProperties()
            {
                Hwnd           = options.Hwnd,
                PixelSize      = new Size2(this.Width, this.Height),
                PresentOptions = options.VSync ? PresentOptions.None : PresentOptions.Immediately
            };

            var renderProperties = new RenderTargetProperties(
                RenderTargetType.Default,
                new PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                96.0f, 96.0f, // we use 96.0f because it's the default value. This will scale every drawing by 1.0f (it obviously does not scale anything). Our drawing will be dpi aware!
                RenderTargetUsage.None,
                FeatureLevel.Level_DEFAULT);

            _factory     = new Factory();
            _fontFactory = new FontFactory();

            try
            {
                _device = new WindowRenderTarget(_factory, renderProperties, _deviceProperties);
            }
            catch (SharpDXException) // D2DERR_UNSUPPORTED_PIXEL_FORMAT
            {
                renderProperties.PixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied);
                _device = new WindowRenderTarget(_factory, renderProperties, _deviceProperties);
            }

            _device.AntialiasMode = AntialiasMode.Aliased; // AntialiasMode.PerPrimitive fails rendering some objects
            // other than in the documentation: Cleartype is much faster for me than GrayScale
            _device.TextAntialiasMode = options.AntiAliasing ? SharpDX.Direct2D1.TextAntialiasMode.Cleartype : SharpDX.Direct2D1.TextAntialiasMode.Aliased;

            _sharedBrush = new SolidColorBrush(_device, default(RawColor4));
        }
        public DrawableText(string t, string name, float size, DeviceContext DC) : base(DC)
        {
            text    += t;
            wfactory = new SharpDX.DirectWrite.Factory();
            wformat  = new SharpDX.DirectWrite.TextFormat(wfactory, name, size);

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

                int fpt = 60 / Speed;

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

                return(true);
            });
        }
Example #22
0
        private void LoadOverlay(object sender, EventArgs e)
        {
            DoubleBuffered = true;
            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint |
                     ControlStyles.Opaque | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true);

            _Factory          = new Factory();
            _FontFactory      = new FontFactory();
            _RenderProperties = new HwndRenderTargetProperties
            {
                Hwnd           = Handle,
                PixelSize      = new SharpDX.Size2(Size.Width, Size.Height),
                PresentOptions = PresentOptions.None
            };

            // Initialize DirectX
            _Device = new WindowRenderTarget(_Factory, new RenderTargetProperties(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)),
                                             _RenderProperties);
            _SolidColorBrush = new SolidColorBrush(_Device, new RawColor4(Color.White.R, Color.White.G, Color.White.B, Color.White.A));

            _ThreadDX = new Thread(new ParameterizedThreadStart(DirectXThread))
            {
                Priority     = ThreadPriority.Highest,
                IsBackground = true
            };

            _Running = true;
            _ThreadDX.Start();
        }
        public Direct2DFactories()
        {
            WICFactory = new WIC.ImagingFactory();
            DWFactory  = new DW.Factory();

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

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

            D2DFactory = d2DDevice.Factory;
            //_d2DDeviceContext = new D2D1.DeviceContext (d2DDevice, D2D1.DeviceContextOptions.None);
            //var dpi = DisplayDpi;
            //_d2DDeviceContext.DotsPerInch = new Size2F (dpi, dpi);
        }
Example #24
0
        public InfoText(SharpDX.Direct3D11.Device device, int width, int height)
        {
            _immediateContext = device.ImmediateContext;
            _rect.Size        = new Size2F(width, height);
            _bitmapSize       = width * height * 4;
            IsEnabled         = true;

            using (var factoryWic = new SharpDX.WIC.ImagingFactory())
            {
                _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic,
                                                    width, height, _pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad);
            }

            var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                                                                    new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                                                                                                      SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None,
                                                                    SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);

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

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

            Color4 color = new Color4(1, 1, 1, 1);

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

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

            OverlayBufferView = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription()
            {
                Format    = _renderTexture.Description.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels       = 1,
                    MostDetailedMip = 0
                }
            });
        }
Example #25
0
 private D2D(Direct2D.Factory d2dFactory, Direct2D.RenderTarget d2dRenderTarget)
 {
     this.d2dFactory      = d2dFactory;
     this.d2dRenderTarget = d2dRenderTarget;
     this.wicFactory      = new WIC.ImagingFactory();
     this.dwFactory       = new DW.Factory();
 }
Example #26
0
        /// <summary>
        /// Disposes of object resources.
        /// </summary>
        /// <param name="disposeManagedResources">If true, managed resources should be
        /// disposed of in addition to unmanaged resources.</param>
        protected virtual void Dispose(bool disposeManagedResources)
        {
            if (disposeManagedResources)
            {
                _d3d11Device.Dispose();
                _dxgiDevice.Dispose();
                _backBuffer.Dispose();
                _targetBitmap.Dispose();
                _backBuffer2.Dispose();
                _targetBitmap2.Dispose();
                _d2dDevice.Dispose();
                swapChain.Dispose();
                swapChain2.Dispose();
                d2dContext.Dispose();
                d2dContext2.Dispose();
                dw_Factory.Dispose();
            }

            _d3d11Device   = null;
            _dxgiDevice    = null;
            _backBuffer    = null;
            _targetBitmap  = null;
            _backBuffer2   = null;
            _targetBitmap2 = null;
            _d2dDevice     = null;
            swapChain      = null;
            swapChain2     = null;
            d2dContext     = null;
            d2dContext2    = null;
            dw_Factory     = null;
        }
        public InfoText(SharpDX.Direct3D11.Device device, int width, int height)
        {
            _immediateContext = device.ImmediateContext;
            _rect.Size = new Size2F(width, height);
            _bitmapSize = width * height * 4;
            IsEnabled = true;

            using (var factoryWic = new SharpDX.WIC.ImagingFactory())
            {
                _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic,
                    width, height, _pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad);
            }

            var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None,
                    SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);

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

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

            Color4 color = new Color4(1, 1, 1, 1);
            _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color);
            _clearColor = color;
            _clearColor.Alpha = 0;

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

            OverlayBufferRes = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription()
            {
                Format = _renderTexture.Description.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            });
        }
Example #28
0
        public void DrawText(WindowRenderTarget renderTarget, string titleText, string xAxisText, string yAxisText, float baseTextSize)
        {
            var sgOffsetY       = renderTarget.Size.Height * 1 / 15;
            var sgOffsetX       = renderTarget.Size.Width * 1 / 15;
            var containerHeight = renderTarget.Size.Height - sgOffsetY * 2;
            var containerWidth  = renderTarget.Size.Width - sgOffsetX * 2; // not used?
            var textWidth       = (int)containerHeight;
            var textHeight      = (int)sgOffsetY;

            var factoryDWrite = new SharpDX.DirectWrite.Factory();

            _textFormatTitle = new TextFormat(factoryDWrite, "Segoe", baseTextSize * 5 / 4)
            {
                TextAlignment      = TextAlignment.Center,
                ParagraphAlignment = ParagraphAlignment.Center
            };
            _textFormatHorizontal = new TextFormat(factoryDWrite, "Segoe", baseTextSize)
            {
                TextAlignment      = TextAlignment.Center,
                ParagraphAlignment = ParagraphAlignment.Far
            };
            _textFormatVertical = new TextFormat(factoryDWrite, "Segoe", baseTextSize)
            {
                TextAlignment      = TextAlignment.Center,
                ParagraphAlignment = ParagraphAlignment.Far
            };

            renderTarget.AntialiasMode     = AntialiasMode.PerPrimitive;
            renderTarget.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype;

            var ClientRectangleTitle = new RectangleF(0, 0, textWidth, textHeight);
            var ClientRectangleXAxis = new RectangleF(0,
                                                      containerHeight - textHeight + sgOffsetY * 2, textWidth, textHeight);
            var ClientRectangleYAxis = new RectangleF(-sgOffsetX,
                                                      containerHeight - textHeight + sgOffsetY, textWidth, textHeight);

            _textSceneColorBrush.Color = _black;

            // Draw title and x axis text.
            renderTarget.BeginDraw();

            renderTarget.Clear(_white);
            renderTarget.DrawText(titleText, _textFormatTitle, ClientRectangleTitle, _textSceneColorBrush);
            renderTarget.DrawText(xAxisText, _textFormatHorizontal, ClientRectangleXAxis, _textSceneColorBrush);

            renderTarget.EndDraw();

            // Rotate render target to draw y axis text.
            renderTarget.Transform = Matrix3x2.Rotation((float)(-Math.PI / 2), new SharpDX.Vector2(0, containerHeight));

            renderTarget.BeginDraw();

            renderTarget.DrawText(yAxisText, _textFormatVertical, ClientRectangleYAxis, _textSceneColorBrush);

            renderTarget.EndDraw();

            // Rotate the RenderTarget back.
            renderTarget.Transform = Matrix3x2.Identity;
        }
Example #29
0
        public Row(SharpDX.DirectWrite.Factory directWriteFactory, SolidColorBrush textColor, UniverseTeamTable teamTable, PlayerEntry playerEntry, float x, float y, float width, float height)
        {
            X     = x;
            Y     = y;
            Width = width;

            rowContent  = new List <IFixedDrawable>();
            disposables = new List <IDisposable>();

            Height = 0f;

            try
            {
                float columnWidth = 0f;
                foreach (Column column in teamTable.Columns)
                {
                    if (PlayerEntry.PropertyInfos[column.FieldName].PropertyType == typeof(SharpDX.Direct2D1.Bitmap))
                    {
                        Bitmap bitmap = (SharpDX.Direct2D1.Bitmap)PlayerEntry.PropertyInfos[column.FieldName].GetValue(playerEntry);

                        ImageBox imageBox = new ImageBox(bitmap,
                                                         x + UniverseTeamTable.PADDING + columnWidth,
                                                         y);

                        if (imageBox.Bitmap.PixelSize.Height > Height)
                        {
                            Height = imageBox.Bitmap.PixelSize.Height;
                        }

                        rowContent.Add(imageBox);
                    }
                    else
                    {
                        Label label = new Label(directWriteFactory,
                                                PlayerEntry.PropertyInfos[column.FieldName].GetValue(playerEntry).ToString(),
                                                FormFonts.NormalTextFont,
                                                textColor,
                                                x + UniverseTeamTable.PADDING + columnWidth,
                                                y,
                                                width, height);

                        disposables.Add(label);

                        if (label.TextLayout.Metrics.Height > Height)
                        {
                            Height = label.TextLayout.Metrics.Height;
                        }

                        rowContent.Add(label);
                    }

                    columnWidth += column.Width;
                }
            }
            catch
            { }

            rowLine = new Line(new Vector2(x + UniverseTeamTable.PADDING, y + Height), new Vector2(x - UniverseTeamTable.PADDING + Width, y + Height), textColor);
        }
Example #30
0
 public Renderer()
 {
     D2DFactory  = new D2DFactory();
     FontFactory = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
     fonts       = new Dictionary <FontDescription, TextFormat>();
     brushes     = new Dictionary <BrushDescription, Brush>();
     circles     = new Dictionary <int, Vector2[]>();
 }
Example #31
0
 //public static Brush TEXT_BRUSH;
 public static void Initialize(RenderTarget g)
 {
     SCBRUSH_RED = new SolidColorBrush(g, Color.Red);
     SCBRUSH_BLACK = new SolidColorBrush(g, Color.Black);
     WRITE_FACTORY = new SharpDX.DirectWrite.Factory();
     TEXT_FORMAT = new TextFormat(WRITE_FACTORY, "Arial", 14);
     //TEXT_BRUSH = new SolidColorBrush(g, Color.Red);
 }
Example #32
0
        //public static Brush TEXT_BRUSH;

        public static void Initialize(RenderTarget g)
        {
            SCBRUSH_RED   = new SolidColorBrush(g, Color.Red);
            SCBRUSH_BLACK = new SolidColorBrush(g, Color.Black);
            WRITE_FACTORY = new SharpDX.DirectWrite.Factory();
            TEXT_FORMAT   = new TextFormat(WRITE_FACTORY, "Arial", 14);
            //TEXT_BRUSH = new SolidColorBrush(g, Color.Red);
        }
        public static void DrawSimpleTip(this MusicCanvasControl canvas, string text, RawVector2?pos = new RawVector2?())
        {
            if (MusicCanvasControl.EnableControlTip && canvas.IsAltKeyPressed())
            {
                Trimming     trimming;
                InlineObject obj2;
                if (!pos.HasValue)
                {
                    Point point = canvas.PointToClient(Control.MousePosition);
                    pos = new RawVector2((float)(point.X + 0x18), (float)(point.Y - 0x18));
                }
                RenderTarget renderTarget = canvas.RenderTarget2D;
                SharpDX.DirectWrite.Factory factoryDWrite = canvas.FactoryDWrite;
                TextFormat textFormat = new TextFormat(factoryDWrite, "微软雅黑", FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, FontStretch.Normal, 12f);
                textFormat.GetTrimming(out trimming, out obj2);
                trimming.Granularity = TrimmingGranularity.Word;
                textFormat.SetTrimming(trimming, obj2);
                textFormat.TextAlignment      = TextAlignment.Center;
                textFormat.ParagraphAlignment = ParagraphAlignment.Center;
                TextLayout layout = new TextLayout(factoryDWrite, text, textFormat, 1920f, 1080f);
                textFormat.TextAlignment      = TextAlignment.Leading;
                textFormat.ParagraphAlignment = ParagraphAlignment.Far;
                TextLayout textLayout = new TextLayout(factoryDWrite, text, textFormat, layout.Metrics.Width, layout.Metrics.Height);
                layout.Dispose();
                RawVector2 origin = new RawVector2(pos.Value.X, pos.Value.Y);
                switch (textFormat.TextAlignment)
                {
                case TextAlignment.Trailing:
                    origin.X = pos.Value.X - textLayout.Metrics.Width;
                    break;

                case TextAlignment.Center:
                case TextAlignment.Justified:
                    origin.X = pos.Value.X - (textLayout.Metrics.Width / 2f);
                    break;
                }
                switch (textFormat.ParagraphAlignment)
                {
                case ParagraphAlignment.Far:
                    origin.Y = pos.Value.Y - textLayout.Metrics.Height;
                    break;

                case ParagraphAlignment.Center:
                    origin.Y = pos.Value.Y - (textLayout.Metrics.Height / 2f);
                    break;
                }
                origin.X += 4f;
                origin.Y += 4f;
                textFormat.Dispose();
                RawRectangleF rectF = new RawRectangleF(pos.Value.X, pos.Value.Y - textLayout.Metrics.Height, (pos.Value.X + textLayout.Metrics.Width) + 8f, pos.Value.Y + 8f);
                canvas.FillRoundedRectangle(rectF, 4f, Color.FromArgb(150, 0x1f, 0x1f, 0x22));
                canvas.DrawRoundedRectangle(rectF, 4f, Color.FromArgb(150, 0xe9, 0xe9, 0xe9), 2f);
                SolidColorBrush defaultForegroundBrush = new SolidColorBrush(renderTarget, Color.FromArgb(250, Color.DarkGray).ToRawColor4(1f));
                renderTarget.DrawTextLayout(origin, textLayout, defaultForegroundBrush, DrawTextOptions.Clip);
                defaultForegroundBrush.Dispose();
                textLayout.Dispose();
            }
        }
Example #34
0
        public void Initialize(Presenter presenter)
        {
            // https://msdn.microsoft.com/en-us/library/windows/desktop/mt186590(v=vs.85).aspx
            Presenter  = presenter;
            Device3D11 = Device3D11.CreateFromDirect3D12(
                Device.NativeDevice,
                DeviceCreationFlags.BgraSupport,// | DeviceCreationFlags.Debug,
                null,
                null,
                presenter.NativeCommandQueue);

            DeviceContext3D = Device3D11.ImmediateContext;
            Device3D        = Device3D11.QueryInterface <Device3D>();

            // create d2d/directwrite
            using (var factory = new Factory(FactoryType.SingleThreaded))
            {
                Factory = factory.QueryInterface <Factory1>();
            }


            RoundedRectangleGeometry = new RoundedRectangleGeometry(
                Factory,
                new RoundedRectangle()
            {
                RadiusX = 32,
                RadiusY = 32,
                Rect    = new RectangleF(128, 128, 500 - 128 * 2, 500 - 128 * 2)
            });


            // direct write
            FactoryDW      = new FactoryDW(SharpDX.DirectWrite.FactoryType.Shared);
            FontLoader     = new ResourceFontLoader(FactoryDW, @"Fonts");
            FontCollection = new FontCollection(FactoryDW, FontLoader, FontLoader.Key);

            TextFormat = new TextFormat(
                FactoryDW,
                "Material-Design-Iconic-Font",
                FontCollection,
                SharpDX.DirectWrite.FontWeight.Normal,
                FontStyle.Normal,
                FontStretch.Normal,
                30);
            TextFormat.TextAlignment      = TextAlignment.Leading;
            TextFormat.ParagraphAlignment = ParagraphAlignment.Near;

            DeviceContextOptions deviceOptions = DeviceContextOptions.None;

            using (var deviceGI = Device3D.QueryInterface <DeviceGI>())
            {
                Device2D      = new Device(Factory, deviceGI);
                DeviceContext = new DeviceContext(Device2D, deviceOptions);
            }

            DesktopDpi = Factory.DesktopDpi;
            InitializePresentable(Device);
        }
Example #35
0
        private bool CheckRender(IntPtr hwnd)
        {
            //window did not change
            if (hwnd == window)
            {
                return(window != IntPtr.Zero); //is not no window
            }
            //window changed do some cleanup of resource attached to old window
            fpsColor?.Dispose();
            fpsFont?.Dispose();
            renderOverlay?.Dispose();
            renderTarget?.Dispose();
            renderTexture?.Dispose();
            renderWindow?.Dispose();
            fpsCounter?.Dispose();
            window = hwnd;

            //window changed to no window
            if (window == IntPtr.Zero)
            {
                return(false);
            }

            //window render init
            using (var factory = adapter.GetParent <Factory2>()) {
                renderWindow = new SwapChain1(factory, device, window, ref renderDescription,
                                              new SwapChainFullScreenDescription()
                {
                    RefreshRate = new Rational(15, 1),
                    Scaling     = DisplayModeScaling.Stretched,
                    Windowed    = true
                }, null);

                factory.MakeWindowAssociation(window, WindowAssociationFlags.IgnoreAll);
            }

            renderTexture = Texture2D.FromSwapChain <Texture2D>(renderWindow, 0);
            renderTarget  = new RenderTargetView(device, renderTexture);

            //overlay init
            using (var surface = renderWindow.GetBackBuffer <Surface>(0))
                using (var factory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded))
                    renderOverlay = new RenderTarget(factory, surface, new RenderTargetProperties()
                    {
                        Type        = RenderTargetType.Default,
                        PixelFormat = new D2DPixelFormat(Format.B8G8R8A8_UNorm, D2DAlphaMode.Premultiplied)
                    })
                    {
                        TextAntialiasMode = TextAntialiasMode.Cleartype
                    };

            using (var factory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared))
                fpsFont = new TextFormat(factory, "Calibri", FontWeight.Bold, FontStyle.Normal, 18);

            fpsColor   = new SolidColorBrush(renderOverlay, new Color4(1f, 0f, 1f, 0.7f));
            fpsCounter = new AvgFPSCounter();
            return(true);
        }
Example #36
0
 public EngineInfoDrawer(RenderTarget renderTarget)
 {
     var factory = new DW.Factory(DW.FactoryType.Shared);
     defaultBrush = new SolidColorBrush(renderTarget, Color.Black);
     defaultTextFormat = new TextFormat(factory, "Microsoft Yahei Mono", FONT_SIZE);
     defaultRectangleFList = new RectangleF[MAX_ROW_COUNT];
     for (int i = 0; i < MAX_ROW_COUNT; i++) {
         defaultRectangleFList[i] = new RectangleF(0, i * FONT_SIZE, ROW_WEIGHT, FONT_SIZE);
     }
 }
Example #37
0
        public DeviceManager()
        {
            var device = new D3D11.Device(
                D3D.DriverType.Hardware,
                /*DeviceCreationFlags.Debug |*/ D3D11.DeviceCreationFlags.BgraSupport);

            DeviceContext = device.ImmediateContext;
            Direct2dFactory = new D2D.Factory();
            DirectWriteFactory = new DW.Factory();
        }
Example #38
0
        internal AssetManager(RenderTarget renderTarget2D)
            : base()
        {
            Debug.Assert(renderTarget2D != null, "RenderTarget should not be null");

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

            _renderTarget2D = renderTarget2D;
            _dwriteFactory = new DWriteFactory();
            _singleton = this;
            _loadFontResources();
            IsDisposed = false;
        }
Example #39
0
        public void Import(SpriteFontAsset options, List<char> characters)
        {
            var factory = new Factory();

            // try to get the font face from the source file if not null
            FontFace fontFace = !string.IsNullOrEmpty(options.Source) ? GetFontFaceFromSource(factory, options) : GetFontFaceFromSystemFonts(factory, options);
            
            var fontMetrics = fontFace.Metrics;

            // Create a bunch of GDI+ objects.
            var fontSize = FontHelper.PointsToPixels(options.Size);

            var glyphList = new List<Glyph>();

            // Remap the LineMap coming from the font with a user defined remapping
            // Note:
            // We are remapping the lineMap to allow to shrink the LineGap and to reposition it at the top and/or bottom of the 
            // font instead of using only the top
            // According to http://stackoverflow.com/questions/13939264/how-to-determine-baseline-position-using-directwrite#comment27947684_14061348
            // (The response is from a MSFT employee), the BaseLine should be = LineGap + Ascent but this is not what
            // we are experiencing when comparing with MSWord (LineGap + Ascent seems to offset too much.)
            //
            // So we are first applying a factor to the line gap:
            //     NewLineGap = LineGap * LineGapFactor
            var lineGap = fontMetrics.LineGap * options.LineGapFactor;

            // Store the font height.
            LineSpacing = (float)(lineGap + fontMetrics.Ascent + fontMetrics.Descent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // And then the baseline is also changed in order to allow the linegap to be distributed between the top and the 
            // bottom of the font:
            //     BaseLine = NewLineGap * LineGapBaseLineFactor
            BaseLine = (float)(lineGap * options.LineGapBaseLineFactor + fontMetrics.Ascent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // Rasterize each character in turn.
            foreach (var character in characters)
                glyphList.Add(ImportGlyph(factory, fontFace, character, fontMetrics, fontSize, options.AntiAlias));

            Glyphs = glyphList;

            factory.Dispose();
        }
        public override string GetFontPath(AssetCompilerResult result = null)
        {
            using (var factory = new Factory())
            {
                Font font;

                using (var fontCollection = factory.GetSystemFontCollection(false))
                {
                    int index;
                    if (!fontCollection.FindFamilyName(FontName, out index))
                    {
                        result?.Error("Cannot find system font '{0}'. Make sure it is installed on this machine.", FontName);
                        return null;
                    }

                    using (var fontFamily = fontCollection.GetFontFamily(index))
                    {
                        var weight = Style.IsBold() ? FontWeight.Bold : FontWeight.Regular;
                        var style = Style.IsItalic() ? SharpDX.DirectWrite.FontStyle.Italic : SharpDX.DirectWrite.FontStyle.Normal;
                        font = fontFamily.GetFirstMatchingFont(weight, FontStretch.Normal, style);
                        if (font == null)
                        {
                            result?.Error("Cannot find style '{0}' for font family {1}. Make sure it is installed on this machine.", Style, FontName);
                            return null;
                        }
                    }
                }

                var fontFace = new FontFace(font);

                // get the font path on the hard drive
                var file = fontFace.GetFiles().First();
                var referenceKey = file.GetReferenceKey();
                var originalLoader = (FontFileLoaderNative)file.Loader;
                var loader = originalLoader.QueryInterface<LocalFontFileLoader>();
                return loader.GetFilePath(referenceKey);
            }
        }
        public Direct2DRenderer(IntPtr hwnd, bool limitFps)
        {
            _factory = new Factory();

            _fontFactory = new FontFactory();

            RECT bounds;//immer 1920x1080. resizing muss durch die Overlay klasse geregelt sein
            NativeMethods.GetWindowRect(hwnd, out bounds);

            var targetProperties = new HwndRenderTargetProperties
            {
                Hwnd = hwnd,
                PixelSize = new Size2(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top),
                PresentOptions = limitFps ? PresentOptions.None : PresentOptions.Immediately //Immediatly -> Zeichnet sofort ohne auf 60fps zu locken. None lockt auf 60fps
            };

            var prop = new RenderTargetProperties(RenderTargetType.Hardware, new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);

            _device = new WindowRenderTarget(_factory, prop, targetProperties)
            {
                TextAntialiasMode = TextAntialiasMode.Cleartype,
                AntialiasMode = AntialiasMode.PerPrimitive
            };
        }
        /// <inheritdoc/>
        public override FontFace GetFontFace()
        {
            var factory = new Factory();

            SharpDX.DirectWrite.Font font;
            using (var fontCollection = factory.GetSystemFontCollection(false))
            {
                int index;
                if (!fontCollection.FindFamilyName(FontName, out index))
                {
                    // Lets try to import System.Drawing for old system bitmap fonts (like MS Sans Serif)
                    throw new FontNotFoundException(FontName);
                }

                using (var fontFamily = fontCollection.GetFontFamily(index))
                {
                    var weight = Style.IsBold() ? FontWeight.Bold : FontWeight.Regular;
                    var style = Style.IsItalic() ? SharpDX.DirectWrite.FontStyle.Italic : SharpDX.DirectWrite.FontStyle.Normal;
                    font = fontFamily.GetFirstMatchingFont(weight, FontStretch.Normal, style);
                }
            }

            return new FontFace(font);
        }
Example #43
0
        public static List<InstalledFont> GetFonts()
        {
            var fontList = new List<InstalledFont>();

            var factory = new Factory();
            var fontCollection = factory.GetSystemFontCollection(false);
            var familyCount = fontCollection.FontFamilyCount;

            for (int i = 0; i < familyCount; i++)
            {
                var fontFamily = fontCollection.GetFontFamily(i);
                var familyNames = fontFamily.FamilyNames;
                int index;

                if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out index))
                {
                    if (!familyNames.FindLocaleName("en-us", out index))
                    {
                        index = 0;
                    }
                }

                bool isSymbolFont = fontFamily.GetFont(index).IsSymbolFont;

                string name = familyNames.GetString(index);
                fontList.Add(new InstalledFont()
                {
                    Name = name,
                    FamilyIndex = i,
                    Index = index,
                    IsSymbolFont = isSymbolFont
                });
            }

            return fontList;
        }
Example #44
0
        public List<Character> GetCharacters()
        {
            var factory = new Factory();
            var fontCollection = factory.GetSystemFontCollection(false);
            var fontFamily = fontCollection.GetFontFamily(FamilyIndex);

            var font = fontFamily.GetFont(Index);

            var characters = new List<Character>();
            var count = 65535;
            for (var i = 0; i < count; i++)
            {
                if (font.HasCharacter(i))
                {
                    characters.Add(new Character()
                    {
                        Char = char.ConvertFromUtf32(i),
                        UnicodeIndex = i
                    });
                }
            }

            return characters;
        }
Example #45
0
        public static MemoryStream Resize(System.IO.Stream source, int maxwidth, int maxheight, Action beforeDrawImage, Action afterDrawImage)
        {
            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Warp,
                                                              d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.SingleThreaded | d3d.DeviceCreationFlags.PreventThreadingOptimizations);

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

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

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

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

            var dwFactory = new dw.Factory();

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

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

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

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

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

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

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

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

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

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

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

            var ms = new MemoryStream();

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

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

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

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

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

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

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            formatConverter.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();
            return ms;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceFontFileEnumerator"/> class.
 /// </summary>
 /// <param name="factory">The factory.</param>
 /// <param name="loader">The loader.</param>
 /// <param name="key">The key.</param>
 public ResourceFontFileEnumerator(Factory factory, FontFileLoader loader, DataPointer key)
 {
     _factory = factory;
     _loader = loader;
     keyStream = new DataStream(key.Pointer, key.Size, true, false);
 }
Example #47
0
 private void InitFont()
 {
     var directWriteFactory = new SharpDX.DirectWrite.Factory();
     _directWriteTextFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, _fontName, _fontSize) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near };
     _directWriteFontColor = new SharpDX.Direct2D1.SolidColorBrush(_direct2DRenderTarget, _fontColor);
     directWriteFactory.Dispose();
 }
Example #48
0
        /// <summary>
        /// Inits the direct2D and direct write.
        /// </summary>
        private void InitDirect2DAndDirectWrite()
        {
            Factory2D = new SharpDX.Direct2D1.Factory();
            FactoryDWrite = new SharpDX.DirectWrite.Factory();

            var properties = new HwndRenderTargetProperties();
            properties.Hwnd = renderControl.Handle;
            properties.PixelSize = new Size2(renderControl.ClientSize.Width, renderControl.ClientSize.Height);
            properties.PresentOptions = PresentOptions.None;

            RenderTarget2D = new WindowRenderTarget(Factory2D, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)), properties);
            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;
            RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;

            SceneColorBrush = new SolidColorBrush(RenderTarget2D, Color.Black);

            renderControl.Paint += new PaintEventHandler(renderControl_Paint);
            renderControl.Resize += new EventHandler(renderControl_Resize);
        }
Example #49
0
        private void LoadFonts()
        {
            Task.Run(() =>
                {
                    var x = new List<string>();
                    var factory = new Factory();
                    FontCollection fontCollection = factory.GetSystemFontCollection(false);
                    int familyCount = fontCollection.FontFamilyCount;
                    for (int i = 0; i < familyCount; i++)
                    {
                        FontFamily fontFamily = fontCollection.GetFontFamily(i);
                        LocalizedStrings familyNames = fontFamily.FamilyNames;
                        int index;
                        if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out index))
                            familyNames.FindLocaleName("en-us", out index);

                        string name = familyNames.GetString(index);
                        x.Add(name);
                    }
                    Fonts = new ObservableCollection<string>(x.OrderBy(y => y));
                });
        }
Example #50
0
        static void Main(string[] args)
        {
            mainForm = new RenderForm("Advanced Text rendering demo");

            d2dFactory = new D2DFactory();
            dwFactory = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            
            textRenderer = new CustomColorRenderer();

            CreateResources();

            var bgcolor = new Color4(0.1f,0.1f,0.1f,1.0f);

            //This is the offset where we start our text layout
            Vector2 offset = new Vector2(202.0f,250.0f);

            textFormat = new TextFormat(dwFactory, "Arial", FontWeight.Regular, FontStyle.Normal, 16.0f);
            textLayout = new TextLayout(dwFactory, introText, textFormat, 300.0f, 200.0f);

            //Apply various modifications to text
            textLayout.SetUnderline(true, new TextRange(0, 5));
            textLayout.SetDrawingEffect(greenBrush, new TextRange(10, 20));
            textLayout.SetFontSize(24.0f, new TextRange(6, 4));
            textLayout.SetFontFamilyName("Comic Sans MS", new TextRange(11,7));

            //Measure full layout
            var textSize = textLayout.Metrics;
            fullTextBackground = new RectangleF(textSize.Left + offset.X, textSize.Top + offset.Y, textSize.Width, textSize.Height);

            //Measure text to apply background to
            var metrics = textLayout.HitTestTextRange(53, 4, 0.0f, 0.0f)[0];
            textRegionRect = new RectangleF(metrics.Left + offset.X, metrics.Top + offset.Y, metrics.Width, metrics.Height);

            //Assign render target and brush to our custom renderer
            textRenderer.AssignResources(renderTarget, defaultBrush);

            RenderLoop.Run(mainForm, () =>
            {
                renderTarget.BeginDraw();
                renderTarget.Clear(bgcolor);

                renderTarget.FillRectangle(fullTextBackground, backgroundBrush);

                renderTarget.FillRectangle(textRegionRect, redBrush);

                textLayout.Draw(textRenderer, offset.X, offset.Y);

                try
                {
                    renderTarget.EndDraw();
                }
                catch
                {
                    CreateResources();
                }
            });

            d2dFactory.Dispose();
            dwFactory.Dispose();
            renderTarget.Dispose();
        }
Example #51
0
        /// <summary>
        /// Inits the direct2D and direct write.
        /// </summary>
        private void InitDirect2DAndDirectWrite()
        {
            Factory2D = new SharpDX.Direct2D1.Factory();
            FactoryDWrite = new SharpDX.DirectWrite.Factory();

            var properties = new HwndRenderTargetProperties { Hwnd = panel1.Handle, PixelSize = new Size2(panel1.ClientSize.Width, panel1.ClientSize.Height), PresentOptions = PresentOptions.None };

            RenderTarget2D = new WindowRenderTarget(Factory2D, new RenderTargetProperties(), properties)
            {
                AntialiasMode = AntialiasMode.PerPrimitive,
                TextAntialiasMode = TextAntialiasMode.Cleartype
            };

            brush = new SolidColorBrush(RenderTarget2D, Color.Black);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceFontFileEnumerator"/> class.
 /// </summary>
 /// <param name="factory">The factory.</param>
 /// <param name="loader">The loader.</param>
 /// <param name="keyStream">The key stream.</param>
 public ResourceFontFileEnumerator(Factory factory, FontFileLoader loader, DataStream keyStream)
 {
     _factory = factory;
     _loader = loader;
     this.keyStream = keyStream;
 }
 public static void Init()
 {
     factory = new Factory();
     fontFactory = new FontFactory();
     fonts = new Hashtable();
 }
Example #54
0
        /// <summary>
        /// Creates a font file enumerator object that encapsulates a collection of font files. The font system calls back to this interface to create a font collection.
        /// </summary>
        /// <param name="factory">Pointer to the <see cref="SharpDX.DirectWrite.Factory"/> object that was used to create the current font collection.</param>
        /// <param name="collectionKey">A font collection key that uniquely identifies the collection of font files within the scope of the font collection loader being used. The buffer allocated for this key must be at least  the size, in bytes, specified by collectionKeySize.</param>
        /// <returns>
        /// a reference to the newly created font file enumerator.
        /// </returns>
        /// <unmanaged>HRESULT IDWriteFontCollectionLoader::CreateEnumeratorFromKey([None] IDWriteFactory* factory,[In, Buffer] const void* collectionKey,[None] int collectionKeySize,[Out] IDWriteFontFileEnumerator** fontFileEnumerator)</unmanaged>
        FontFileEnumerator FontCollectionLoader.CreateEnumeratorFromKey(Factory factory, DataStream collectionKey)
        {
            var enumerator = new ResourceFontFileEnumerator(factory, this, new DataStream(_keyStream.DataPointer, _keyStream.Length, true,true));
            _enumerators.Add(enumerator);

            return enumerator;
        }
Example #55
0
 // Methods
 public TextSource(string Str, SharpDX.DirectWrite.Factory Factory)
 {
     this._Str = Str;
     this._Factory = Factory;
 }
Example #56
0
        static void Main()
        {
            // input and output files are supposed to be in the program folder
            var inputPath = "Input.png";
            var outputPath = "Output.png";

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

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

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

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

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

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

            var dwFactory = new dw.Factory();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // dispose everything and free used resources

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

            // show the result
            System.Diagnostics.Process.Start(outputPath);
        }
Example #57
0
        private Glyph ImportGlyph(Factory factory, FontFace fontFace, char character, FontMetrics fontMetrics, float fontSize, bool activateAntiAliasDetection)
        {
            var indices = fontFace.GetGlyphIndices(new int[] {character});

            var metrics = fontFace.GetDesignGlyphMetrics(indices, false);
            var metric = metrics[0];

            var width = (float)(metric.AdvanceWidth - metric.LeftSideBearing - metric.RightSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize;
            var height = (float)(metric.AdvanceHeight - metric.TopSideBearing - metric.BottomSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize;

            var xOffset = (float)metric.LeftSideBearing / fontMetrics.DesignUnitsPerEm * fontSize;
            var yOffset = (float)(metric.TopSideBearing - metric.VerticalOriginY) / fontMetrics.DesignUnitsPerEm * fontSize;

            var advanceWidth = (float)(metric.AdvanceWidth) / fontMetrics.DesignUnitsPerEm * fontSize;
            var advanceHeight = (float)(metric.AdvanceHeight) / fontMetrics.DesignUnitsPerEm * fontSize;

            var pixelWidth = (int)Math.Ceiling(width + 2);
            var pixelHeight = (int)Math.Ceiling(height + 2);

            Bitmap bitmap;
            if(char.IsWhiteSpace(character))
            {
                bitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
            }
            else
            {
                var glyphRun = new GlyphRun()
                               {
                                   FontFace = fontFace,
                                   Advances = new[] { (float)Math.Round(advanceWidth) },
                                   FontSize = fontSize,
                                   BidiLevel = 0,
                                   Indices = indices,
                                   IsSideways = false,
                                   Offsets = new[] {new GlyphOffset()}
                               };

                var matrix = SharpDX.Matrix.Identity;
                matrix.M41 = -(float)Math.Floor(xOffset - 1);
                matrix.M42 = -(float)Math.Floor(yOffset - 1);

                RenderingMode renderingMode;
                if (activateAntiAliasDetection)
                {
                    var rtParams = new RenderingParams(factory);
                    renderingMode = fontFace.GetRecommendedRenderingMode(fontSize, 1.0f, MeasuringMode.Natural, rtParams);
                    rtParams.Dispose();
                }
                else
                {
                    renderingMode = RenderingMode.Aliased;
                }

                using(var runAnalysis = new GlyphRunAnalysis(factory,
                    glyphRun,
                    1.0f,
                    matrix,
                    renderingMode,
                    MeasuringMode.Natural,
                    0.0f,
                    0.0f))
                {
                    var bounds = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);
                    bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);

                    if(renderingMode == RenderingMode.Aliased)
                    {
                        var texture = new byte[bounds.Width * bounds.Height];
                        runAnalysis.CreateAlphaTexture(TextureType.Aliased1x1, bounds, texture, texture.Length);
                        bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
                        for (int y = 0; y < bounds.Height; y++)
                        {
                            for (int x = 0; x < bounds.Width; x++)
                            {
                                int pixelX = y * bounds.Width + x;
                                var grey = texture[pixelX];
                                var color = Color.FromArgb(grey, grey, grey);

                                bitmap.SetPixel(x, y, color);
                            }
                        }
                    }
                    else
                    {
                        var texture = new byte[bounds.Width * bounds.Height * 3];
                        runAnalysis.CreateAlphaTexture(TextureType.Cleartype3x1, bounds, texture, texture.Length);
                        for (int y = 0; y < bounds.Height; y++)
                        {
                            for (int x = 0; x < bounds.Width; x++)
                            {
                                int pixelX = (y * bounds.Width + x) * 3;
                                var red = texture[pixelX];
                                var green = texture[pixelX + 1];
                                var blue = texture[pixelX + 2];
                                var color = Color.FromArgb(red, green, blue);

                                bitmap.SetPixel(x, y, color);
                            }
                        }
                    }

                    //var positionUnderline = (float)fontMetrics.UnderlinePosition / fontMetrics.DesignUnitsPerEm * fontSize;
                    //var positionUnderlineSize = (float)fontMetrics.UnderlineThickness / fontMetrics.DesignUnitsPerEm * fontSize;
                }
            }

            var glyph = new Glyph(character, bitmap)
                        {
                            XOffset = (float)Math.Floor(xOffset-1),
                            XAdvance = (float)Math.Round(advanceWidth),
                            YOffset = (float)Math.Floor(yOffset-1),
                        };
            return glyph;
        }
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

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

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

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

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

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

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

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

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

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

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

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

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush = new SolidColorBrush(d2dContext, Color.Black);
        }
Example #59
0
 public MainGame()
 {
     FactoryDWrite = new SharpDX.DirectWrite.Factory();
     TextFormat = new TextFormat(FactoryDWrite, "Arial", 32) { TextAlignment = TextAlignment.Leading, ParagraphAlignment = ParagraphAlignment.Center };
     _scoreApi = new ScoreClient();
 }
Example #60
0
        /// <summary>
        /// Creates a font file enumerator object that encapsulates a collection of font files. The font system calls back to this interface to create a font collection.
        /// </summary>
        /// <param name="factory">Pointer to the <see cref="SharpDX.DirectWrite.Factory"/> object that was used to create the current font collection.</param>
        /// <param name="collectionKey">A font collection key that uniquely identifies the collection of font files within the scope of the font collection loader being used. The buffer allocated for this key must be at least  the size, in bytes, specified by collectionKeySize.</param>
        /// <returns>
        /// a reference to the newly created font file enumerator.
        /// </returns>
        /// <unmanaged>HRESULT IDWriteFontCollectionLoader::CreateEnumeratorFromKey([None] IDWriteFactory* factory,[In, Buffer] const void* collectionKey,[None] int collectionKeySize,[Out] IDWriteFontFileEnumerator** fontFileEnumerator)</unmanaged>
        FontFileEnumerator FontCollectionLoader.CreateEnumeratorFromKey(Factory factory, DataPointer collectionKey)
        {
            var enumerator = new ResourceFontFileEnumerator(factory, this, collectionKey);
            _enumerators.Add(enumerator);

            return enumerator;
        }