Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
TextBlock.cs
1using System.Drawing;
2using System.Runtime.CompilerServices;
3using System.Text.RegularExpressions;
10using SkiaSharp;
11
13
43public class TextBlock : DirectDrawingMovableBase
44{
48 public enum VerticalAlign
49 {
52
55
58 }
59
60 #region events
61
66 public event Action<string>? TextRevealed;
67
73 public event Action<string>? TextRevealComplete;
74
75 #endregion events
76
77 private string _text = string.Empty;
78 private readonly List<string> _lines = new();
79 private float _lineHeight;
80 private bool _layoutDirty = true;
81
82 private SKColor _foreColor = SKColors.White;
83 private SKColor _backColor = SKColors.Transparent;
84
85 private float _fontSize = 16f;
86 private float? _minFontSize = null;
87 private SKTypeface? _typeface = null;
88
89 private bool _useOutline = false;
90 private bool _wrapText = true;
91 private int? _maxLines = null;
92
93 private bool _useShadow = false;
94 private float _shadowDx = 2f, _shadowDy = 2f;
95 private byte _shadowAlpha = 128;
96 private float _shadowBlurSigma = 1.5f; // 0 = no blur
97
98 private SKTextAlign _hAlign = SKTextAlign.Left;
99 private VerticalAlign _vAlign = VerticalAlign.Top;
100 private float _verticalScrollOffsetPx;
101 private float _verticalScrollEndPaddingPx;
102
103 // --- Pulse (text color) ---
104 private bool _pulseTextEnabled;
105 private SKColor _pulseFrom, _pulseTo;
106 private float _pulsePeriodSec = 1f;
107 private PulseWave _pulseWave = PulseWave.Sine;
108
109 // timing
110 private long? _pulseLastTick;
111 private float _timeSec;
112
113 // --- Text reveal animation ---
114 private long _revealLastTick;
115 private TextRevealMode _textRevealMode = TextRevealMode.None;
116 private int _revealCharCount; // how many chars currently visible
117 private int _revealTargetCharCount; // cap (usually Text.Length)
118 private float _revealRate; // cps or wps (depending on mode)
119 private float _revealAccum; // accumulator for dt-based stepping
120
121 // precomputed for word-based reveal
122 private int[]? _wordEndCharIndexes; // end indexes (exclusive) per word
123 private int _wordIndex; // words shown so far
124
125 // Punctuation pause tuning
126 private bool _pauseEnabled = true;
127 private float _pauseLongSec = 0.25f;
128 private float _pauseShortSec = 0.10f;
129
130 // current resolved color used for drawing (defaults to _foreColor)
131 private SKColor _resolvedForeColor;
132
143 private TextBlock(
144 RenderSurfaceHostBase renderSurfaceHost,
146 SceneLayer? sceneLayer,
147 View? view,
148 Rectangle? screenBounds,
149 Rectangle? worldBounds,
150 string? nickname = null)
151 : base(
152 renderSurfaceHost,
153 mode,
154 sceneLayer,
155 view,
156 screenBounds,
157 worldBounds,
158 nickname)
159 {
160 _resolvedForeColor = _foreColor;
161 }
162
171 public TextBlock(
172 RenderSurfaceHostBase renderSurfaceHost,
173 SceneLayer sceneLayer,
174 View? view,
175 Rectangle worldBounds,
176 string? nickname = null)
177 : this(
178 renderSurfaceHost,
180 sceneLayer,
181 view,
182 screenBounds: null,
183 worldBounds: worldBounds,
184 nickname: nickname)
185 {
186 }
187
195 public TextBlock(
196 RenderSurfaceHostBase renderSurfaceHost,
197 View view,
198 Rectangle screenBounds,
199 string? nickname = null)
200 : this(
201 renderSurfaceHost,
203 sceneLayer: null,
204 view: view,
205 screenBounds: screenBounds,
206 worldBounds: null,
207 nickname: nickname)
208 {
209 }
210
214 public float LineSpacingMultiplier { get; set; } = 1.0f;
215
219 public float HorizontalPadding { get; set; } = 0f;
220
224 public float VerticalPadding { get; set; } = 0f;
225
234 {
235 get => _verticalScrollOffsetPx;
236 set
237 {
238 if (!float.IsFinite(value) || value < 0f)
239 throw new ArgumentOutOfRangeException(nameof(value));
240
241 if (Math.Abs(_verticalScrollOffsetPx - value) < 0.001f)
242 return;
243
244 _verticalScrollOffsetPx = value;
245 ForceRefresh();
246 }
247 }
248
257 {
258 get => _verticalScrollEndPaddingPx;
259 set
260 {
261 if (!float.IsFinite(value) || value < 0f)
262 throw new ArgumentOutOfRangeException(nameof(value));
263
264 if (Math.Abs(_verticalScrollEndPaddingPx - value) < 0.001f)
265 return;
266
267 _verticalScrollEndPaddingPx = value;
268 ForceRefresh();
269 }
270 }
271
280 {
281 Rectangle bounds = Mode == DirectDrawingMode.View ? ScreenBounds : WorldBounds;
282 float innerWidth = Math.Max(0f, bounds.Width - HorizontalPadding * 2f);
283 float innerHeight = Math.Max(0f, bounds.Height - VerticalPadding * 2f);
284
285 _typeface ??= SKTypeface.Default;
286
287 using var paint = new SKPaint
288 {
289 Typeface = _typeface,
290 TextSize = _fontSize,
291 TextAlign = _hAlign
292 };
293
294 float fontSize = _fontSize;
295 float minimumFontSize = _minFontSize ?? 0f;
296
297 while (true)
298 {
299 paint.TextSize = fontSize;
300 RebuildLayout(paint, innerWidth);
301
302 int drawableLines = _maxLines.HasValue
303 ? Math.Min(_lines.Count, _maxLines.Value)
304 : _lines.Count;
305
306 float contentHeight = drawableLines * _lineHeight;
307 bool exceedsHeight = contentHeight > innerHeight;
308 bool exceedsWidth = _lines.Any(line => paint.MeasureText(line) > innerWidth);
309
310 if (_minFontSize.HasValue &&
311 (exceedsHeight || exceedsWidth) &&
312 fontSize > minimumFontSize)
313 {
314 fontSize = Math.Max(minimumFontSize, fontSize - 1f);
315 continue;
316 }
317
318 float maximumOffset = Math.Max(0f, contentHeight - innerHeight);
319
320 if (maximumOffset > 0f)
321 maximumOffset += VerticalScrollEndPaddingPx;
322
323 // Measurement may have laid out at an auto-shrunk font size. Force the next draw
324 // to rebuild from the configured font settings rather than reusing measurement state.
325 _layoutDirty = true;
326 return maximumOffset;
327 }
328 }
329
336 public TextBlock SetPadding(float horizontal, float vertical)
337 {
338 if (!float.IsFinite(horizontal) || horizontal < 0f)
339 throw new ArgumentOutOfRangeException(nameof(horizontal));
340
341 if (!float.IsFinite(vertical) || vertical < 0f)
342 throw new ArgumentOutOfRangeException(nameof(vertical));
343
344 HorizontalPadding = horizontal;
345 VerticalPadding = vertical;
346 _layoutDirty = true;
347 ForceRefresh();
348 return this;
349 }
350
356 public TextBlock SetSize(Size size)
357 {
358 if (size.Width <= 0 || size.Height <= 0)
359 throw new ArgumentOutOfRangeException(nameof(size), size, "Text block size must be positive.");
360
361 if (Mode == DirectDrawingMode.View)
362 ScreenBounds = new Rectangle(ScreenBounds.Location, size);
363 else
364 WorldBounds = new Rectangle(WorldBounds.Location, size);
365
366 _layoutDirty = true;
367 ForceRefresh();
368 return this;
369 }
370
378 public TextBlock SetText(string text)
379 {
380 _text = text ?? string.Empty;
381 _layoutDirty = true;
382
383 if (_textRevealMode == TextRevealMode.None)
384 {
385 // when not revealing, default to fully visible
386 _revealCharCount = _text.Length;
387 }
388 else
389 {
390 // keep the animation's target in sync with the new text
391 _revealTargetCharCount = _text.Length;
392
393 // if we had already revealed more than the new length, clamp it
394 if (_revealCharCount > _revealTargetCharCount)
395 _revealCharCount = _revealTargetCharCount;
396
397 // optional: smooth start after text swap
398 _revealAccum = 0f;
399 // if you added a dedicated reveal timer, warm it so first frame doesn't "time-warp"
400 _revealLastTick = 0; // keep this if you're using the separate reveal timer
401 }
402
403 ForceRefresh();
404 return this;
405 }
406
414 public TextBlock SetFont(SKTypeface typeface, float size, float? minSize = null)
415 {
416 _typeface = typeface;
417 _fontSize = size;
418 _minFontSize = minSize;
419 _layoutDirty = true;
420 ForceRefresh();
421 return this;
422 }
423
430 public TextBlock SetColors(SKColor fg, SKColor bg)
431 {
432 _foreColor = fg;
433 _backColor = bg;
434 _resolvedForeColor = fg; // keep resolved in sync
435 ForceRefresh();
436 return this;
437 }
438
445 public TextBlock SetColors(Color fg, Color bg) => SetColors(fg.ToSKColor(), bg.ToSKColor());
446
453 public TextBlock SetAlignment(SKTextAlign h, VerticalAlign v)
454 {
455 _hAlign = h;
456 _vAlign = v;
457 ForceRefresh();
458 return this;
459 }
460
466 public TextBlock UseShadow(bool enable = true)
467 {
468 _useShadow = enable;
469 ForceRefresh();
470 return this;
471 }
472
496 public TextBlock SetShadow(
497 float dx,
498 float dy,
499 byte alpha = 128,
500 float blurSigma = 1.5f)
501 {
502 _shadowDx = dx;
503 _shadowDy = dy;
504 _shadowAlpha = alpha;
505 _shadowBlurSigma = MathF.Max(0f, blurSigma);
506 ForceRefresh();
507 return this;
508 }
509
515 public TextBlock UseOutline(bool enable = true)
516 {
517 _useOutline = enable;
518 ForceRefresh();
519 return this;
520 }
521
527 public TextBlock EnableWrapping(bool enable = true)
528 {
529 _wrapText = enable;
530 _layoutDirty = true;
531 ForceRefresh();
532 return this;
533 }
534
540 public TextBlock SetMaxLines(int? maxLines)
541 {
542 _maxLines = maxLines;
543 ForceRefresh();
544 return this;
545 }
546
556 public TextBlock PulseColor(
557 Color from,
558 Color to,
559 float periodSec,
560 bool enabled = true,
561 bool triangle = false)
562 {
563 _pulseTextEnabled = enabled;
564 _pulseFrom = from.ToSKColor();
565 _pulseTo = to.ToSKColor();
566 _pulsePeriodSec = MathF.Max(0.0001f, periodSec);
567 _pulseWave = triangle ? PulseWave.Triangle : PulseWave.Sine;
568
569 // start from base time; force a redraw
570 _resolvedForeColor = _foreColor;
571 ForceRefresh();
572 return this;
573 }
574
579 public TextBlock StopColorPulse()
580 {
581 _pulseTextEnabled = false;
582 _resolvedForeColor = _foreColor; // restore base
583 ForceRefresh();
584 return this;
585 }
586
596 public TextBlock StartTypewriter(
597 float charsPerSecond,
598 int? maxChars = null,
599 bool enablePauses = true,
600 float longPauseSec = 0.25f,
601 float shortPauseSec = 0.10f)
602 {
603 _textRevealMode = TextRevealMode.CharactersPerSecond;
604 _revealRate = MathF.Max(0f, charsPerSecond);
605 _revealCharCount = 0;
606 _revealTargetCharCount = maxChars.HasValue ? Math.Min(maxChars.Value, _text.Length) : _text.Length;
607 _revealAccum = 0f;
608 _wordEndCharIndexes = null;
609
610 _revealLastTick = 0;
611
612 // punctuation tuning
613 _pauseEnabled = enablePauses;
614 _pauseLongSec = longPauseSec;
615 _pauseShortSec = shortPauseSec;
616
617 ForceRefresh();
618 return this;
619 }
620
629 public TextBlock StartWordReveal(
630 float wordsPerSecond,
631 bool enablePauses = true,
632 float longPauseSec = 0.25f,
633 float shortPauseSec = 0.10f)
634 {
635 _textRevealMode = TextRevealMode.WordsPerSecond;
636 _revealRate = MathF.Max(0f, wordsPerSecond);
637 _revealCharCount = 0;
638 _revealTargetCharCount = _text.Length;
639 _revealAccum = 0f;
640 _wordIndex = 0;
641
642 // split words once; keep trailing punctuation with the word so it reveals naturally
643 // You can refine this regex to match your localization needs.
644 _wordEndCharIndexes = Regex.Matches(_text, @"\S+\s*")
645 .Select(m => m.Index + m.Length)
646 .ToArray();
647
648 _revealLastTick = 0;
649
650 _pauseEnabled = enablePauses;
651 _pauseLongSec = longPauseSec;
652 _pauseShortSec = shortPauseSec;
653
654 ForceRefresh();
655 return this;
656 }
657
665 public TextBlock SetPunctuationPauses(bool enabled, float longPauseSec = 0.25f, float shortPauseSec = 0.10f)
666 {
667 _pauseEnabled = enabled;
668 _pauseLongSec = longPauseSec;
669 _pauseShortSec = shortPauseSec;
670 return this;
671 }
672
678 public TextBlock RevealSetCount(int charCount)
679 {
680 _textRevealMode = TextRevealMode.ManualCount;
681 _revealCharCount = Math.Clamp(charCount, 0, _text.Length);
682 _revealTargetCharCount = _text.Length;
683 ForceRefresh();
684 return this;
685 }
686
691 public TextBlock RevealStop()
692 {
693 _textRevealMode = TextRevealMode.None;
694 _revealCharCount = _text.Length;
695
696 // Fire final events: first the revealed text (full), then the completion event
697 TextRevealed?.Invoke(_text);
698 TextRevealComplete?.Invoke(_text);
699
700 ForceRefresh();
701 return this;
702 }
703
704 private float PauseFor(char c)
705 {
706 if (!_pauseEnabled)
707 return 0f;
708
709 return c switch
710 {
711 '.' or '!' or '?' => _pauseLongSec,
712 ',' or ';' or ':' => _pauseShortSec,
713 _ => 0f
714 };
715 }
716
722 public override void Update(long tick)
723 {
724 if (tick == _lastTick)
725 return;
726
727 // --- PULSE TIMING (independent) ---
728 float dtPulse = 0f;
729
730 if (_pulseLastTick.HasValue)
731 dtPulse = HighResTimer.GetDuration(_pulseLastTick.Value, tick);
732
733 _pulseLastTick = tick;
734
735 if (dtPulse > 0f && dtPulse < 1f)
736 _timeSec += dtPulse;
737
738 if (_pulseTextEnabled)
739 {
740 float t = PulseT(_timeSec, _pulsePeriodSec, _pulseWave);
741 var c = LerpColor(_pulseFrom, _pulseTo, t);
742
743 if (c != _resolvedForeColor)
744 {
745 _resolvedForeColor = c;
746 ForceRefresh();
747 }
748 }
749 else
750 {
751 // keep resolved color at base if not pulsing
752 if (_resolvedForeColor != _foreColor)
753 {
754 _resolvedForeColor = _foreColor;
755 ForceRefresh();
756 }
757 }
758
759 // --- REVEAL TIMING (independent and clamped) ---
760 float dtReveal = 0f;
761
762 if (_revealLastTick == 0)
763 {
764 _revealLastTick = tick; // warm up: first frame uses 0 dt
765 }
766 else
767 {
768 dtReveal = HighResTimer.GetDuration(_revealLastTick, tick);
769 _revealLastTick = tick;
770
771 // Clamp to avoid first-frame "time warp" completing the whole text
772 if (dtReveal > 0.1f)
773 dtReveal = 0.1f; // ~100ms/frame cap
774
775 if (dtReveal < 0f)
776 dtReveal = 0f;
777 }
778
779 // --- Typewriter / word reveal ---
780 if (_textRevealMode == TextRevealMode.CharactersPerSecond)
781 {
782 _revealAccum += dtReveal;
783
784 if (_revealRate > 0f)
785 {
786 int step = (int)(_revealAccum * _revealRate);
787
788 if (step > 0)
789 {
790 _revealAccum -= step / _revealRate;
791
792 int old = _revealCharCount;
793 _revealCharCount = Math.Min(_revealCharCount + step, _revealTargetCharCount);
794
795 // Punctuation pauses for newly revealed chars
796 for (int i = old; i < _revealCharCount; i++)
797 _revealAccum -= PauseFor(_text[i]);
798
799 // Mark dirty + redraw
800 ForceRefresh();
801
802 // Fire TextRevealed with the cumulative revealed text
803 if (_revealCharCount > old)
804 {
805 var revealed = _text.Substring(0, _revealCharCount);
806 TextRevealed?.Invoke(revealed);
807 }
808
809 // If we've reached the target, fire completion (TextRevealed already sent above)
810 if (_revealCharCount >= _revealTargetCharCount)
811 {
812 _textRevealMode = TextRevealMode.None;
813 // Ensure ordering: revealed then complete
814 TextRevealComplete?.Invoke(_text);
815 }
816 }
817 }
818 }
819 else if (_textRevealMode == TextRevealMode.WordsPerSecond && _wordEndCharIndexes is not null)
820 {
821 _revealAccum += dtReveal;
822
823 if (_revealRate > 0f)
824 {
825 int step = (int)(_revealAccum * _revealRate);
826
827 if (step > 0)
828 {
829 _revealAccum -= step / _revealRate;
830
831 int oldCount = _revealCharCount;
832
833 _wordIndex = Math.Min(_wordIndex + step, _wordEndCharIndexes.Length);
834 _revealCharCount = _wordIndex == 0 ? 0 : _wordEndCharIndexes[_wordIndex - 1];
835
836 // Simple frontier pause (cheap). Loop oldCount.._revealCharCount-1 if you want per-char.
837 if (_revealCharCount > 0)
838 _revealAccum -= PauseFor(_text[_revealCharCount - 1]);
839
840 ForceRefresh();
841
842 // Fire TextRevealed with the cumulative revealed text
843 if (_revealCharCount > oldCount)
844 {
845 var revealed = _text.Substring(0, _revealCharCount);
846 TextRevealed?.Invoke(revealed);
847 }
848
849 if (_wordIndex >= _wordEndCharIndexes.Length)
850 {
851 _textRevealMode = TextRevealMode.None;
852 // Ensure ordering: revealed then complete
853 TextRevealComplete?.Invoke(_text);
854 }
855 }
856 }
857 }
858
859 // Let the base advance fade tween and set _lastTick
860 base.Update(tick);
861 }
862
868 protected override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
869 {
870 var canvas = backbuffer.Canvas;
871 var rect = destRectScreen.ToSKRect();
872
873 float zoom = ResolveTextScale(Mode, RenderContext.Current?.ViewportZoom ?? 1f);
874
875 // Scale "pixel-like" adornments with zoom so text behaves like other world-space drawables.
876 float hPad = HorizontalPadding * zoom;
877 float vPad = VerticalPadding * zoom;
878 float shadowDx = _shadowDx * zoom;
879 float shadowDy = _shadowDy * zoom;
880 float shadowBlur = _shadowBlurSigma * zoom;
881 float outlineWidth = 1.5f * zoom;
882
883 // Background
884 if (_backColor.Alpha != 0)
885 {
886 using var bg = new SKPaint { Color = _backColor };
887 canvas.DrawRect(rect, bg);
888 }
889
890 _typeface ??= SKTypeface.Default;
891
892 // Build a paint we can reuse for layout + draw (TEXT SIZE IS IN SCREEN PIXELS)
893 using var paint = new SKPaint
894 {
895 Typeface = _typeface ?? SKTypeface.Default,
896 TextSize = _fontSize * zoom,
897 Color = _resolvedForeColor,
898 IsAntialias = true,
899 IsStroke = false,
900 TextAlign = _hAlign
901 };
902
903 // Auto-shrink: reflow until it fits height (if min size provided)
904 float fontSize = _fontSize * zoom;
905 float minFontSize = _minFontSize.HasValue ? _minFontSize.Value * zoom : 0f;
906
907 float innerW = Math.Max(0, rect.Width - hPad * 2f);
908 float innerH = Math.Max(0, rect.Height - vPad * 2f);
909
910 while (true)
911 {
912 paint.TextSize = fontSize;
913
914 // Rebuild when flagged, and also whenever zoom is in play so wrap/line-height stay correct.
915 if (_layoutDirty || zoom != 1f)
916 RebuildLayout(paint, innerW);
917
918 int drawableLines = _maxLines.HasValue ? Math.Min(_lines.Count, _maxLines.Value) : _lines.Count;
919 float totalH = drawableLines * _lineHeight;
920
921 bool exceedsHeight = totalH > innerH;
922 bool exceedsWidth = _lines.Any(line => paint.MeasureText(line) > innerW);
923
924 if (_minFontSize.HasValue &&
925 (exceedsHeight || exceedsWidth) &&
926 fontSize > minFontSize)
927 {
928 fontSize = Math.Max(minFontSize, fontSize - 1f);
929 _layoutDirty = true;
930
931 if (fontSize <= minFontSize)
932 break;
933
934 continue;
935 }
936
937 break;
938 }
939
940 // Determine how many characters are currently visible (content-driven reveal)
941 int visibleChars = _textRevealMode != TextRevealMode.None
942 ? Math.Clamp(_revealCharCount, 0, _text.Length)
943 : _text.Length;
944
945 // Build the set of lines to draw from the already-laid-out _lines,
946 // truncating at 'visibleChars' so wrapping and alignment still work.
947 List<string> drawLines = new(_lines.Count);
948
949 if (visibleChars <= 0)
950 {
951 // nothing to show
952 }
953 else if (visibleChars >= _text.Length)
954 {
955 drawLines.AddRange(_lines);
956 }
957 else
958 {
959 int remaining = visibleChars;
960
961 foreach (var ln in _lines)
962 {
963 if (remaining <= 0)
964 break;
965
966 if (ln.Length <= remaining)
967 {
968 drawLines.Add(ln);
969 remaining -= ln.Length;
970 }
971 else
972 {
973 drawLines.Add(ln.Substring(0, remaining));
974 remaining = 0;
975 }
976 }
977 }
978
979 bool wasTruncatedByMaxLines = _maxLines.HasValue && drawLines.Count > _maxLines.Value;
980
981 // Apply max-lines cap at draw time
982 int linesToDraw = _maxLines.HasValue ? Math.Min(drawLines.Count, _maxLines.Value) : drawLines.Count;
983
984 if (linesToDraw > 0 && wasTruncatedByMaxLines)
985 {
986 drawLines[linesToDraw - 1] = FitLineWithEllipsis(paint, drawLines[linesToDraw - 1], innerW);
987 }
988
989 // Vertical start (Skia draws at baseline, so apply ascent shift)
990 var fm = paint.FontMetrics;
991 float baselineShift = -fm.Ascent;
992
993 float contentH = linesToDraw * _lineHeight;
994 float maximumScrollOffset = Math.Max(0f, contentH - innerH);
995
996 if (maximumScrollOffset > 0f)
997 maximumScrollOffset += VerticalScrollEndPaddingPx;
998
999 float yStart = maximumScrollOffset > 0f
1000 ? rect.Top + vPad
1001 : _vAlign switch
1002 {
1003 VerticalAlign.Center => rect.Top + vPad + Math.Max(0, (innerH - contentH) * 0.5f),
1004 VerticalAlign.Bottom => rect.Bottom - vPad - contentH,
1005 _ => rect.Top + vPad
1006 };
1007
1008 float scrollOffset = Math.Min(_verticalScrollOffsetPx * zoom, maximumScrollOffset);
1009 yStart -= scrollOffset;
1010
1011 // Horizontal anchor per line
1012 float xAnchorLeft = rect.Left + hPad;
1013 float xAnchorCenter = rect.MidX;
1014 float xAnchorRight = rect.Right - hPad;
1015
1016 canvas.Save();
1017 canvas.ClipRect(rect);
1018
1019 float y = yStart;
1020
1021 for (int i = 0; i < linesToDraw; i++)
1022 {
1023 var line = drawLines[i];
1024
1025 float x = _hAlign switch
1026 {
1027 SKTextAlign.Center => xAnchorCenter,
1028 SKTextAlign.Right => xAnchorRight,
1029 _ => xAnchorLeft
1030 };
1031
1032 if (_useShadow)
1033 {
1034 using var shadow = paint.Clone();
1035 shadow.IsStroke = false;
1036
1037 shadow.MaskFilter = shadowBlur > 0f
1038 ? SKMaskFilter.CreateBlur(SKBlurStyle.Normal, shadowBlur)
1039 : null;
1040
1041 shadow.Color = new SKColor(
1042 0,
1043 0,
1044 0,
1045 _shadowAlpha);
1046
1047 // manually offset
1048 canvas.DrawText(
1049 line,
1050 x + shadowDx,
1051 y + baselineShift + shadowDy,
1052 shadow);
1053 }
1054
1055 if (_useOutline)
1056 {
1057 using var outline = paint.Clone();
1058 outline.IsStroke = true;
1059 outline.StrokeWidth = outlineWidth;
1060 outline.Color = SKColors.Black;
1061
1062 canvas.DrawText(
1063 line,
1064 x,
1065 y + baselineShift,
1066 outline);
1067 }
1068
1069 canvas.DrawText(
1070 line,
1071 x,
1072 y + baselineShift,
1073 paint);
1074
1075 y += _lineHeight;
1076
1077 // safety clip
1078 if (y > rect.Bottom)
1079 break;
1080 }
1081
1082 canvas.Restore();
1083 }
1084
1085 internal static float ResolveTextScale(DirectDrawingMode mode, float viewportZoom)
1086 {
1087 if (mode != DirectDrawingMode.SceneLayer)
1088 return 1f;
1089
1090 return viewportZoom > 0f ? viewportZoom : 1f;
1091 }
1092
1093 private void RebuildLayout(SKPaint paint, float maxWidth)
1094 {
1095 _lines.Clear();
1096
1097 var fm = paint.FontMetrics;
1098 _lineHeight = ((fm.Descent - fm.Ascent) + fm.Leading) * LineSpacingMultiplier;
1099
1100 var paragraphs = _text.Replace("\r\n", "\n").Split('\n');
1101
1102 foreach (var para in paragraphs)
1103 {
1104 if (string.IsNullOrEmpty(para))
1105 {
1106 _lines.Add(string.Empty);
1107 continue;
1108 }
1109
1110 if (!_wrapText)
1111 {
1112 _lines.Add(para);
1113 continue;
1114 }
1115
1116 var words = para.Split(' ', StringSplitOptions.None);
1117 var current = string.Empty;
1118
1119 foreach (var word in words)
1120 {
1121 string candidate = string.IsNullOrEmpty(current) ? word : current + " " + word;
1122 float candidateWidth = paint.MeasureText(candidate);
1123
1124 if (candidateWidth <= maxWidth)
1125 {
1126 current = candidate;
1127 continue;
1128 }
1129
1130 // If current already has content, commit it first and retry this word on a new line.
1131 if (!string.IsNullOrEmpty(current))
1132 {
1133 _lines.Add(current);
1134 current = string.Empty;
1135 }
1136
1137 // If the single word fits on its own line, use it.
1138 if (paint.MeasureText(word) <= maxWidth)
1139 {
1140 current = word;
1141 continue;
1142 }
1143
1144 // Fallback: hard-break an overlong word by character.
1145 var chunk = string.Empty;
1146
1147 foreach (char ch in word)
1148 {
1149 string next = chunk + ch;
1150
1151 if (paint.MeasureText(next) <= maxWidth || string.IsNullOrEmpty(chunk))
1152 {
1153 chunk = next;
1154 }
1155 else
1156 {
1157 _lines.Add(chunk);
1158 chunk = ch.ToString();
1159 }
1160 }
1161
1162 if (!string.IsNullOrEmpty(chunk))
1163 current = chunk;
1164 }
1165
1166 if (!string.IsNullOrEmpty(current))
1167 _lines.Add(current);
1168 }
1169
1170 _layoutDirty = false;
1171 }
1172
1173 [MethodImpl(MethodImplOptions.AggressiveInlining)]
1174 private static float PulseT(float timeSec, float periodSec, PulseWave wave)
1175 {
1176 float phase = (timeSec / periodSec) % 1f;
1177
1178 return wave == PulseWave.Sine
1179 ? 0.5f * (1f + MathF.Sin(phase * MathF.PI * 2f)) // [0..1]
1180 : (phase < 0.5f ? phase * 2f : 1f - (phase - 0.5f) * 2f); // triangle
1181 }
1182
1183 [MethodImpl(MethodImplOptions.AggressiveInlining)]
1184 private static SKColor LerpColor(SKColor a, SKColor b, float t01)
1185 {
1186 t01 = Math.Clamp(t01, 0f, 1f);
1187 byte r = (byte)(a.Red + (b.Red - a.Red) * t01);
1188 byte g = (byte)(a.Green + (b.Green - a.Green) * t01);
1189 byte bl = (byte)(a.Blue + (b.Blue - a.Blue) * t01);
1190 byte al = (byte)(a.Alpha + (b.Alpha - a.Alpha) * t01);
1191
1192 return new SKColor(
1193 r,
1194 g,
1195 bl,
1196 al);
1197 }
1198
1199 private static string FitLineWithEllipsis(SKPaint paint, string text, float maxWidth)
1200 {
1201 const string ellipsis = "...";
1202
1203 if (string.IsNullOrEmpty(text))
1204 return text;
1205
1206 if (paint.MeasureText(text) <= maxWidth)
1207 return text;
1208
1209 float ellipsisWidth = paint.MeasureText(ellipsis);
1210
1211 if (ellipsisWidth > maxWidth)
1212 return string.Empty;
1213
1214 int length = text.Length;
1215
1216 while (length > 0)
1217 {
1218 string candidate = text.Substring(0, length).TrimEnd() + ellipsis;
1219
1220 if (paint.MeasureText(candidate) <= maxWidth)
1221 return candidate;
1222
1223 length--;
1224 }
1225
1226 return ellipsisWidth <= maxWidth ? ellipsis : string.Empty;
1227 }
1228
1229 #region public readonly properties
1230
1232 public string Text => _text;
1233
1235 public List<string> Lines => _lines;
1236
1238 public float LineHeight => _lineHeight;
1239
1241 public SKColor ForeColor => _foreColor;
1242
1244 public SKColor BackColor => _backColor;
1245
1247 public float FontSize => _fontSize;
1248
1250 public float? MinFontSize => _minFontSize;
1251
1253 public SKTypeface? TypeFace => _typeface;
1254
1256 public bool OutlineEnabled => _useOutline;
1257
1259 public bool WrapText => _wrapText;
1260
1262 public int? MaxLines => _maxLines;
1263
1265 public bool ShadowEnabled => _useShadow;
1266
1268 public float ShadowDx => _shadowDx;
1269
1271 public float ShadowDy => _shadowDy;
1272
1274 public byte ShadowAlpha => _shadowAlpha;
1275
1277 public float ShadowBlurSigma => _shadowBlurSigma;
1278
1280 public SKTextAlign AlignHoriz => _hAlign;
1281
1283 public VerticalAlign AlignVert => _vAlign;
1284
1286 public bool PulseTextEnabled => _pulseTextEnabled;
1287
1289 public SKColor PulseFrom => _pulseFrom;
1290
1292 public SKColor PulseTo => _pulseTo;
1293
1295 public float PulsePeriodSec => _pulsePeriodSec;
1296
1298 public PulseWave PulseWaveValue => _pulseWave;
1299
1301 public TextRevealMode TextRevealModeValue => _textRevealMode;
1302
1304 public float TextRevealRate => _revealRate;
1305
1307 public bool PuctuationPauseEnabled => _pauseEnabled;
1308
1310 public float PunctuationPauseLongSec => _pauseLongSec;
1311
1313 public float PunctuationPauseShortSec => _pauseShortSec;
1314
1316 public SKColor ResolvedForeColor => _resolvedForeColor;
1317
1318 #endregion public readonly properties
1319
1323 public enum PulseWave
1324 {
1327
1330 }
1331
1349
1350 private readonly object _eventLock = new();
1351
1356 protected override void Dispose(bool disposing)
1357 {
1358 if (disposing)
1359 {
1360 lock (_eventLock)
1361 {
1362 TextRevealed = null;
1363 TextRevealComplete = null;
1364 }
1365 }
1366
1367 base.Dispose(disposing);
1368 }
1369}
View? View
Gets the view to which this direct drawing is attached, or null if the drawing is in scene-layer mode...
long _lastTick
The last engine tick value used for delta-time calculations in Update.
SceneLayer? SceneLayer
Gets the scene layer to which this direct drawing is attached, or null if the drawing is in view mode...
Rectangle WorldBounds
Gets or sets the world-space bounds of this direct drawing in pixels.
DirectDrawingMode Mode
Gets the drawing mode that determines how this direct drawing is positioned and transformed.
Rectangle ScreenBounds
Gets or sets the screen-space bounds of this direct drawing in pixels.
DirectDrawingMovableBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, SceneLayer? sceneLayer, View? view, Rectangle? screenBounds, Rectangle? worldBounds, string? name=null)
Initializes a new instance of the DirectDrawingMovableBase class with integrated movement capabilitie...
TextBlock SetShadow(float dx, float dy, byte alpha=128, float blurSigma=1.5f)
Configures the drop shadow effect for text rendering.
Definition TextBlock.cs:496
TextBlock UseOutline(bool enable=true)
Enables or disables a 1-pixel outline stroke around the text glyphs.
Definition TextBlock.cs:515
float PunctuationPauseShortSec
Gets the short punctuation pause duration (seconds) used for ',', ';', ':'.
float ShadowDy
Gets the vertical shadow offset (in pixels).
PulseWave
Selects the waveform used by PulseColor(Color, Color, float, bool, bool).
@ Triangle
Triangle wave: linear fade-in/out between colors.
@ Sine
Sine wave: smooth continuous pulse between colors.
SKColor ResolvedForeColor
Gets the currently resolved (effective) foreground color used for drawing.
float PulsePeriodSec
Gets the pulse period in seconds.
TextBlock(RenderSurfaceHostBase renderSurfaceHost, SceneLayer sceneLayer, View? view, Rectangle worldBounds, string? nickname=null)
Creates a new TextBlock that draws in world space on the specified scene layer.
Definition TextBlock.cs:171
TextBlock SetColors(Color fg, Color bg)
Sets the foreground (text) and background colors using System.Drawing colors.
float ShadowBlurSigma
Gets the blur radius for the shadow (sigma, in pixels).
SKColor PulseFrom
Gets the starting color for the pulse effect.
VerticalAlign AlignVert
Gets the vertical alignment used when drawing lines.
float HorizontalPadding
Gets or sets the horizontal padding (in pixels) on both left and right sides of the text.
Definition TextBlock.cs:219
float PunctuationPauseLongSec
Gets the long punctuation pause duration (seconds) used for '.', '!', '?'.
TextBlock SetFont(SKTypeface typeface, float size, float? minSize=null)
Sets the font face and size (and optional minimum size for auto-shrink).
Definition TextBlock.cs:414
bool WrapText
Gets a value indicating whether word wrapping is enabled.
TextBlock(RenderSurfaceHostBase renderSurfaceHost, View view, Rectangle screenBounds, string? nickname=null)
Creates a new TextBlock that draws in screen space relative to a view.
Definition TextBlock.cs:195
SKColor ForeColor
Gets the configured foreground (text) color.
TextBlock EnableWrapping(bool enable=true)
Enables or disables word wrapping when laying out paragraphs.
Definition TextBlock.cs:527
TextBlock SetAlignment(SKTextAlign h, VerticalAlign v)
Sets the horizontal and vertical alignment used when drawing the laid-out lines within the bounds.
Definition TextBlock.cs:453
float? MinFontSize
Gets the optional minimum font size used by auto-shrink (or null if disabled).
TextBlock SetPadding(float horizontal, float vertical)
Sets symmetric horizontal and vertical padding and invalidates cached layout.
Definition TextBlock.cs:336
SKTypeface? TypeFace
Gets the configured typeface (or null to use SKTypeface.Default).
TextBlock StartWordReveal(float wordsPerSecond, bool enablePauses=true, float longPauseSec=0.25f, float shortPauseSec=0.10f)
Begins a word-by-word reveal. Words are detected by \S+\s* and include their trailing whitespace/punc...
Definition TextBlock.cs:629
VerticalAlign
Vertical alignment options for multi-line text within the control's bounds.
Definition TextBlock.cs:49
@ Bottom
Align text to the bottom of the inner content area.
Definition TextBlock.cs:57
@ Center
Center text vertically within the inner content area.
Definition TextBlock.cs:54
@ Top
Align text to the top of the inner content area.
Definition TextBlock.cs:51
SKColor BackColor
Gets the configured background color.
TextBlock UseShadow(bool enable=true)
Enables or disables drawing a drop shadow behind the text (parameters are configured via SetShadow(fl...
Definition TextBlock.cs:466
TextBlock SetColors(SKColor fg, SKColor bg)
Sets the foreground (text) and background colors using Skia colors.
Definition TextBlock.cs:430
float LineSpacingMultiplier
Gets or sets a scale factor applied to the computed line height (1.0 = natural spacing).
Definition TextBlock.cs:214
override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
Draws the laid-out text block contents into the destination rectangle.
Definition TextBlock.cs:868
bool PulseTextEnabled
Gets a value indicating whether color pulsing is enabled.
float VerticalScrollEndPaddingPx
Gets or sets extra scrollable space after the final laid-out line.
Definition TextBlock.cs:257
Action< string >? TextRevealComplete
Raised once when the reveal completes. Argument is the full text content. Note: when the final chunk ...
Definition TextBlock.cs:73
override void Dispose(bool disposing)
Releases managed resources used by the text block.
TextBlock RevealSetCount(int charCount)
Sets the currently revealed character count directly (manual mode).
Definition TextBlock.cs:678
float FontSize
Gets the requested font size (before any auto-shrink adjustments).
PulseWave PulseWaveValue
Gets the pulse waveform currently in use.
byte ShadowAlpha
Gets the shadow opacity (0-255).
float MeasureMaximumVerticalScrollOffsetPx()
Measures the maximum vertical scroll offset required to expose all currently laid-out text.
Definition TextBlock.cs:279
bool OutlineEnabled
Gets a value indicating whether an outline stroke is enabled.
SKColor PulseTo
Gets the ending color for the pulse effect.
TextRevealMode TextRevealModeValue
Gets the active text reveal mode.
bool ShadowEnabled
Gets a value indicating whether a drop shadow is enabled.
int? MaxLines
Gets the optional maximum number of lines to draw (or null for no limit).
float ShadowDx
Gets the horizontal shadow offset (in pixels).
TextBlock SetPunctuationPauses(bool enabled, float longPauseSec=0.25f, float shortPauseSec=0.10f)
Configures punctuation pause behavior used by the current or next reveal animation.
Definition TextBlock.cs:665
float VerticalPadding
Gets or sets the vertical padding (in pixels) on both top and bottom sides of the text.
Definition TextBlock.cs:224
List< string > Lines
Gets the laid-out lines (after wrapping and paragraph processing).
TextBlock StopColorPulse()
Stops text color pulsing and restores the base foreground color.
Definition TextBlock.cs:579
float VerticalScrollOffsetPx
Gets or sets the vertical text-content scroll offset in native pixels.
Definition TextBlock.cs:234
TextRevealMode
Describes the mode used for revealing text over time.
@ CharactersPerSecond
Reveal advances by characters per second.
@ None
No reveal is active; all text is shown.
@ ManualCount
Reveal amount is controlled directly via RevealSetCount(int).
@ WordsPerSecond
Reveal advances by words per second.
TextBlock RevealStop()
Stops any active reveal animation and shows the full text immediately.
Definition TextBlock.cs:691
SKTextAlign AlignHoriz
Gets the horizontal alignment used when drawing lines.
Action< string >? TextRevealed
Raised whenever the revealed text portion advances. The argument is the cumulative text currently rev...
Definition TextBlock.cs:66
TextBlock SetText(string text)
Sets the current text content and rebuilds layout as needed. If no reveal animation is active,...
Definition TextBlock.cs:378
float LineHeight
Gets the measured line height (in pixels) used for drawing.
TextBlock PulseColor(Color from, Color to, float periodSec, bool enabled=true, bool triangle=false)
Animates the text color between from and to over periodSec seconds.
Definition TextBlock.cs:556
string Text
Gets the current raw text content.
TextBlock SetSize(Size size)
Sets the text-block size while preserving its current position and invalidates cached layout.
Definition TextBlock.cs:356
TextBlock SetMaxLines(int? maxLines)
Sets a maximum number of lines to draw. If null, all laid-out lines are drawn.
Definition TextBlock.cs:540
override void Update(long tick)
Advances internal animations (pulse, typewriter/word reveal) based on the current tick,...
Definition TextBlock.cs:722
float TextRevealRate
Gets the configured reveal rate (characters/sec or words/sec depending on mode).
bool PuctuationPauseEnabled
Gets a value indicating whether punctuation pauses are enabled.
TextBlock StartTypewriter(float charsPerSecond, int? maxChars=null, bool enablePauses=true, float longPauseSec=0.25f, float shortPauseSec=0.10f)
Begins a character-by-character reveal (typewriter effect).
Definition TextBlock.cs:596
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
SKCanvas Canvas
Gets the SkiaSharp canvas used for drawing operations on this backbuffer.
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
@ View
Performs direct drawing at the view level using screen-space coordinates.