1 module polyplex.core.content.font;
2 import polyplex.core.content.textures;
3 import polyplex.core.content.gl.textures;
4 import polyplex.core.render.gl.gloo;
5 import ppc.types.font;
6 import polyplex.math;
7 
8 public class SpriteFont {
9 private:
10 	GlTexture2DImpl!(GL_RED, 1) texture;
11 	TypeFace typeface;
12 
13 	Vector2i baseCharSize;
14 
15 public:
16 	/// Constructor
17 	this(TypeFace typeface) {
18 		this.typeface = typeface;
19 		PSize size = typeface.getAtlasSize();
20 		this.texture = new GlTexture2DImpl!(GL_RED, 1)(new TextureImg(cast(int)size.width, cast(int)size.height, typeface.getTexture()));
21 
22 		// Gets the base character height of the character A
23 		baseCharSize = cast(Vector2i)MeasureCharacter('A');
24 	}
25 
26 	/// Returns the texture for this sprite font
27 	Texture2D getTexture() {
28 		return cast(Texture2D)texture;
29 	}
30 	
31 	/// Indexer for glyph info
32 	GlyphInfo* opIndex(dchar c) {
33 		return typeface[c];
34 	}
35 
36 	/// Measure the size of a string
37 	Vector2 MeasureString(string text) {
38 		int lines = 1;
39 		float currentLineLength = 0;
40 		Vector2 size = Vector2(0, 0);
41 		foreach(dchar c; text) {
42 			if (c == '\n') {
43 				lines++;
44 				currentLineLength = 0;
45 			}
46 			if (this[c] is null) continue;
47 			
48 			// Bitshift by 6 to make it be in pixels
49 			currentLineLength += (this[c].advance.x >> 6);
50 
51 			if (currentLineLength > size.X) size.X = currentLineLength;
52 		}
53 		float height = lines*(baseCharSize.Y+(baseCharSize.Y/2));
54 		return Vector2(size.X, height-(baseCharSize.Y/2));
55 	}
56 
57 	/// Measure the size of an individual character
58 	Vector2 MeasureCharacter(dchar c) {
59 		return Vector2((this[c].advance.x >> 6), this[c].bearing.y);
60 	}
61 
62 	/**
63 		Returns the base size for the character 'A'
64 	*/
65 	@property Vector2i BaseCharSize() {
66 		return baseCharSize;
67 	}
68 
69 	/**
70 		Gets the size of the sprite font texture atlas
71 	*/
72 	@property Vector2i TexSize() {
73 		return Vector2i(texture.Width, texture.Height);
74 	}
75 }