-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathfont.cpp
More file actions
3649 lines (3431 loc) · 57.8 KB
/
font.cpp
File metadata and controls
3649 lines (3431 loc) · 57.8 KB
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
#include <fstream>
#include <ft2build.h>
#include <freetype/freetype.h>
#include <freetype/ftglyph.h>
#include <freetype/ftsynth.h>
#include <mutex>
#include "freetype/ftcache.h"
#include "freetype/ftbitmap.h"
#include "freetype/ftsizes.h"
#include "draw_manager.hpp"
#define ARRAY_SIZE(x) ((int)(sizeof(x)/sizeof(*x)))
#define STBRP_ASSERT(x) assert(x)
#define STBRP_STATIC
#define STB_RECT_PACK_IMPLEMENTATION
#include <stb/stb_rectpack.h>
const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000;
using namespace util::draw;
#pragma region font_utils
void* load_file_to_mem(const char *filename, size_t *data_size)
{
std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);
if (!file.is_open())
return nullptr;
const auto file_size = file.tellg();
const auto file_data = reinterpret_cast<char*>(malloc(static_cast<std::size_t>(file_size)));
file.seekg(0, std::ios::beg);
file.read(file_data, file_size);
file.close();
*data_size = static_cast<std::size_t>(file_size);
return file_data;
}
template<typename ...args>
size_t format_string(char *buf, const size_t buf_size, const char *fmt, args ... arg_list)
{
auto req_size = snprintf(buf, buf_size, fmt, arg_list...);
if (!buf)
return req_size;
if (req_size == -1 || req_size >= static_cast<int32_t>(buf_size))
req_size = static_cast<int32_t>(buf_size) - 1;
buf[req_size] = 0;
return req_size;
}
int text_char_from_utf8(unsigned int *out_char, const char *in_text, const char *in_text_end)
{
auto c = -1;
const auto *str = reinterpret_cast<const unsigned char*>(in_text);
if (!(*str & 0x80))
{
c = static_cast<uint32_t>(*str++);
*out_char = c;
return 1;
}
if ((*str & 0xe0) == 0xc0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - reinterpret_cast<const char*>(str) < 2)
return 1;
if (*str < 0xc2)
return 2;
c = static_cast<uint32_t>((*str++ & 0x1f) << 6);
if ((*str & 0xc0) != 0x80)
return 2;
c += (*str++ & 0x3f);
*out_char = c;
return 2;
}
if ((*str & 0xf0) == 0xe0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - reinterpret_cast<const char*>(str) < 3)
return 1;
if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf))
return 3;
if (*str == 0xed && str[1] > 0x9f)
return 3; // str[1] < 0x80 is checked below
c = static_cast<uint32_t>((*str++ & 0x0f) << 12);
if ((*str & 0xc0) != 0x80)
return 3;
c += static_cast<uint32_t>((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80)
return 3;
c += (*str++ & 0x3f);
*out_char = c;
return 3;
}
if ((*str & 0xf8) == 0xf0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - reinterpret_cast<const char*>(str) < 4)
return 1;
if (*str > 0xf4)
return 4;
if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf))
return 4;
if (*str == 0xf4 && str[1] > 0x8f)
return 4; // str[1] < 0x80 is checked below
c = static_cast<uint32_t>((*str++ & 0x07) << 18);
if ((*str & 0xc0) != 0x80)
return 4;
c += static_cast<uint32_t>((*str++ & 0x3f) << 12);
if ((*str & 0xc0) != 0x80)
return 4;
c += static_cast<uint32_t>((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80)
return 4;
c += (*str++ & 0x3f);
// utf-8 encodings of values used in surrogate pairs are invalid
if ((c & 0xFFFFF800) == 0xD800)
return 4;
*out_char = c;
return 4;
}
*out_char = 0;
return 0;
}
static inline int upper_power_of_two(int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
#pragma endregion
#pragma region font_config
font_config::font_config()
{
font_data = nullptr;
font_data_size = 0;
owned_by_atlas = true;
font_idx = 0;
size_pixels = 0.f;
oversample_h = 3;
oversample_v = 1;
pixel_snap_h = false;
glyph_extra_spacing = position{0.f, 0.f};
glyph_offset = position{0.f, 0.f};
glyph_ranges = nullptr;
glyph_min_advance = 0.f;
glyph_max_advance = FLT_MAX;
merge_mode = false;
rasterizer_flags = 0;
rasterizer_multiply = 1.f;
dst_font = nullptr;
}
#pragma endregion
#pragma region font
// From SDL_ttf : Handy routines for converting from fixed point
template<typename t>
t FT_CEIL(const t x)
{
static_assert(std::is_fundamental_v<t>, "FT_CEIL not used with fundamental type.");
return ((x + 63) & -64) / 64;
}
font::font()
{
scale = 1.f;
fallback_char = static_cast<font_wchar>('?');
display_offset = position{0.f, 0.f};
clear_output_data();
}
font::~font()
{
clear_output_data();
}
bool font::init(const font_config &cfg, const uint32_t user_flags)
{
auto result = FT_Init_FreeType(&freetype_library);
if (result)
return false;
result = FT_New_Memory_Face(freetype_library,
reinterpret_cast<uint8_t*>(cfg.font_data),
cfg.font_data_size,
cfg.font_idx,
&freetype_face);
if (result)
return false;
result = FT_Select_Charmap(freetype_face, FT_ENCODING_UNICODE);
if (result)
return false;
info = {};
set_pixel_height(static_cast<std::size_t>(cfg.size_pixels));
this->user_flags = cfg.rasterizer_flags | user_flags;
freetype_load_flags = FT_LOAD_NO_BITMAP;
if (this->user_flags & NO_HINTING)
freetype_load_flags |= FT_LOAD_NO_HINTING;
if (this->user_flags & NO_AUTO_HINT)
freetype_load_flags |= FT_LOAD_NO_AUTOHINT;
if (this->user_flags & FORCE_AUTO_HINT)
freetype_load_flags |= FT_LOAD_FORCE_AUTOHINT;
if (this->user_flags & LIGHT_HINTING)
freetype_load_flags |= FT_LOAD_TARGET_LIGHT;
else if (this->user_flags & MONO_HINTING)
freetype_load_flags |= FT_LOAD_TARGET_MONO;
else
freetype_load_flags |= FT_LOAD_TARGET_NORMAL;
return true;
}
void font::shutdown()
{
if (!freetype_face)
return;
FT_Done_Face(freetype_face);
freetype_face = nullptr;
FT_Done_FreeType(freetype_library);
freetype_library = nullptr;
}
void font::set_pixel_height(uint32_t pixel_height)
{
FT_Size_RequestRec req;
req.type = FT_SIZE_REQUEST_TYPE_REAL_DIM;
req.width = 0;
req.height = pixel_height * 64;
req.horiResolution = 0;
req.vertResolution = 0;
FT_Request_Size(freetype_face, &req); //TODO: err
const auto &metrics = freetype_face->size->metrics;
info.pixel_height = pixel_height;
info.ascender = static_cast<float>(FT_CEIL(metrics.ascender));
info.descender = static_cast<float>(FT_CEIL(metrics.descender));
info.line_spacing = static_cast<float>(FT_CEIL(metrics.height));
info.line_gap = static_cast<float>(FT_CEIL(metrics.height - metrics.ascender + metrics.descender));
info.max_advance_width = static_cast<float>(FT_CEIL(metrics.max_advance));
}
bool font::calc_glyph_info(const uint32_t codepoint,
glyph_info &glyph_info,
FT_Glyph &ft_glyph,
FT_BitmapGlyph &ft_bitmap) const
{
const auto glyph_idx = FT_Get_Char_Index(freetype_face, codepoint);
if (!glyph_idx)
return false;
auto result = FT_Load_Glyph(freetype_face, glyph_idx, freetype_load_flags);
if (result)
return false;
//Need an outline for this to work
const auto slot = freetype_face->glyph;
assert(slot->format == FT_GLYPH_FORMAT_OUTLINE);
if (user_flags & BOLD)
FT_GlyphSlot_Embolden(slot);
if (user_flags & OBLIQUE)
FT_GlyphSlot_Oblique(slot);
//Retrieve Glyph
result = FT_Get_Glyph(slot, &ft_glyph);
if (result)
return false;
//Rasterize
result = FT_Glyph_To_Bitmap(&ft_glyph, FT_RENDER_MODE_NORMAL, nullptr, true);
if (result)
return false;
ft_bitmap = reinterpret_cast<FT_BitmapGlyph>(ft_glyph);
glyph_info.advance_x = static_cast<float>(FT_CEIL(slot->advance.x));
glyph_info.offset_x = static_cast<float>(ft_bitmap->left);
glyph_info.offset_y = static_cast<float>(-ft_bitmap->top);
glyph_info.width = static_cast<float>(ft_bitmap->bitmap.width);
glyph_info.height = static_cast<float>(ft_bitmap->bitmap.rows);
return true;
}
void font::blit_glyph(const FT_BitmapGlyph ft_bitmap,
uint8_t *dst,
const uint32_t dst_pitch,
const unsigned char *multiply_table) const
{
assert(ft_bitmap != nullptr);
const auto w = ft_bitmap->bitmap.width;
const auto h = ft_bitmap->bitmap.rows;
auto src = ft_bitmap->bitmap.buffer;
const auto src_pitch = ft_bitmap->bitmap.pitch;
for (auto y = 0u; y < h; y++, src += src_pitch, dst += dst_pitch)
{
if (multiply_table)
{
for (auto x = 0u; x < w; x++)
dst[x] = multiply_table[src[x]];
}
else
{
memcpy(dst, src, w);
}
}
}
void font::clear_output_data()
{
font_size = 0.f;
glyphs.clear();
index_advance_x.clear();
index_lookup.clear();
index_glyph_y.clear();
fallback_glyph = nullptr;
fallback_advance_x = 0.f;
config_data_count = 0;
config_data = nullptr;
container_atlas = nullptr;
ascent = descent = 0.f;
dirty_lookup_tables = true;
metrics_total_surface = 0;
}
void font::build_lookup_table()
{
auto max_codepoint = 0;
for (const auto &glyph : glyphs)
max_codepoint = std::max(max_codepoint, static_cast<int32_t>(glyph.codepoint));
assert(glyphs.size() < 0xFFFF);
index_advance_x.clear();
index_lookup.clear();
dirty_lookup_tables = false;
grow_index(max_codepoint + 1);
for (auto i = 0u; i < glyphs.size(); i++)
{
const auto codepoint = static_cast<int32_t>(glyphs[i].codepoint);
index_advance_x[codepoint] = glyphs[i].advance_x;
index_glyph_y[codepoint] = glyphs[i].y1;
index_lookup[codepoint] = i;
}
if (find_glyph(static_cast<font_wchar>(' ')))
{
if (glyphs.back().codepoint != '\t')
glyphs.resize(glyphs.size() + 1);
auto &tab_glyph = glyphs.back();
tab_glyph = *find_glyph(static_cast<font_wchar>(' '));
tab_glyph.codepoint = '\t';
tab_glyph.advance_x *= 4;
index_advance_x[tab_glyph.codepoint] = tab_glyph.advance_x;
index_lookup[tab_glyph.codepoint] = static_cast<font_wchar>(glyphs.size() - 1);
index_glyph_y[tab_glyph.codepoint] = font_size;
}
fallback_glyph = find_glyph_no_fallback(fallback_char);
fallback_advance_x = fallback_glyph ? fallback_glyph->advance_x : 0.f;
for (auto i = 0; i < max_codepoint + 1; i++)
if (index_advance_x[i] < 0.f)
index_advance_x[i] = fallback_advance_x;
}
void font::set_fallback_char(font_wchar c)
{
fallback_char = c;
build_lookup_table();
}
void font::grow_index(const size_t new_size)
{
assert(index_advance_x.size() == index_lookup.size());
if (new_size <= index_lookup.size())
return;
index_advance_x.resize(new_size, -1.f);
index_lookup.resize(new_size, -1);
index_glyph_y.resize(new_size, -1);
}
void font::add_glyph(const font_wchar c,
const float x0,
const float y0,
const float x1,
const float y1,
const float u0,
const float v0,
const float u1,
const float v1,
const float advance_x)
{
glyphs.resize(glyphs.size() + 1);
auto &glyph = glyphs.back();
glyph.codepoint = c;
glyph.x0 = x0;
glyph.y0 = y0;
glyph.x1 = x1;
glyph.y1 = y1;
glyph.u0 = u0;
glyph.v0 = v0;
glyph.u1 = u1;
glyph.v1 = v1;
glyph.advance_x = advance_x + config_data->glyph_extra_spacing.x;
if (config_data->pixel_snap_h)
glyph.advance_x = std::roundf(glyph.advance_x);
dirty_lookup_tables = true;
metrics_total_surface = static_cast<int32_t>((glyph.u1 - glyph.u0) * container_atlas->tex_width + 1.99f) *
static_cast<int32_t>((glyph.v1 - glyph.v0) * container_atlas->tex_height + 1.99f);
}
void font::add_remap_char(const font_wchar dst, const font_wchar src, const bool overwrite_dst)
{
const auto index_size = index_lookup.size();
assert(index_size > 0);
if (dst < index_size && index_lookup[dst] == 0xFFFF && !overwrite_dst) //dst exists
return;
if (src >= index_size && dst >= index_size) //src & dst dont exist
return;
grow_index(dst + 1);
index_lookup[dst] = (src < index_size) ? index_lookup[src] : -1;
index_advance_x[dst] = (src < index_size) ? index_advance_x[src] : 1.f;
}
const font_glyph* font::find_glyph(const font_wchar c) const
{
if (c >= index_lookup.size())
return fallback_glyph;
const auto i = index_lookup[c];
if (i == 0xFFFF)
return fallback_glyph;
return &glyphs[i];
}
const font_glyph* font::find_glyph_no_fallback(font_wchar c) const
{
if (c >= index_lookup.size())
return nullptr;
const auto i = index_lookup[c];
if (i == 0xFFFF)
return nullptr;
return &glyphs[i];
}
const char* font::calc_word_wrap_pos(float scale, const char *text, const char *text_end, float wrap_width) const
{
//TODO: Blatant c&p
// Simple word-wrapping for English, not full-featured. Please submit failing cases!
// FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.)
// For references, possible wrap point marked with ^
// "aaa bbb, ccc,ddd. eee fff. ggg!"
// ^ ^ ^ ^ ^__ ^ ^
// List of hardcoded separators: .,;!?'"
// Skip extra blanks after a line returns (that includes not counting them in width computation)
// e.g. "Hello world" --> "Hello" "World"
// Cut words that cannot possibly fit within one line.
// e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish"
auto line_width = 0.0f;
auto word_width = 0.0f;
auto blank_width = 0.0f;
wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters
auto word_end = text;
const char *prev_word_end = nullptr;
auto inside_word = true;
auto s = text;
while (s < text_end)
{
auto c = static_cast<uint32_t>(*s);
const char *next_s;
if (c < 0x80)
next_s = s + 1;
else
next_s = s + text_char_from_utf8(&c, s, text_end);
if (c == 0)
break;
if (c < 32)
{
if (c == '\n')
{
line_width = word_width = blank_width = 0.0f;
inside_word = true;
s = next_s;
continue;
}
if (c == '\r')
{
s = next_s;
continue;
}
}
const float char_width = (c < index_advance_x.size() ? index_advance_x[c] : fallback_advance_x);
if (c == ' ' || c == '\t' || c == 0x3000)
{
if (inside_word)
{
line_width += blank_width;
blank_width = 0.0f;
word_end = s;
}
blank_width += char_width;
inside_word = false;
}
else
{
word_width += char_width;
if (inside_word)
{
word_end = next_s;
}
else
{
prev_word_end = word_end;
line_width += word_width + blank_width;
word_width = blank_width = 0.0f;
}
// Allow wrapping after punctuation.
inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"');
}
// We ignore blank width at the end of the line (they can be skipped)
if (line_width + word_width >= wrap_width)
{
// Words that cannot possibly fit within an entire line will be cut anywhere.
if (word_width < wrap_width)
s = prev_word_end ? prev_word_end : word_end;
break;
}
s = next_s;
}
return s;
}
position font::calc_text_size(const float size,
const float max_width,
const float wrap_width,
const char *text_begin,
const char *text_end,
const char **remaining) const
{
if (!text_end)
text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this.
const auto line_height = size;
const auto scale = size / font_size;
auto text_size = position{0.f, 0.f};
auto line_width = 0.0f;
const auto word_wrap_enabled = (wrap_width > 0.0f);
const char *word_wrap_eol = nullptr;
auto s = text_begin;
while (s < text_end)
{
if (word_wrap_enabled)
{
// Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.
if (!word_wrap_eol)
{
word_wrap_eol = calc_word_wrap_pos(scale, s, text_end, wrap_width - line_width);
if (word_wrap_eol == s)
// Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity.
word_wrap_eol++;
// +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below
}
if (s >= word_wrap_eol)
{
if (text_size.x < line_width)
text_size.x = line_width;
text_size.y += line_height;
line_width = 0.0f;
word_wrap_eol = nullptr;
// Wrapping skips upcoming blanks
while (s < text_end)
{
const char c = *s;
if (c == ' ' || c == '\t' || c == 0x3000)
{
s++;
}
else if (c == '\n')
{
s++;
break;
}
else
{
break;
}
}
continue;
}
}
// Decode and advance source
const auto prev_s = s;
auto c = static_cast<uint32_t>(*s);
if (c < 0x80)
{
s += 1;
}
else
{
s += text_char_from_utf8(&c, s, text_end);
if (c == 0) // Malformed UTF-8?
break;
}
if (c < 32)
{
if (c == '\n')
{
text_size.x = std::max(text_size.x, line_width);
text_size.y += line_height;
line_width = 0.0f;
continue;
}
if (c == '\r')
continue;
}
const auto char_width = (c < index_advance_x.size() ? index_advance_x[c] : fallback_advance_x) * scale;
if (line_width + char_width >= max_width)
{
s = prev_s;
break;
}
line_width += char_width;
}
if (text_size.x < line_width)
text_size.x = line_width;
if (line_width > 0 || text_size.y == 0.0f)
text_size.y += line_height;
if (remaining)
*remaining = s;
return text_size;
}
rect font::calc_text_bounds(const float size,
const float max_width,
const float wrap_width,
const char *text_begin,
const char *text_end,
const char **remaining) const
{
if (!text_end)
text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this.
auto line_height = 0.f;
auto offset_y = FLT_MAX;
const auto scale = size / font_size;
auto text_size = position{0.f, 0.f};
auto line_width = 0.0f;
auto first_char_of_line = true;
const auto word_wrap_enabled = (wrap_width > 0.0f);
const char *word_wrap_eol = nullptr;
auto s = text_begin;
while (s < text_end)
{
if (word_wrap_enabled)
{
// Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.
if (!word_wrap_eol)
{
word_wrap_eol = calc_word_wrap_pos(scale, s, text_end, wrap_width - line_width);
if (word_wrap_eol == s)
// Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity.
word_wrap_eol++;
// +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below
}
if (s >= word_wrap_eol)
{
if (text_size.x < line_width)
text_size.x = line_width;
text_size.y += line_height;
line_width = 0.0f;
word_wrap_eol = nullptr;
// Wrapping skips upcoming blanks
while (s < text_end)
{
const char c = *s;
if (c == ' ' || c == '\t' || c == 0x3000)
{
s++;
}
else if (c == '\n')
{
s++;
break;
}
else
{
break;
}
}
continue;
}
}
// Decode and advance source
const auto prev_s = s;
auto c = static_cast<uint32_t>(*s);
if (c < 0x80)
{
s += 1;
}
else
{
s += text_char_from_utf8(&c, s, text_end);
if (c == 0) // Malformed UTF-8?
break;
}
if (c < 32)
{
if (c == '\n')
{
text_size.x = std::max(text_size.x, line_width);
text_size.y += line_height;
line_width = 0.0f;
line_height = 0.f;
first_char_of_line = true;
continue;
}
if (c == '\r')
continue;
}
const auto glyph_info = find_glyph(c);
const auto char_width = glyph_info->advance_x * scale;
if (line_width + char_width >= max_width)
{
s = prev_s;
break;
}
if (first_char_of_line)
{
first_char_of_line = false;
line_width += glyph_info->x0 * scale;
}
line_width += char_width;
line_height = std::max(line_height, glyph_info->y1 * scale);
offset_y = std::min(offset_y, glyph_info->y0 * scale);
}
if (text_size.x < line_width)
text_size.x = line_width;
if (line_width > 0 || text_size.y == 0.0f)
text_size.y += line_height;
if (remaining)
*remaining = s;
return rect{0.f, offset_y, line_width, line_height};
}
void font::render_char(draw_buffer *draw_buffer,
const float size,
position pos,
const pack_color col,
const font_wchar c) const
{
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
return;
if (const auto glyph = find_glyph(c))
{
const auto scale = (size >= 0.f) ? (size / font_size) : 1.f;
pos.x = static_cast<float>(static_cast<int>(pos.x + display_offset.x));
pos.y = static_cast<float>(static_cast<int>(pos.y + display_offset.y));
draw_buffer->prim_reserve(6, 4);
draw_buffer->prim_rect_uv(position{pos.x + glyph->x0 * scale, pos.y + glyph->y0 * scale},
position{pos.x + glyph->x1 * scale, pos.y + glyph->y1 * scale},
position{glyph->u0, glyph->v0},
position{glyph->u1, glyph->v1},
col);
}
}
void font::render_text(draw_buffer *draw_buffer,
const float size,
position pos,
const pack_color col,
const rect &clip_rect,
const char *text_begin,
const char *text_end,
const float wrap_width,
const bool cpu_fine_clip) const
{
//TODO: more c&p
if (!text_end)
text_end = text_begin + strlen(text_begin);
// ImGui functions generally already provides a valid text_end, so this is merely to handle direct calls.
// Align to be pixel perfect
pos.x = static_cast<float>(static_cast<int>(pos.x + display_offset.x));
pos.y = static_cast<float>(static_cast<int>(pos.y + display_offset.y));
auto x = pos.x;
auto y = pos.y;
if (y > clip_rect.w)
return;
const auto scale = size / font_size;
const auto line_height = font_size * scale;
const auto word_wrap_enabled = (wrap_width > 0.0f);
const char *word_wrap_eol = nullptr;
// Fast-forward to first visible line
auto s = text_begin;
if (y + line_height < clip_rect.y && !word_wrap_enabled)
while (y + line_height < clip_rect.y && s < text_end)
{
s = reinterpret_cast<const char*>(memchr(s, '\n', text_end - s));
s = s ? s + 1 : text_end;
y += line_height;
}
// For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve()
// Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm)
if (text_end - s > 10000 && !word_wrap_enabled)
{
const char *s_end = s;
float y_end = y;
while (y_end < clip_rect.w && s_end < text_end)
{
s_end = reinterpret_cast<const char*>(memchr(s_end, '\n', text_end - s_end));
s = s ? s + 1 : text_end;
y_end += line_height;
}
text_end = s_end;
}
if (s == text_end)
return;
// Reserve vertices for remaining worse case (over-reserving is useful and easily amortized)
const auto vtx_count_max = static_cast<int32_t>(text_end - s) * 4;
const auto idx_count_max = static_cast<int32_t>(text_end - s) * 6;
const auto idx_expected_size = draw_buffer->indices.size() + idx_count_max;
const auto vtx_expected_size = draw_buffer->vertices.size() + vtx_count_max;
draw_buffer->prim_reserve(idx_count_max, vtx_count_max);
auto vtx_write = draw_buffer->vtx_write_ptr;
auto idx_write = draw_buffer->idx_write_ptr;
auto vtx_current_idx = draw_buffer->cur_idx;
while (s < text_end)
{
if (word_wrap_enabled)
{
// Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.
if (!word_wrap_eol)
{
word_wrap_eol = calc_word_wrap_pos(scale, s, text_end, wrap_width - (x - pos.x));
if (word_wrap_eol == s)
// Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity.
word_wrap_eol++;
// +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below
}
if (s >= word_wrap_eol)
{
x = pos.x;
y += line_height;
word_wrap_eol = nullptr;
// Wrapping skips upcoming blanks
while (s < text_end)
{
const char c = *s;
if (c == ' ' || c == '\t' || c == 0x3000)
{
s++;
}
else if (c == '\n')
{
s++;
break;
}
else
{
break;
}
}
continue;
}
}
// Decode and advance source
auto c = static_cast<uint32_t>(*s);
if (c < 0x80)
{
s += 1;
}
else
{
s += text_char_from_utf8(&c, s, text_end);
if (c == 0) // Malformed UTF-8?
break;
}
if (c < 32)
{
if (c == '\n')
{
x = pos.x;
y += line_height;
if (y > clip_rect.w)
break; // break out of main loop
continue;
}
if (c == '\r')
continue;
}
auto char_width = 0.0f;
if (const auto glyph = find_glyph(static_cast<font_wchar>(c)))
{
char_width = glyph->advance_x * scale;
// Arbitrarily assume that both space and tabs are empty glyphs as an optimization
if (c != ' ' && c != '\t')
{
// We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w
float x1 = x + glyph->x0 * scale;
float x2 = x + glyph->x1 * scale;
float y1 = y + glyph->y0 * scale;
float y2 = y + glyph->y1 * scale;
if (x1 <= clip_rect.z && x2 >= clip_rect.x)
{
// Render a character
float u1 = glyph->u0;
float v1 = glyph->v0;
float u2 = glyph->u1;
float v2 = glyph->v1;
// CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads.
if (cpu_fine_clip)
{
if (x1 < clip_rect.x)
{
u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1);
x1 = clip_rect.x;
}
if (y1 < clip_rect.y)
{
v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1);
y1 = clip_rect.y;
}