forked from azsn/gllabel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlabel.cpp
1338 lines (1132 loc) · 40.7 KB
/
label.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Aidan Shafran <[email protected]>, 2016.
*
* This code is based on Will Dobbie's WebGL vector-based text rendering (2016).
* It can be found here:
* http://wdobbie.com/post/gpu-text-rendering-with-vector-textures/
*
* Dobbie's original code used a pre-generated bezier curve atlas generated
* from a PDF. This GLLabel class allows for live text rendering based on
* glyph curves exported from FreeType2.
*
* Text is rendered size-independently. This means you can scale, rotate,
* or reposition text rendered using GLLabel without any loss of quality.
* All that's required is a font file to load the text from. TTF works well.
*
* The only remaining portion of Dobbie's code is the fragment shader.
* Although the code had no license, comments seemed to imply the code is
* freely available for use. I have contacted him to ask for a license,
* but received no response. Therefore, all of this code except the
* fragment shader is under the Apache License v2.0, while the fragment
* shader is unlicensed until further notice.
* (Dobbie, please let me know if you have issues with this.)
*/
#include "label.hpp"
#include <set>
#include <fstream>
#include <glm/gtc/type_ptr.hpp>
#define sq(x) ((x)*(x))
static char32_t readNextChar(const char **p, size_t *datalen);
static GLuint loadShaderProgram(const char *vsCodeC, const char *fsCodeC);
std::shared_ptr<GLFontManager> GLFontManager::singleton = nullptr;
namespace {
extern const char *kGlyphVertexShader;
extern const char *kGlyphFragmentShader;
}
static const uint8_t kGridMaxSize = 20;
static const uint16_t kGridAtlasSize = 256; // Fits exactly 1024 8x8 grids
static const uint16_t kBezierAtlasSize = 256; // Fits around 700-1000 glyphs, depending on their curves
static const uint8_t kAtlasChannels = 4; // Must be 4 (RGBA), otherwise code breaks
GLLabel::GLLabel()
: showingCaret(false), caretPosition(0), prevTime(0),
horzAlign(GLLabel::Align::Start), vertAlign(GLLabel::Align::Start)
{
// this->lastColor = {0,0,0,255};
this->manager = GLFontManager::GetFontManager();
// this->lastFace = this->manager->GetDefaultFont();
// this->manager->LoadASCII(this->lastFace);
glGenBuffers(1, &this->vertBuffer);
glGenBuffers(1, &this->caretBuffer);
}
GLLabel::~GLLabel()
{
glDeleteBuffers(1, &this->vertBuffer);
glDeleteBuffers(1, &this->caretBuffer);
}
void GLLabel::InsertText(std::u32string text, size_t index, float size, glm::vec4 color, FT_Face face)
{
if(index > this->text.size())
index = this->text.size();
this->text.insert(index, text);
this->glyphs.insert(this->glyphs.begin() + index, text.size(), nullptr);
size_t prevCapacity = this->verts.capacity();
GlyphVertex emptyVert = {glm::vec2(), 0};
this->verts.insert(this->verts.begin() + index*6, text.size()*6, emptyVert);
glm::vec2 appendOffset;
if(index > 0)
{
appendOffset = this->verts[(index-1)*6].pos;
if(this->glyphs[index-1])
appendOffset += -glm::vec2(this->glyphs[index-1]->offset[0], this->glyphs[index-1]->offset[1]) + glm::vec2(this->glyphs[index-1]->advance, 0);
}
glm::vec2 initialAppendOffset = appendOffset;
for(size_t i=0;i<text.size();++i)
{
if(text[i] == '\r') {
this->verts[(index + i)*6].pos = appendOffset;
continue;
}
else if(text[i] == '\n') {
appendOffset.x = 0;
appendOffset.y -= face->height;
this->verts[(index + i)*6].pos = appendOffset;
continue;
}
else if(text[i] == '\t') {
appendOffset.x += 2000;
this->verts[(index + i)*6].pos = appendOffset;
continue;
}
GLFontManager::Glyph *glyph = this->manager->GetGlyphForCodepoint(face, text[i]);
if(!glyph) {
this->verts[(index + i)*6].pos = appendOffset;
continue;
}
GlyphVertex v[6]; // Insertion code depends on v[0] equaling appendOffset (therefore it is also set before continue;s above)
v[0].pos = glm::vec2(0, 0);
v[1].pos = glm::vec2(glyph->size[0], 0);
v[2].pos = glm::vec2(0, glyph->size[1]);
v[3].pos = glm::vec2(glyph->size[0], glyph->size[1]);
v[4].pos = glm::vec2(0, glyph->size[1]);
v[5].pos = glm::vec2(glyph->size[0], 0);
for(unsigned int j=0;j<6;++j)
{
v[j].pos += appendOffset;
v[j].pos[0] += glyph->offset[0];
v[j].pos[1] += glyph->offset[1];
v[j].color = {(uint8_t)(color.r*255), (uint8_t)(color.g*255), (uint8_t)(color.b*255), (uint8_t)(color.a*255)};
// Encode both the bezier position and the norm coord into one int
// This theoretically could overflow, but the atlas position will
// never be over half the size of a uint16, so it's fine.
unsigned int k = (j < 4) ? j : 6 - j;
v[j].data[0] = glyph->bezierAtlasPos[0]*2 + ((k & 1) ? 1 : 0);
v[j].data[1] = glyph->bezierAtlasPos[1]*2 + ((k > 1) ? 1 : 0);
this->verts[(index + i)*6 + j] = v[j];
}
appendOffset.x += glyph->advance;
this->glyphs[index + i] = glyph;
}
// Shift everything after, if necessary
glm::vec2 deltaAppend = appendOffset - initialAppendOffset;
for(size_t i=index+text.size(); i<this->text.size(); ++i)
{
// If a newline is reached and no change in the y has happened, all
// glyphs which need to be moved have been moved.
if(this->text[i] == '\n')
{
if(deltaAppend.y == 0)
break;
if(deltaAppend.x < 0)
deltaAppend.x = 0;
}
for(unsigned int j=0; j<6; ++j)
this->verts[i*6 + j].pos += deltaAppend;
}
glBindBuffer(GL_ARRAY_BUFFER, this->vertBuffer);
if(this->verts.capacity() != prevCapacity)
{
// If the capacity changed, completely reupload the buffer
glBufferData(GL_ARRAY_BUFFER, this->verts.capacity() * sizeof(GlyphVertex), NULL, GL_DYNAMIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, this->verts.size() * sizeof(GlyphVertex), &this->verts[0]);
}
else
{
// Otherwise only upload the changed parts
glBufferSubData(GL_ARRAY_BUFFER,
index*6*sizeof(GlyphVertex),
(this->verts.size() - index*6)*sizeof(GlyphVertex),
&this->verts[index*6]);
}
caretTime = 0;
}
void GLLabel::RemoveText(size_t index, size_t length)
{
if(index >= this->text.size())
return;
if(index + length > this->text.size())
length = this->text.size() - index;
glm::vec2 startOffset;
if(index > 0)
{
startOffset = this->verts[(index-1)*6].pos;
if(this->glyphs[index-1])
startOffset += -glm::vec2(this->glyphs[index-1]->offset[0], this->glyphs[index-1]->offset[1]) + glm::vec2(this->glyphs[index-1]->advance, 0);
}
// printf("start offset: %f, %f\n", startOffset.x, startOffset.y);
// Since all the glyphs between index-1 and index+length have been erased,
// the end offset will be at index until it gets shifted back
glm::vec2 endOffset;
// if(this->glyphs[index+length-1])
// {
endOffset = this->verts[index*6].pos;
if(this->glyphs[index+length-1])
endOffset += -glm::vec2(this->glyphs[index+length-1]->offset[0], this->glyphs[index+length-1]->offset[1]) + glm::vec2(this->glyphs[index+length-1]->advance, 0);
// }
// printf("end offset: %f, %f\n", endOffset.x, endOffset.y);
this->text.erase(index, length);
this->glyphs.erase(this->glyphs.begin() + index, this->glyphs.begin() + (index+length));
this->verts.erase(this->verts.begin() + index*6, this->verts.begin() + (index+length)*6);
glm::vec2 deltaOffset = endOffset - startOffset;
// printf("%f, %f\n", deltaOffset.x, deltaOffset.y);
// Shift everything after, if necessary
for(size_t i=index; i<this->text.size(); ++i)
{
if(this->text[i] == '\n')
deltaOffset.x = 0;
for(unsigned int j=0; j<6; ++j)
this->verts[i*6 + j].pos -= deltaOffset;
}
// Otherwise only upload the changed parts
glBindBuffer(GL_ARRAY_BUFFER, this->vertBuffer);
glBufferSubData(GL_ARRAY_BUFFER,
index*6*sizeof(GlyphVertex),
(this->verts.size() - index*6)*sizeof(GlyphVertex),
&this->verts[index*6]);
caretTime = 0;
}
void GLLabel::SetHorzAlignment(Align horzAlign)
{
}
void GLLabel::SetVertAlignment(Align vertAlign)
{
}
void GLLabel::Render(float time, glm::mat4 transform)
{
float deltaTime = time - prevTime;
this->caretTime += deltaTime;
this->manager->UseGlyphShader();
this->manager->UploadAtlases();
this->manager->UseAtlasTextures(0); // TODO: Textures based on each glyph
this->manager->SetShaderTransform(transform);
glEnable(GL_BLEND);
glBindBuffer(GL_ARRAY_BUFFER, this->vertBuffer);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLLabel::GlyphVertex), (void*)offsetof(GLLabel::GlyphVertex, pos));
glVertexAttribPointer(1, 2, GL_UNSIGNED_SHORT, GL_FALSE, sizeof(GLLabel::GlyphVertex), (void*)offsetof(GLLabel::GlyphVertex, data));
glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(GLLabel::GlyphVertex), (void*)offsetof(GLLabel::GlyphVertex, color));
glDrawArrays(GL_TRIANGLES, 0, this->verts.size());
if(this->showingCaret && !(((int)(this->caretTime*3/2)) % 2))
{
GLFontManager::Glyph *pipe = this->manager->GetGlyphForCodepoint(this->manager->GetDefaultFont(), '|');
size_t index = this->caretPosition;
glm::vec2 offset;
if(index > 0)
{
offset = this->verts[(index-1)*6].pos;
if(this->glyphs[index-1])
offset += -glm::vec2(this->glyphs[index-1]->offset[0], this->glyphs[index-1]->offset[1]) + glm::vec2(this->glyphs[index-1]->advance, 0);
}
GlyphVertex x[6];
x[1].pos = glm::vec2(pipe->size[0], 0);
x[2].pos = glm::vec2(0, pipe->size[1]);
x[3].pos = glm::vec2(pipe->size[0], pipe->size[1]);
x[4].pos = glm::vec2(0, pipe->size[1]);
x[5].pos = glm::vec2(pipe->size[0], 0);
for(unsigned int j=0;j<6;++j)
{
x[j].pos += offset;
x[j].pos.x -= 500;
x[j].pos[0] += pipe->offset[0];
x[j].pos[1] += pipe->offset[1];
x[j].color = {0,0,255,100};
// Encode both the bezier position and the norm coord into one int
// This theoretically could overflow, but the atlas position will
// never be over half the size of a uint16, so it's fine.
unsigned int k = (j < 4) ? j : 6 - j;
x[j].data[0] = pipe->bezierAtlasPos[0]*2 + ((k & 1) ? 1 : 0);
x[j].data[1] = pipe->bezierAtlasPos[1]*2 + ((k > 1) ? 1 : 0);
// this->verts[(index + i)*6 + j] = v[j];
}
glBindBuffer(GL_ARRAY_BUFFER, this->caretBuffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLLabel::GlyphVertex), (void*)offsetof(GLLabel::GlyphVertex, pos));
glVertexAttribPointer(1, 2, GL_UNSIGNED_SHORT, GL_FALSE, sizeof(GLLabel::GlyphVertex), (void*)offsetof(GLLabel::GlyphVertex, data));
glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(GLLabel::GlyphVertex), (void*)offsetof(GLLabel::GlyphVertex, color));
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(GlyphVertex), &x[0], GL_STREAM_DRAW);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisable(GL_BLEND);
prevTime = time;
}
GLFontManager::GLFontManager() : defaultFace(nullptr)
{
if(FT_Init_FreeType(&this->ft) != FT_Err_Ok)
printf("Failed to load freetype\n");
this->glyphShader = loadShaderProgram(kGlyphVertexShader, kGlyphFragmentShader);
this->uGridAtlas = glGetUniformLocation(glyphShader, "uGridAtlas");
this->uBezierAtlas = glGetUniformLocation(glyphShader, "uBezierAtlas");
this->uGridTexel = glGetUniformLocation(glyphShader, "uGridTexel");
this->uBezierTexel = glGetUniformLocation(glyphShader, "uBezierTexel");
this->uTransform = glGetUniformLocation(glyphShader, "uTransform");
this->UseGlyphShader();
glUniform1i(this->uGridAtlas, 0);
glUniform1i(this->uBezierAtlas, 1);
glUniform2f(this->uGridTexel, 1.0/kGridAtlasSize, 1.0/kGridAtlasSize);
glUniform2f(this->uBezierTexel, 1.0/kBezierAtlasSize, 1.0/kBezierAtlasSize);
glUniform4f(this->uTransform, 0, 0, 1, 1);
}
GLFontManager::~GLFontManager()
{
// TODO: Destroy atlases
glDeleteProgram(this->glyphShader);
FT_Done_FreeType(this->ft);
}
std::shared_ptr<GLFontManager> GLFontManager::GetFontManager()
{
if(!GLFontManager::singleton)
GLFontManager::singleton = std::shared_ptr<GLFontManager>(new GLFontManager());
return GLFontManager::singleton;
}
// TODO: FT_Faces don't get destroyed... FT_Done_FreeType cleans them eventually,
// but maybe use shared pointers?
FT_Face GLFontManager::GetFontFromPath(std::string fontPath)
{
FT_Face face;
return FT_New_Face(this->ft, fontPath.c_str(), 0, &face) ? nullptr : face;
}
FT_Face GLFontManager::GetFontFromName(std::string fontName)
{
std::string path = fontName; // TODO
return GLFontManager::GetFontFromPath(path);
}
FT_Face GLFontManager::GetDefaultFont()
{
// TODO
if(!defaultFace)
defaultFace = GLFontManager::GetFontFromPath("/usr/share/fonts/noto/NotoSans-Regular.ttc");
return defaultFace;
}
GLFontManager::AtlasGroup * GLFontManager::GetOpenAtlasGroup()
{
if(this->atlases.size() == 0 || this->atlases[this->atlases.size()-1].full)
{
AtlasGroup group = {0};
group.bezierAtlas = new uint8_t[sq(kBezierAtlasSize)*kAtlasChannels]();
group.gridAtlas = new uint8_t[sq(kGridAtlasSize)*kAtlasChannels]();
group.uploaded = true;
glGenTextures(1, &group.bezierAtlasId);
glBindTexture(GL_TEXTURE_2D, group.bezierAtlasId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, kBezierAtlasSize, kBezierAtlasSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, group.bezierAtlas);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glGenTextures(1, &group.gridAtlasId);
glBindTexture(GL_TEXTURE_2D, group.gridAtlasId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, kGridAtlasSize, kGridAtlasSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, group.gridAtlas);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
this->atlases.push_back(group);
}
return &this->atlases[this->atlases.size()-1];
}
struct Bezier
{
glm::vec2 e0;
glm::vec2 e1;
glm::vec2 c; // control point
};
inline bool almostEqual(float a, float b)
{
return std::fabs(a-b) < 1e-5;
}
/*
* Taking a quadratic bezier curve and a horizontal line y=Y, finds the x
* values of intersection of the line and the curve. Returns 0, 1, or 2,
* depending on how many intersections were found, and outX is filled with
* that many x values of intersection.
*
* Quadratic bezier curves are represented by the function
* F(t) = (1-t)^2*A + 2*t*(1-t)*B + t^2*C
* where F is a vector function, A and C are the endpoint vectors, C is
* the control point vector, and 0 <= t <= 1.
* Solving the bezier function for t gives:
* t = (A - B [+-] sqrt(y*a + B^2 - A*C))/a , where a = A - 2B + C.
* http://www.wolframalpha.com/input/?i=y+%3D+(1-t)%5E2a+%2B+2t(1-t)*b+%2B+t%5E2*c+solve+for+t
*/
static int bezierIntersectHorz(Bezier *curve, glm::vec2 *outX, float Y)
{
glm::vec2 A = curve->e0;
glm::vec2 B = curve->c;
glm::vec2 C = curve->e1;
int i = 0;
#define T_VALID(t) ((t) <= 1 && (t) >= 0)
#define X_FROM_T(t) ((1-(t))*(1-(t))*curve->e0.x + 2*(t)*(1-(t))*curve->c.x + (t)*(t)*curve->e1.x)
// Parts of the bezier function solved for t
float a = curve->e0.y - 2*curve->c.y + curve->e1.y;
// In the condition that a=0, the standard formulas won't work
if(almostEqual(a, 0))
{
float t = (2*B.y - C.y - Y) / (2*(B.y-C.y));
if(T_VALID(t))
(*outX)[i++] = X_FROM_T(t);
return i;
}
float sqrtTerm = sqrt(Y*a + B.y*B.y - A.y*C.y);
float t = (A.y - B.y + sqrtTerm) / a;
if(T_VALID(t))
(*outX)[i++] = X_FROM_T(t);
t = (A.y - B.y - sqrtTerm) / a;
if(T_VALID(t))
(*outX)[i++] = X_FROM_T(t);
return i;
#undef X_FROM_T
#undef T_VALID
}
/*
* Same as bezierIntersectHorz, except finds the y values of an intersection
* with the vertical line x=X.
*/
static int bezierIntersectVert(Bezier *curve, glm::vec2 *outY, float X)
{
Bezier inverse = {
glm::vec2(curve->e0.y, curve->e0.x),
glm::vec2(curve->e1.y, curve->e1.x),
glm::vec2(curve->c.y, curve->c.x)
};
return bezierIntersectHorz(&inverse, outY, X);
}
struct OutlineDecomposeState
{
FT_Vector prevPoint;
std::vector<Bezier> *curves;
FT_Pos metricsX;
FT_Pos metricsY;
};
/*
* Uses FreeType's outline decomposing to convert an outline into a vector
* of beziers. This just makes working with the outline easier.
*/
static std::vector<Bezier> GetCurvesForOutline(FT_Outline *outline)
{
std::vector<Bezier> curves;
if(outline->n_points <= 0)
return curves;
// For some reason, the glyphs aren't always positioned with their bottom
// left corner at 0,0. So find the min x and y values.
FT_Pos metricsX=outline->points[0].x, metricsY=outline->points[0].y;
for(short i=1; i<outline->n_points; ++i)
{
metricsX = std::min(metricsX, outline->points[i].x);
metricsY = std::min(metricsY, outline->points[i].y);
}
OutlineDecomposeState state = {0};
state.curves = &curves;
state.metricsX = metricsX;
state.metricsY = metricsY;
FT_Outline_Funcs funcs = {0};
funcs.move_to = [](const FT_Vector *to, void *user) -> int {
auto state = static_cast<OutlineDecomposeState *>(user);
state->prevPoint = *to;
return 0;
};
funcs.line_to = [](const FT_Vector *to, void *user) -> int {
auto state = static_cast<OutlineDecomposeState *>(user);
Bezier b;
b.e0 = glm::vec2(state->prevPoint.x - state->metricsX, state->prevPoint.y - state->metricsY);
b.c = b.e0;
b.e1 = glm::vec2(to->x - state->metricsX, to->y - state->metricsY);
state->curves->push_back(b);
state->prevPoint = *to;
return 0;
};
funcs.conic_to = [](const FT_Vector *control, const FT_Vector *to, void *user) -> int {
auto state = static_cast<OutlineDecomposeState *>(user);
Bezier b;
b.e0 = glm::vec2(state->prevPoint.x - state->metricsX, state->prevPoint.y - state->metricsY);
b.c = glm::vec2(control->x - state->metricsX, control->y - state->metricsY);
b.e1 = glm::vec2(to->x - state->metricsX, to->y - state->metricsY);
state->curves->push_back(b);
state->prevPoint = *to;
return 0;
};
funcs.cubic_to = [](const FT_Vector *control1, const FT_Vector *control2, const FT_Vector *to, void *user) -> int {
// Not implemented
return -1;
};
if(FT_Outline_Decompose(outline, &funcs, &state) == 0)
return curves;
return std::vector<Bezier>();
}
/*
* Using the outline curves of a glyph, creates a square grid of edge length
* GLLabel::kGridMaxSize where each cell stores all of the indices of the
* curves that intersect that cell.
* The grid is returned as a lineariezed 2D array.
*/
static std::vector<std::set<uint16_t>> GetGridForCurves(std::vector<Bezier> &curves, FT_Pos glyphWidth, FT_Pos glyphHeight, uint8_t &gridWidth, uint8_t &gridHeight)
{
gridWidth = kGridMaxSize;
gridHeight = kGridMaxSize;
std::vector<std::set<uint16_t>> grid;
grid.resize(gridWidth * gridHeight);
// For each curve, for each vertical and horizontal grid line
// (including edges), determine where the curve intersects. Each
// intersection affects two cells, and each curve can intersect a line
// up to twice, for a maximum of four cells per line per curve.
for(uint32_t i=0;i<curves.size();++i)
{
// TODO: The std::set insert operation is really slow?
// It appears that this operation nearly doubles the runtime
// of calculateGridForGlyph.
#define SETGRID(x, y) { grid[(y)*gridWidth+(x)].insert(i); }
// If a curve intersects no grid lines, it won't be included. So
// make sure the cell the the curve starts in is included
SETGRID(std::min((unsigned long)(curves[i].e0.x * gridWidth / glyphWidth), (unsigned long)gridWidth-1), std::min((unsigned long)(curves[i].e0.y * gridHeight / glyphHeight), (unsigned long)gridHeight-1));
for(size_t j=0; j<=gridWidth; ++j)
{
glm::vec2 intY;
int num = bezierIntersectVert(&curves[i], &intY, j * glyphWidth / gridWidth);
for(int z=0;z<num;++z)
{
uint8_t y = (uint8_t)glm::clamp((signed long)(intY[z] * gridHeight / glyphHeight), 0L, (signed long)gridHeight-1);
uint8_t x1 = (size_t)std::max((signed long)j-1, (signed long)0);
uint8_t x2 = (size_t)std::min((signed long)j, (signed long)gridWidth-1);
SETGRID(x1, y);
SETGRID(x2, y);
}
}
for(size_t j=0; j<=gridHeight; ++j)
{
glm::vec2 intX;
int num = bezierIntersectHorz(&curves[i], &intX, j * glyphHeight / gridHeight);
for(int z=0;z<num;++z)
{
uint8_t x = (uint8_t)glm::clamp((signed long)(intX[z] * gridWidth / glyphWidth), 0L, (signed long)gridWidth-1);
uint8_t y1 = (size_t)std::max((signed long)j-1, (signed long)0);
uint8_t y2 = (size_t)std::min((signed long)j, (signed long)gridHeight-1);
SETGRID(x, y1);
SETGRID(x, y2);
}
}
#undef SETGRID
}
// In order for the shader to know whether a cell that has no intersections
// is within or outside the glyph, a flag is stored in each cell telling
// whether the center of the cell is inside or not.
std::set<float> intersections; // Sets keep ordered (avoids calling sort)
for(size_t i=0; i<gridHeight; ++i)
{
intersections.clear();
float Y = i + 0.5; // Test midpoints of cells
for(size_t j=0; j<curves.size(); ++j)
{
glm::vec2 intX;
int num = bezierIntersectHorz(&curves[j], &intX, Y * glyphHeight / gridHeight);
for(int z=0;z<num;++z)
intersections.insert(intX[z] * gridWidth / glyphWidth);
}
// TODO: Necessary? Should never be required on a closed curve.
// (Make sure last intersection is >= gridWidth)
// if(*intersections.rbegin() < gridWidth)
// intersections.insert(gridWidth);
bool inside = false;
float start = 0;
for(auto it=intersections.begin(); it!=intersections.end(); it++)
{
float end = *it;
// printf("row %i intersection [%f, %f]\n", i, start, end);
if(inside)
{
size_t roundS = glm::clamp(round(start), (double)0.0, (double)(gridWidth));
size_t roundE = glm::clamp(round(end), (double)0.0, (double)(gridWidth));
// printf("inside, %i, %i\n", roundS, roundE);
for(size_t k=roundS;k<roundE;++k)
{
size_t gridIndex = i*gridWidth + k;
grid[gridIndex].insert(254); // Becomes 255 after +1 to remove 0s
}
}
inside = !inside;
start = end;
}
}
return grid;
}
//#pragma pack(push, 1)
//struct bitmapdata
//{
// char magic[2];
// uint32_t size;
// uint16_t res1;
// uint16_t res2;
// uint32_t offset;
//
// uint32_t biSize;
// uint32_t width;
// uint32_t height;
// uint16_t planes;
// uint16_t bitCount;
// uint32_t compression;
// uint32_t imageSizeBytes;
// uint32_t xpelsPerMeter;
// uint32_t ypelsPerMeter;
// uint32_t clrUsed;
// uint32_t clrImportant;
//};
//#pragma pack(pop)
//
//void writeBMP(const char *path, uint32_t width, uint32_t height, uint16_t channels, uint8_t *data)
//{
// FILE *f = fopen(path, "wb");
//
// bitmapdata head;
// head.magic[0] = 'B';
// head.magic[1] = 'M';
// head.size = sizeof(bitmapdata) + width*height*channels;
// head.res1 = 0;
// head.res2 = 0;
// head.offset = sizeof(bitmapdata);
// head.biSize = 40;
// head.width = width;
// head.height = height;
// head.planes = 1;
// head.bitCount = 8*channels;
// head.compression = 0;
// head.imageSizeBytes = width*height*channels;
// head.xpelsPerMeter = 0;
// head.ypelsPerMeter = 0;
// head.clrUsed = 0;
// head.clrImportant = 0;
//
// fwrite(&head, sizeof(head), 1, f);
// fwrite(data, head.imageSizeBytes, 1, f);
// fclose(f);
//}
GLFontManager::Glyph * GLFontManager::GetGlyphForCodepoint(FT_Face face, uint32_t point)
{
auto faceIt = this->glyphs.find(face);
if(faceIt != this->glyphs.end())
{
auto glyphIt = faceIt->second.find(point);
if(glyphIt != faceIt->second.end())
return &glyphIt->second;
}
AtlasGroup *atlas = this->GetOpenAtlasGroup();
// Load the glyph. FT_LOAD_NO_SCALE implies that FreeType should not
// render the glyph to a bitmap, and ensures that metrics and outline
// points are represented in font units instead of em.
FT_UInt glyphIndex = FT_Get_Char_Index(face, point);
if(FT_Load_Glyph(face, glyphIndex, FT_LOAD_NO_SCALE))
return nullptr;
FT_Pos glyphWidth = face->glyph->metrics.width;
FT_Pos glyphHeight = face->glyph->metrics.height;
uint8_t gridWidth, gridHeight;
std::vector<Bezier> curves = GetCurvesForOutline(&face->glyph->outline);
std::vector<std::set<uint16_t>> grid = GetGridForCurves(curves, glyphWidth, glyphHeight, gridWidth, gridHeight);
// Although the data is represented as a 32bit texture, it's actually
// two 16bit ints per pixel, each with an x and y coordinate for
// the bezier. Every six 16bit ints (3 pixels) is a full bezier
// Plus two pixels for grid position information
uint16_t bezierPixelLength = 2 + curves.size()*3;
if(curves.size() == 0 || grid.size() == 0 || bezierPixelLength > kBezierAtlasSize)
{
if(bezierPixelLength > kBezierAtlasSize)
printf("WARNING: Glyph %i has too many curves\n", point);
GLFontManager::Glyph glyph = {0};
glyph.bezierAtlasPos[2] = -1;
glyph.size[0] = glyphWidth;
glyph.size[1] = glyphHeight;
glyph.offset[0] = face->glyph->metrics.horiBearingX;
glyph.offset[1] = face->glyph->metrics.horiBearingY - glyphHeight;
glyph.advance = face->glyph->metrics.horiAdvance;
this->glyphs[face][point] = glyph;
return &this->glyphs[face][point];
}
// Find an open position in the bezier atlas
if(atlas->nextBezierPos[0] + bezierPixelLength > kBezierAtlasSize)
{
// Next row
atlas->nextBezierPos[1] ++;
atlas->nextBezierPos[0] = 0;
if(atlas->nextBezierPos[1] >= kBezierAtlasSize)
{
atlas->full = true;
atlas->uploaded = false;
atlas = this->GetOpenAtlasGroup();
}
}
// Find an open position in the grid atlas
if(atlas->nextGridPos[0] + kGridMaxSize > kGridAtlasSize)
{
atlas->nextGridPos[1] += kGridMaxSize;
atlas->nextGridPos[0] = 0;
if(atlas->nextGridPos[1] >= kGridAtlasSize)
{
atlas->full = true;
atlas->uploaded = false;
atlas = this->GetOpenAtlasGroup(); // Should only ever happen once per glyph
}
}
uint8_t *bezierData = atlas->bezierAtlas + (atlas->nextBezierPos[1]*kBezierAtlasSize + atlas->nextBezierPos[0])*kAtlasChannels;
uint16_t *bezierData16 = (uint16_t *)bezierData;
// TODO: The shader combines each set of bytes into 16 bit ints, which
// depends on endianness. So this currently only works on little-endian
bezierData16[0] = atlas->nextGridPos[0];
bezierData16[1] = atlas->nextGridPos[1];
bezierData16[2] = kGridMaxSize;
bezierData16[3] = kGridMaxSize;
bezierData16 += 4; // 2 pixels
for(uint32_t j=0;j<curves.size();++j)
{
// 3 pixels = 6 uint16s
// Scale coords from [0,glyphSize] to [0,maxUShort]
bezierData16[j*6+0] = curves[j].e0.x * 65535 / glyphWidth;
bezierData16[j*6+1] = curves[j].e0.y * 65535 / glyphHeight;
bezierData16[j*6+2] = curves[j].c.x * 65535 / glyphWidth;
bezierData16[j*6+3] = curves[j].c.y * 65535 / glyphHeight;
bezierData16[j*6+4] = curves[j].e1.x * 65535 / glyphWidth;
bezierData16[j*6+5] = curves[j].e1.y * 65535 / glyphHeight;
}
// Copy grid to atlas
for(uint32_t y=0;y<gridHeight;++y)
{
for(uint32_t x=0;x<gridWidth;++x)
{
size_t gridIdx = y*gridWidth + x;
size_t gridmapIdx = ((atlas->nextGridPos[1]+y)*kGridAtlasSize + (atlas->nextGridPos[0]+x))*kAtlasChannels;
size_t j = 0;
for(auto it=grid[gridIdx].begin(); it!=grid[gridIdx].end(); ++it)
{
if(j >= kAtlasChannels) // TODO: More than four beziers per pixel?
{
printf("MORE THAN 4 on %i\n", point);
break;
}
atlas->gridAtlas[gridmapIdx+j] = *it + 1;
j++;
}
}
}
GLFontManager::Glyph glyph = {0};
glyph.bezierAtlasPos[0] = atlas->nextBezierPos[0];
glyph.bezierAtlasPos[1] = atlas->nextBezierPos[1];
glyph.bezierAtlasPos[2] = this->atlases.size()-1;
glyph.size[0] = glyphWidth;
glyph.size[1] = glyphHeight;
glyph.offset[0] = face->glyph->metrics.horiBearingX;
glyph.offset[1] = face->glyph->metrics.horiBearingY - glyphHeight;
glyph.advance = face->glyph->metrics.horiAdvance;
this->glyphs[face][point] = glyph;
atlas->nextBezierPos[0] += bezierPixelLength;
atlas->nextGridPos[0] += kGridMaxSize;
atlas->uploaded = false;
//writeBMP("bezierAtlas.bmp", kBezierAtlasSize, kBezierAtlasSize, 4, atlas->bezierAtlas);
//writeBMP("gridAtlas.bmp", kGridAtlasSize, kGridAtlasSize, 4, atlas->gridAtlas);
return &this->glyphs[face][point];
}
void GLFontManager::LoadASCII(FT_Face face)
{
if(!face)
return;
this->GetGlyphForCodepoint(face, 0);
for(int i=32; i<128; ++i)
this->GetGlyphForCodepoint(face, i);
}
void GLFontManager::UploadAtlases()
{
for(size_t i=0;i<this->atlases.size();++i)
{
if(this->atlases[i].uploaded)
continue;
glBindTexture(GL_TEXTURE_2D, this->atlases[i].bezierAtlasId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, kBezierAtlasSize, kBezierAtlasSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, this->atlases[i].bezierAtlas);
glBindTexture(GL_TEXTURE_2D, this->atlases[i].gridAtlasId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, kGridAtlasSize, kGridAtlasSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, this->atlases[i].gridAtlas);
atlases[i].uploaded = true;
}
}
void GLFontManager::UseGlyphShader()
{
glUseProgram(this->glyphShader);
}
void GLFontManager::SetShaderTransform(glm::mat4 transform)
{
glUniformMatrix4fv(this->uTransform, 1, GL_FALSE, glm::value_ptr(transform));
}
void GLFontManager::UseAtlasTextures(uint16_t atlasIndex)
{
if(atlasIndex >= this->atlases.size())
return;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->atlases[atlasIndex].gridAtlasId);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, this->atlases[atlasIndex].bezierAtlasId);
}
static char32_t readNextChar(const char **p, size_t *datalen)
{
// Gets the next Unicode Code Point from a UTF8 encoded string
// (Basically converts UTF8 to UTF32 one char at a time)
// http://stackoverflow.com/questions/2948308/how-do-i-read-utf-8-characters-via-a-pointer/2953960#2953960
#define IS_IN_RANGE(c, f, l) (((c) >= (f)) && ((c) <= (l)))
unsigned char c1, c2, *ptr = (unsigned char*)(*p);
char32_t uc = 0;
int seqlen;
// int datalen = ... available length of p ...;
if( (*datalen) < 1 )
{
// malformed data, do something !!!
return (char32_t)-1;
}
c1 = ptr[0];
if((c1 & 0x80) == 0)
{
uc = (char32_t)(c1 & 0x7F);
seqlen = 1;
}
else if((c1 & 0xE0) == 0xC0)
{
uc = (char32_t)(c1 & 0x1F);
seqlen = 2;
}
else if((c1 & 0xF0) == 0xE0)
{
uc = (char32_t)(c1 & 0x0F);
seqlen = 3;
}
else if((c1 & 0xF8) == 0xF0)
{
uc = (char32_t)(c1 & 0x07);
seqlen = 4;
}
else
{
// malformed data, do something !!!
return (char32_t)-1;
}
if( seqlen > (*datalen) )
{
// malformed data, do something !!!
return (char32_t) -1;
}
for(int i = 1; i < seqlen; ++i)
{
c1 = ptr[i];
if((c1 & 0xC0) != 0x80)
{
// malformed data, do something !!!
return (char32_t)-1;
}
}
switch(seqlen)
{
case 2:
{
c1 = ptr[0];
if(!IS_IN_RANGE(c1, 0xC2, 0xDF))
{
// malformed data, do something !!!
return (char32_t)-1;
}
break;
}
case 3:
{
c1 = ptr[0];
c2 = ptr[1];
if(((c1 == 0xE0) && !IS_IN_RANGE(c2, 0xA0, 0xBF)) ||
((c1 == 0xED) && !IS_IN_RANGE(c2, 0x80, 0x9F)) ||
(!IS_IN_RANGE(c1, 0xE1, 0xEC) && !IS_IN_RANGE(c1, 0xEE, 0xEF)))
{
// malformed data, do something !!!
return (char32_t)-1;
}
break;
}
case 4:
{
c1 = ptr[0];
c2 = ptr[1];
if(((c1 == 0xF0) && !IS_IN_RANGE(c2, 0x90, 0xBF)) ||
((c1 == 0xF4) && !IS_IN_RANGE(c2, 0x80, 0x8F)) ||
!IS_IN_RANGE(c1, 0xF0, 0xF4)) //0xF1, 0xF3) ) // Modified because originally, no 4-byte characters would pass
{
// malformed data, do something !!!
return (char32_t)-1;
}