diff --git a/LuaScript/LuaScriptEngine.cs b/LuaScript/LuaScriptEngine.cs index 913ecce..76c7ae8 100644 --- a/LuaScript/LuaScriptEngine.cs +++ b/LuaScript/LuaScriptEngine.cs @@ -56,6 +56,13 @@ namespace LuaScript private readonly Dictionary _options = new(StringComparer.Ordinal); private readonly Dictionary _pixelOptions = new(StringComparer.Ordinal); + private TextRenderer? _textRenderer; + private string _fontFamily = string.Empty; + private double _fontSize = 34d; + private bool _fontBold; + private bool _fontItalic; + private int _fontColor = 0xFFFFFF; + private Script? _script; private DynValue? _compiledChunk; private string _lastCompiledCode = string.Empty; @@ -208,6 +215,11 @@ namespace LuaScript _options.Clear(); _pixelOptions.Clear(); + _fontFamily = string.Empty; + _fontSize = 34d; + _fontBold = false; + _fontItalic = false; + _fontColor = 0xFFFFFF; if (isFirstSetup) { @@ -479,18 +491,43 @@ namespace LuaScript obj["load"] = DynValue.NewCallback((_, args) => { _activeCancellation.ThrowIfCancellationRequested(); - if (_activeContext is null || args.Count < 4) - return DynValue.Void; - if (args[0].Type != DataType.String || args[0].String != "figure") + if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String) return DynValue.Void; - string name = args[1].Type == DataType.String ? args[1].String : string.Empty; - int color = (int)(args[2].CastToNumber() ?? 0d); - double size = args[3].CastToNumber() ?? 0d; - double line = args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d; - double aspect = args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d; + switch (args[0].String) + { + case "figure" when args.Count >= 4: + LoadFigure( + args[1].Type == DataType.String ? args[1].String : string.Empty, + (int)(args[2].CastToNumber() ?? 0d), + args[3].CastToNumber() ?? 0d, + args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d, + args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d); + break; + case "text": + LoadText(args.Count > 1 && args[1].Type == DataType.String ? args[1].String : string.Empty); + break; + } + return DynValue.Void; + }); - LoadFigure(name, color, size, line, aspect); + obj["setfont"] = DynValue.NewCallback((_, args) => + { + _activeCancellation.ThrowIfCancellationRequested(); + if (args.Count == 0) + return DynValue.Void; + if (args[0].Type == DataType.String) + _fontFamily = args[0].String; + if (args.Count > 1) + _fontSize = args[1].CastToNumber() ?? _fontSize; + if (args.Count > 2) + { + int type = (int)(args[2].CastToNumber() ?? 0d); + _fontBold = (type & 1) != 0; + _fontItalic = (type & 2) != 0; + } + if (args.Count > 3) + _fontColor = (int)(args[3].CastToNumber() ?? _fontColor); return DynValue.Void; }); @@ -641,6 +678,16 @@ namespace LuaScript RefreshObjDimensions(); } + private void LoadText(string text) + { + _textRenderer ??= new TextRenderer(); + var buffer = _textRenderer.Render( + text, _fontFamily, _fontSize, _fontBold, _fontItalic, _fontColor, + out int w, out int h); + _activeContext!.ReplaceBuffer(buffer, w, h); + RefreshObjDimensions(); + } + private void RefreshObjDimensions() { int w = _activeContext!.ImageWidth; @@ -709,6 +756,7 @@ namespace LuaScript _disposeRequested = true; _workSignal.Release(); _thread.Join(); + _textRenderer?.Dispose(); _cts.Cancel(); _cts.Dispose(); _workSignal.Dispose(); @@ -722,6 +770,7 @@ namespace LuaScript ThreadPool.QueueUserWorkItem(_ => { _thread.Join(); + _textRenderer?.Dispose(); _cts.Dispose(); _workSignal.Dispose(); _doneSignal.Dispose(); diff --git a/LuaScript/TextRenderer.cs b/LuaScript/TextRenderer.cs new file mode 100644 index 0000000..841695f --- /dev/null +++ b/LuaScript/TextRenderer.cs @@ -0,0 +1,97 @@ +using System; +using System.Numerics; +using Vortice.Direct2D1; +using Vortice.DirectWrite; +using Vortice.Mathematics; +using Vortice.WIC; + +namespace LuaScript +{ + internal sealed class TextRenderer : IDisposable + { + private const int MaxDimension = 8192; + private const string FallbackFamily = "Yu Gothic UI"; + + private ID2D1Factory? _d2dFactory; + private IWICImagingFactory? _wicFactory; + private IDWriteFactory? _dwriteFactory; + + private void EnsureFactories() + { + _d2dFactory ??= D2D1.D2D1CreateFactory( + Vortice.Direct2D1.FactoryType.MultiThreaded, DebugLevel.None); + _wicFactory ??= new IWICImagingFactory(); + _dwriteFactory ??= DWrite.DWriteCreateFactory( + Vortice.DirectWrite.FactoryType.Shared); + } + + public unsafe byte[] Render( + string text, string fontFamily, double fontSize, + bool bold, bool italic, int colorRgb, + out int width, out int height) + { + width = 1; + height = 1; + if (string.IsNullOrEmpty(text)) + return new byte[4]; + + EnsureFactories(); + + float size = (float)Math.Clamp(fontSize, 1d, 4096d); + using var format = _dwriteFactory!.CreateTextFormat( + string.IsNullOrWhiteSpace(fontFamily) ? FallbackFamily : fontFamily, + null, + bold ? FontWeight.Bold : FontWeight.Normal, + italic ? FontStyle.Italic : FontStyle.Normal, + FontStretch.Normal, + size, + string.Empty); + + using var layout = _dwriteFactory.CreateTextLayout(text, format, MaxDimension, MaxDimension); + var metrics = layout.Metrics; + int w = Math.Clamp((int)Math.Ceiling(metrics.WidthIncludingTrailingWhitespace), 1, MaxDimension); + int h = Math.Clamp((int)Math.Ceiling(metrics.Height), 1, MaxDimension); + + using var wic = _wicFactory!.CreateBitmap( + w, h, Vortice.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad); + + var properties = new RenderTargetProperties( + RenderTargetType.Default, + new Vortice.DCommon.PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied), + 96f, 96f, + RenderTargetUsage.None, + FeatureLevel.Default); + + float r = ((colorRgb >> 16) & 0xFF) / 255f; + float g = ((colorRgb >> 8) & 0xFF) / 255f; + float b = (colorRgb & 0xFF) / 255f; + + using (var target = _d2dFactory!.CreateWicBitmapRenderTarget(wic, properties)) + { + target.BeginDraw(); + target.Clear(new Color4(0f, 0f, 0f, 0f)); + using (var brush = target.CreateSolidColorBrush(new Color4(r, g, b, 1f))) + target.DrawTextLayout(new Vector2(-metrics.Left, -metrics.Top), layout, brush); + target.EndDraw(); + } + + var buffer = new byte[w * h * 4]; + fixed (byte* p = buffer) + wic.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p); + + width = w; + height = h; + return buffer; + } + + public void Dispose() + { + _dwriteFactory?.Dispose(); + _wicFactory?.Dispose(); + _d2dFactory?.Dispose(); + _dwriteFactory = null; + _wicFactory = null; + _d2dFactory = null; + } + } +}