]> git.tdb.fi Git - libs/gl.git/blob - source/text.cpp
Add more public methods to Transform
[libs/gl.git] / source / text.cpp
1 #include "meshbuilder.h"
2 #include "text.h"
3 #include "texture2d.h"
4
5 using namespace std;
6
7 namespace Msp {
8 namespace GL {
9
10 Text::Text(const Font &f, const Technique *tech):
11         font(f),
12         mesh((TEXCOORD2, VERTEX2)),
13         horz_align(0.0f),
14         vert_offset(0.0f),
15         width(0.0f)
16 {
17         object.set_mesh(&mesh);
18         if(tech)
19                 set_technique(tech);
20 }
21
22 void Text::set_technique(const Technique *tech)
23 {
24         if(tech)
25         {
26                 technique = *tech;
27                 technique.replace_texture("diffuse_map", font.get_texture());
28                 object.set_technique(&technique);
29         }
30         else
31                 object.set_technique(0);
32 }
33
34 void Text::set_text(const string &text, StringCodec::Decoder &dec)
35 {
36         clear();
37         width = font.get_string_width(text, dec);
38         MeshBuilder bld(mesh);
39         bld.matrix() *= Matrix::translation(Vector3(-horz_align*width, vert_offset, 0.0f));
40         font.build_string(text, dec, bld);
41 }
42
43 void Text::clear()
44 {
45         mesh.clear();
46         width = 0;
47 }
48
49 void Text::set_alignment(HorizontalAlign ha, VerticalAlign va)
50 {
51         float h;
52         switch(ha)
53         {
54         case LEFT: h = 0.0f; break;
55         case CENTER: h = 0.5f; break;
56         case RIGHT: h = 1.0f; break;
57         default: throw invalid_argument("Text::set_alignment");
58         }
59
60         float v;
61         switch(va)
62         {
63         case DESCENT: v = -font.get_descent(); break;
64         case BASELINE: v = 0.0f; break;
65         case MIDLINE: v = font.get_cap_height()/2; break;
66         case ASCENT: v = font.get_ascent(); break;
67         default: throw invalid_argument("Text::set_alignment");
68         }
69
70         set_alignment(h, v);
71 }
72
73 void Text::set_alignment(float h, float v)
74 {
75         if(h==horz_align && -v==vert_offset)
76                 return;
77
78         float horz_adjust = (horz_align-h)*width;
79         float vert_adjust = -v-vert_offset;
80         horz_align = h;
81         vert_offset = -v;
82
83         unsigned pos_offset = mesh.get_vertices().get_format().offset(VERTEX2);
84         unsigned n_vertices = mesh.get_n_vertices();
85         for(unsigned i=0; i<n_vertices; ++i)
86         {
87                 float *pos = mesh.modify_vertex(i)+pos_offset;
88                 pos[0] += horz_adjust;
89                 pos[1] += vert_adjust;
90         }
91 }
92
93 void Text::render(Renderer &renderer, const Tag &tag) const
94 {
95         object.render(renderer, tag);
96 }
97
98 } // namespace GL
99 } // namespace Msp