diff --git a/src/Avalonia.Base/Rendering/Composition/Server/CompositionTargetOverlays.cs b/src/Avalonia.Base/Rendering/Composition/Server/CompositionTargetOverlays.cs index 52acf4ac33..59414029c2 100644 --- a/src/Avalonia.Base/Rendering/Composition/Server/CompositionTargetOverlays.cs +++ b/src/Avalonia.Base/Rendering/Composition/Server/CompositionTargetOverlays.cs @@ -135,17 +135,16 @@ internal class CompositionTargetOverlays { if (DebugOverlays.HasFlag(RendererDebugOverlays.Fps)) { - var nativeMem = ByteSizeHelper.ToString((ulong)( + var nativeMem = (ulong)( (_target.Compositor.BatchMemoryPool.CurrentUsage + _target.Compositor.BatchMemoryPool.CurrentPool) * - _target.Compositor.BatchMemoryPool.BufferSize), false); - var managedMem = ByteSizeHelper.ToString((ulong)( + _target.Compositor.BatchMemoryPool.BufferSize); + var managedMem = (ulong)( (_target.Compositor.BatchObjectPool.CurrentUsage + _target.Compositor.BatchObjectPool.CurrentPool) * _target.Compositor.BatchObjectPool.ArraySize * - IntPtr.Size), false); + IntPtr.Size); - _oldFpsCounterRect = FpsCounter?.RenderFps(targetContext, - FormattableString.Invariant($"M:{managedMem} / N:{nativeMem} V:{_target.VisitedVisuals:0000} R:{_target.RenderedVisuals:0000}"), - hasLayer, _oldFpsCounterRect); + _oldFpsCounterRect = FpsCounter?.RenderFps(targetContext, managedMem, nativeMem, + _target.VisitedVisuals, _target.RenderedVisuals, hasLayer, _oldFpsCounterRect); } var top = 0.0; diff --git a/src/Avalonia.Base/Rendering/Composition/Server/DiagnosticTextRenderer.cs b/src/Avalonia.Base/Rendering/Composition/Server/DiagnosticTextRenderer.cs index 2c2e3e886b..a9ecfa2d9f 100644 --- a/src/Avalonia.Base/Rendering/Composition/Server/DiagnosticTextRenderer.cs +++ b/src/Avalonia.Base/Rendering/Composition/Server/DiagnosticTextRenderer.cs @@ -5,32 +5,36 @@ namespace Avalonia.Rendering.Composition.Server { /// /// A class used to render diagnostic strings (only!), with caching of ASCII glyph runs. + /// Digits are laid out in equal-width cells so rapidly changing values do not make the text jump around. /// internal sealed class DiagnosticTextRenderer { private const char FirstChar = (char)32; private const char LastChar = (char)126; + private readonly GlyphTypeface _glyphTypeface; + private readonly double _fontRenderingEmSize; private readonly GlyphRun[] _runs = new GlyphRun[LastChar - FirstChar + 1]; + private readonly double[] _digitOffsets = new double[10]; + private readonly double _lineHeight; + private readonly double _digitCellWidth; public double GetMaxHeight() { - var maxHeight = 0.0; - - for (var c = FirstChar; c <= LastChar; c++) - { - var height = _runs[c - FirstChar].Bounds.Height; - if (height > maxHeight) - { - maxHeight = height; - } - } - - return maxHeight; + return _lineHeight; } + /// + /// The width of the cell every digit is centered in. + /// + public double DigitCellWidth => _digitCellWidth; + public DiagnosticTextRenderer(GlyphTypeface glyphTypeface, double fontRenderingEmSize) { + _glyphTypeface = glyphTypeface; + _fontRenderingEmSize = fontRenderingEmSize; + _lineHeight = glyphTypeface.Metrics.LineSpacing * fontRenderingEmSize / glyphTypeface.Metrics.DesignEmHeight; + var chars = new char[LastChar - FirstChar + 1]; for (var c = FirstChar; c <= LastChar; c++) { @@ -39,22 +43,82 @@ namespace Avalonia.Rendering.Composition.Server var glyph = glyphTypeface.CharacterToGlyphMap[c]; _runs[index] = new GlyphRun(glyphTypeface, fontRenderingEmSize, chars.AsMemory(index, 1), new[] { glyph }); } + + // Digits share the width of the widest one so changing values do not shift the text that follows + for (var c = '0'; c <= '9'; c++) + { + _digitCellWidth = Math.Max(_digitCellWidth, _runs[c - FirstChar].Bounds.Width); + } + + for (var digit = 0; digit < _digitOffsets.Length; digit++) + { + _digitOffsets[digit] = (_digitCellWidth - _runs['0' + digit - FirstChar].Bounds.Width) / 2.0; + } + } + + /// + /// Shapes into a single glyph run that can be drawn with + /// without any per-frame measuring or shaping. + /// Glyphs advance by their natural width, so digits are not placed in cells; use + /// for values that change. + /// + public ShapedText Shape(string text) + { + var chars = new char[text.Length]; + var glyphs = new ushort[text.Length]; + + for (var i = 0; i < text.Length; i++) + { + var c = text[i] is >= FirstChar and <= LastChar ? text[i] : ' '; + chars[i] = c; + glyphs[i] = _glyphTypeface.CharacterToGlyphMap[c]; + } + + return new ShapedText(new GlyphRun(_glyphTypeface, _fontRenderingEmSize, chars, glyphs)); + } + + public void DrawShapedText(ImmediateDrawingContext context, ShapedText text, IImmutableBrush foreground) + { + if (text.GlyphRun.GlyphInfos.Count > 0) + context.PlatformImpl.DrawGlyphRun(foreground, text.GlyphRun.PlatformImpl.Item); + } + + /// + /// Draws a non-negative zero padded to digits, + /// each in its own wide cell, without formatting a string. + /// Values that do not fit are clamped to the largest representable value. + /// + public void DrawDigits(ImmediateDrawingContext context, int value, int digitCount, IImmutableBrush foreground) + { + var divisor = 1L; + for (var i = 1; i < digitCount; i++) + divisor *= 10; + + var remaining = Math.Clamp(value, 0, divisor * 10 - 1); + + for (var i = 0; i < digitCount; i++) + { + var digit = (int)(remaining / divisor); + remaining %= divisor; + divisor /= 10; + + using (context.PushPreTransform(Matrix.CreateTranslation(i * _digitCellWidth + _digitOffsets[digit], 0.0))) + context.PlatformImpl.DrawGlyphRun(foreground, _runs['0' + digit - FirstChar].PlatformImpl.Item); + } } public Size MeasureAsciiText(ReadOnlySpan text) { var width = 0.0; - var height = 0.0; foreach (var c in text) { var effectiveChar = c is >= FirstChar and <= LastChar ? c : ' '; var run = _runs[effectiveChar - FirstChar]; - width += run.Bounds.Width; - height = Math.Max(height, run.Bounds.Height); + width += c is >= '0' and <= '9' ? _digitCellWidth : run.Bounds.Width; } - return new Size(width, height); + return new Size(width, _lineHeight); } public void DrawAsciiText(ImmediateDrawingContext context, ReadOnlySpan text, IImmutableBrush foreground) @@ -64,12 +128,36 @@ namespace Avalonia.Rendering.Composition.Server foreach (var c in text) { var effectiveChar = c is >= FirstChar and <= LastChar ? c : ' '; + var charIsNumber = c is >= '0' and <= '9'; var run = _runs[effectiveChar - FirstChar]; - using (context.PushPreTransform(Matrix.CreateTranslation(offset, 0.0))) + + // Center digits inside the fixed-width digit cell + var centeringOffset = charIsNumber ? (_digitCellWidth - run.Bounds.Width) / 2.0 : 0.0; + + using (context.PushPreTransform(Matrix.CreateTranslation(offset + centeringOffset, 0.0))) context.PlatformImpl.DrawGlyphRun(foreground, run.PlatformImpl.Item); - offset += run.Bounds.Width; + + offset += charIsNumber ? _digitCellWidth : run.Bounds.Width; + } + + } + + /// + /// A piece of text shaped once by . + /// + public sealed class ShapedText : IDisposable + { + internal ShapedText(GlyphRun glyphRun) + { + GlyphRun = glyphRun; + Width = glyphRun.Bounds.Width; } + internal GlyphRun GlyphRun { get; } + + public double Width { get; } + + public void Dispose() => GlyphRun.Dispose(); } } } diff --git a/src/Avalonia.Base/Rendering/Composition/Server/FpsCounter.cs b/src/Avalonia.Base/Rendering/Composition/Server/FpsCounter.cs index 81f41e3a42..225c80d5fd 100644 --- a/src/Avalonia.Base/Rendering/Composition/Server/FpsCounter.cs +++ b/src/Avalonia.Base/Rendering/Composition/Server/FpsCounter.cs @@ -4,17 +4,37 @@ using System.Globalization; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Platform; +using Avalonia.Utilities; namespace Avalonia.Rendering.Composition.Server; /// -/// An FPS counter helper that can draw itself on the render thread +/// An FPS counter helper that can draw itself on the render thread. +/// The labels are shaped once and the changing numbers are drawn in a fixed digit grid, +/// so a frame neither formats nor measures any text. /// internal class FpsCounter { + private const int FrameDigits = 8; + private const int FpsDigits = 3; + private const int VisualDigits = 5; + + private static readonly ImmutableSolidColorBrush s_layerBrush = new(Colors.Black, 0.5); + private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); private readonly DiagnosticTextRenderer _textRenderer; + private readonly DiagnosticTextRenderer.ShapedText _frameLabel; + private readonly DiagnosticTextRenderer.ShapedText _fpsLabel; + private readonly DiagnosticTextRenderer.ShapedText _visitedLabel; + private readonly DiagnosticTextRenderer.ShapedText _renderedLabel; + private readonly double _digitsWidth; + private readonly double _lineHeight; + + private DiagnosticTextRenderer.ShapedText _memoryText; + private ulong _managedBytes; + private ulong _nativeBytes; + private double _textWidth; private int _framesThisSecond; private int _totalFrames; @@ -22,12 +42,23 @@ internal class FpsCounter private TimeSpan _lastFpsUpdate; public FpsCounter(DiagnosticTextRenderer textRenderer) - => _textRenderer = textRenderer; + { + _textRenderer = textRenderer; + _frameLabel = textRenderer.Shape("Frame #"); + _fpsLabel = textRenderer.Shape(" FPS: "); + _visitedLabel = textRenderer.Shape(" V:"); + _renderedLabel = textRenderer.Shape(" R:"); + _digitsWidth = (FrameDigits + FpsDigits + 2 * VisualDigits) * textRenderer.DigitCellWidth; + _lineHeight = textRenderer.GetMaxHeight(); + _memoryText = CreateMemoryText(); + UpdateTextWidth(); + } public void FpsTick() => _framesThisSecond++; - public Rect? RenderFps(ImmediateDrawingContext context, string aux, bool hasLayer, Rect? oldRect) + public Rect? RenderFps(ImmediateDrawingContext context, ulong managedBytes, ulong nativeBytes, + int visitedVisuals, int renderedVisuals, bool hasLayer, Rect? oldRect) { var now = _stopwatch.Elapsed; var elapsed = now - _lastFpsUpdate; @@ -42,23 +73,59 @@ internal class FpsCounter _lastFpsUpdate = now; } - var fpsLine = string.Create(CultureInfo.InvariantCulture, $"Frame #{_totalFrames:00000000} FPS: {_fps:000} {aux}"); - - var size = _textRenderer.MeasureAsciiText(fpsLine.AsSpan()); - - + if (managedBytes != _managedBytes || nativeBytes != _nativeBytes) + { + _managedBytes = managedBytes; + _nativeBytes = nativeBytes; + _memoryText.Dispose(); + _memoryText = CreateMemoryText(); + UpdateTextWidth(); + } - var rect = new Rect(0.0, 0.0, size.Width + 3.0, size.Height + 3.0); + var rect = new Rect(0.0, 0.0, _textWidth + 3.0, _lineHeight + 3.0); if (hasLayer && oldRect.HasValue) rect = rect.Union(oldRect.Value); - var layerBr = new ImmutableSolidColorBrush(Colors.Black, 0.5); - context.DrawRectangle(hasLayer ? layerBr : Brushes.Black, null, rect); - _textRenderer.DrawAsciiText(context, fpsLine.AsSpan(), Brushes.White); + context.DrawRectangle(hasLayer ? s_layerBrush : Brushes.Black, null, rect); + + var x = 0.0; + DrawLabel(context, _frameLabel, ref x); + DrawNumber(context, _totalFrames, FrameDigits, ref x); + DrawLabel(context, _fpsLabel, ref x); + DrawNumber(context, _fps, FpsDigits, ref x); + DrawLabel(context, _memoryText, ref x); + DrawLabel(context, _visitedLabel, ref x); + DrawNumber(context, visitedVisuals, VisualDigits, ref x); + DrawLabel(context, _renderedLabel, ref x); + DrawNumber(context, renderedVisuals, VisualDigits, ref x); + return rect; + } + + private void DrawLabel(ImmediateDrawingContext context, DiagnosticTextRenderer.ShapedText text, ref double x) + { + using (context.PushPreTransform(Matrix.CreateTranslation(x, 0.0))) + _textRenderer.DrawShapedText(context, text, Brushes.White); + + x += text.Width; + } + + private void DrawNumber(ImmediateDrawingContext context, int value, int digitCount, ref double x) + { + using (context.PushPreTransform(Matrix.CreateTranslation(x, 0.0))) + _textRenderer.DrawDigits(context, value, digitCount, Brushes.White); + x += digitCount * _textRenderer.DigitCellWidth; } + private DiagnosticTextRenderer.ShapedText CreateMemoryText() + => _textRenderer.Shape(string.Create(CultureInfo.InvariantCulture, + $" M:{ByteSizeHelper.ToString(_managedBytes, false)} / N:{ByteSizeHelper.ToString(_nativeBytes, false)}")); + + private void UpdateTextWidth() + => _textWidth = _frameLabel.Width + _fpsLabel.Width + _visitedLabel.Width + _renderedLabel.Width + + _memoryText.Width + _digitsWidth; + public void Reset() { _framesThisSecond = 0; diff --git a/tests/Avalonia.Base.UnitTests/Rendering/DiagnosticTextRendererTests.cs b/tests/Avalonia.Base.UnitTests/Rendering/DiagnosticTextRendererTests.cs new file mode 100644 index 0000000000..df0b1d203f --- /dev/null +++ b/tests/Avalonia.Base.UnitTests/Rendering/DiagnosticTextRendererTests.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.Generic; +using Avalonia.Headless; +using Avalonia.Media; +using Avalonia.Platform; +using Avalonia.Rendering.Composition.Server; +using Avalonia.UnitTests; +using Moq; +using Xunit; + +namespace Avalonia.Base.UnitTests.Rendering +{ + public class DiagnosticTextRendererTests : TestWithServicesBase + { + private const double EmSize = 12.0; + + [Fact] + public void Digits_Measure_To_The_Same_Width() + { + using (Start()) + { + var renderer = CreateRenderer(); + + var width = renderer.MeasureAsciiText("0".AsSpan()).Width; + + for (var c = '1'; c <= '9'; c++) + { + Assert.Equal(width, renderer.MeasureAsciiText(c.ToString().AsSpan()).Width); + } + + Assert.Equal(width * 3, renderer.MeasureAsciiText("108".AsSpan()).Width); + } + } + + [Fact] + public void Height_Is_The_Scaled_Line_Spacing() + { + using (Start()) + { + var glyphTypeface = Typeface.Default.GlyphTypeface; + var renderer = new DiagnosticTextRenderer(glyphTypeface, EmSize); + var expected = glyphTypeface.Metrics.LineSpacing * EmSize / glyphTypeface.Metrics.DesignEmHeight; + + Assert.Equal(expected, renderer.GetMaxHeight()); + Assert.Equal(expected, renderer.MeasureAsciiText("FPS: 60".AsSpan()).Height); + } + } + + [Fact] + public void Digits_Are_Centered_Inside_The_Digit_Cell() + { + using (Start()) + { + var renderer = CreateRenderer(); + var cellWidth = renderer.MeasureAsciiText("0".AsSpan()).Width; + + // Narrow digits shift to the center of their cell, they must never leave it. + const string digits = "1234567890"; + var drawn = Draw(renderer, digits); + + Assert.Equal(digits.Length, drawn.Count); + + for (var i = 0; i < drawn.Count; i++) + { + var cellStart = i * cellWidth; + var glyphWidth = MeasureGlyph(digits[i]); + + Assert.True(drawn[i] >= cellStart - 1e-6, $"Digit {i} starts before its cell."); + Assert.True(drawn[i] + glyphWidth <= cellStart + cellWidth + 1e-6, $"Digit {i} ends after its cell."); + Assert.Equal(cellStart + (cellWidth - glyphWidth) / 2.0, drawn[i], 6); + } + } + } + + [Fact] + public void Text_After_Digits_Does_Not_Depend_On_The_Digit_Values() + { + using (Start()) + { + var renderer = CreateRenderer(); + + var narrow = Draw(renderer, "111 ms"); + var wide = Draw(renderer, "888 ms"); + + Assert.Equal(narrow.Count, wide.Count); + Assert.Equal(narrow[^1], wide[^1], 6); + } + } + + [Theory] + [InlineData(42, 5, "00042")] + [InlineData(0, 3, "000")] + [InlineData(12345678, 8, "12345678")] + [InlineData(1000, 3, "999")] + [InlineData(-5, 3, "000")] + public void DrawDigits_Matches_Drawing_The_Padded_Text(int value, int digitCount, string expectedText) + { + using (Start()) + { + var renderer = CreateRenderer(); + + var digits = Capture(c => renderer.DrawDigits(c, value, digitCount, Brushes.White)); + var text = Capture(c => renderer.DrawAsciiText(c, expectedText.AsSpan(), Brushes.White)); + + Assert.Equal(text.Count, digits.Count); + + for (var i = 0; i < text.Count; i++) + { + Assert.Same(text[i].Glyph, digits[i].Glyph); + Assert.Equal(text[i].X, digits[i].X, 6); + } + } + } + + [Fact] + public void ShapedText_Is_Measured_Once_And_Drawn_As_A_Single_Run() + { + using (Start()) + { + var renderer = CreateRenderer(); + using var shaped = renderer.Shape(" FPS: "); + + Assert.Equal(renderer.MeasureAsciiText(" FPS: ".AsSpan()).Width, shaped.Width, 6); + Assert.Single(Capture(c => renderer.DrawShapedText(c, shaped, Brushes.White))); + } + } + + [Fact] + public void FpsCounter_Layout_Does_Not_Depend_On_The_Numbers() + { + using (Start()) + { + var counter = new FpsCounter(CreateRenderer()); + var rects = new List(); + + var first = Capture(c => rects.Add(counter.RenderFps(c, 1000, 1000, 1, 1, false, null))); + var second = Capture(c => rects.Add(counter.RenderFps(c, 1000, 1000, 99999, 88888, false, null))); + + Assert.Equal(rects[0], rects[1]); + Assert.Equal(first.Count, second.Count); + + // Labels, and every digit cell, stay where they were no matter which digits are shown. + for (var i = 0; i < first.Count; i++) + { + if (first[i].Glyph.Equals(second[i].Glyph)) + Assert.Equal(first[i].X, second[i].X, 6); + } + } + } + + private static double MeasureGlyph(char c) + { + var glyphTypeface = Typeface.Default.GlyphTypeface; + var glyph = glyphTypeface.CharacterToGlyphMap[c]; + return new GlyphRun(glyphTypeface, EmSize, c.ToString().AsMemory(), new[] { glyph }).Bounds.Width; + } + + private static DiagnosticTextRenderer CreateRenderer() + => new(Typeface.Default.GlyphTypeface, EmSize); + + private static List Draw(DiagnosticTextRenderer renderer, string text) + => Capture(context => renderer.DrawAsciiText(context, text.AsSpan(), Brushes.White)).ConvertAll(d => d.X); + + private static List<(double X, IGlyphRunImpl Glyph)> Capture(Action draw) + { + var drawn = new List<(double, IGlyphRunImpl)>(); + var impl = new Mock(); + var transform = Matrix.Identity; + impl.SetupGet(x => x.Transform).Returns(() => transform); + impl.SetupSet(x => x.Transform = It.IsAny()).Callback(m => transform = m); + impl.Setup(x => x.DrawGlyphRun(It.IsAny(), It.IsAny())) + .Callback((_, glyph) => drawn.Add((transform.M31, glyph))); + + using (var context = new ImmediateDrawingContext(impl.Object, false)) + { + draw(context); + } + + return drawn; + } + + private static IDisposable Start() + { + return UnitTestApplication.Start(TestServices.StyledWindow.With( + renderInterface: new HeadlessPlatformRenderInterface())); + } + } +}