#region usings using System; using OpenTK; using OpenTK.Graphics; using SM.Base.Window; #endregion namespace SM.Base.Drawing.Text { /// /// Defines a basis for text drawing. /// /// Transformation type public abstract class TextDrawingBasis : DrawingBasis where TTransform : GenericTransformation, new() { /// /// The different instances for drawing. /// protected Instance[] _instances; /// /// The text, that is drawn. /// protected string _text; /// /// The width of the text object. /// public float Width; /// /// The height of the text object. /// public float Height; /// /// The spacing between numbers. /// Default: 1 /// public float Spacing = 1; /// /// The font. /// public Font Font { get => (Font)Material.Texture; set { Material.Texture = value; GenerateMatrixes(); } } /// /// The text, that is drawn. /// public string Text { get => _text; set { _text = value; GenerateMatrixes(); } } /// /// The font color. /// public Color4 Color { get => Material.Tint; set => Material.Tint = value; } /// /// Creates a text object with a font. /// /// The font. protected TextDrawingBasis(Font font) { Material.Texture = font; Material.Blending = true; } /// protected override void DrawContext(ref DrawContext context) { base.DrawContext(ref context); if (_instances == null) GenerateMatrixes(); } /// /// This generates the instances. /// /// The font doesn't contain a character that is needed for the text. public void GenerateMatrixes() { if (!Font.WasCompiled) Font.RegenerateTexture(); _text = _text.Replace("\r\n", "\n").Replace("\t", " "); _instances = new Instance[_text.Length]; float x = 0; float y = 0; var _last = new CharParameter(); for (var i = 0; i < _text.Length; i++) { if (_text[i] == ' ') { x += Font.SpaceWidth * Spacing; continue; } if (_text[i] == '\n') { y += Font.Height; Width = Math.Max(Width, x); x = 0; continue; } CharParameter parameter; try { parameter = Font.Positions[_text[i]]; } catch { throw new Exception("Font doesn't contain '" + _text[i] + "'"); } var matrix = Matrix4.CreateScale(parameter.Width, Font.Height, 1) * Matrix4.CreateTranslation(x, -y, 0); _instances[i] = new Instance { ModelMatrix = matrix, TextureMatrix = TextureTransformation.CalculateMatrix(new Vector2(parameter.NormalizedX, 0), new Vector2(parameter.NormalizedWidth, 1), 0) }; x += parameter.Width * Spacing; _last = parameter; } Width = Math.Max(Width, x); Height = y + Font.Height; } } }