using System;
using OpenTK;
using OpenTK.Graphics;
using SM.Base.Contexts;
using SM.Base.Scene;
using SM.Data.Fonts;
namespace SM.Base.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 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;
}
///
/// The spacing between numbers.
/// Default: 1
///
public float Spacing = 1;
///
/// Creates a text object with a font.
///
/// The font.
protected TextDrawingBasis(Font font)
{
_material.Texture = font;
}
///
public override void Draw(DrawContext context)
{
base.Draw(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();
_instances = new Instance[_text.Length];
float x = 0;
CharParameter _last = new CharParameter();
for (var i = 0; i < _text.Length; i++)
{
if (_text[i] == 32)
{
x += _last.Width * Spacing;
continue;
}
CharParameter parameter;
try
{
parameter = Font.Positions[_text[i]];
}
catch
{
throw new Exception("Font doesn't contain '" + _text[i] + "'");
}
Matrix4 matrix = Matrix4.CreateScale(parameter.Width, Font.Height, 1) *
Matrix4.CreateTranslation(x, 0, 0);
_instances[i] = new Instance
{
ModelMatrix = matrix,
TexturePosition = new Vector2(parameter.NormalizedX, 0),
TextureScale = new Vector2(parameter.NormalizedWidth, 1)
};
x += parameter.Width * Spacing;
_last = parameter;
}
}
}
}