Text shaping done more or less right
Francesco Pasa 9 months ago
Francesco Pasa 9 months ago
CMakeLists.txt M +9
82 GIT_SHALLOW TRUE
83 )
84
85+# ICU (unused)
86+FetchContent_Declare(
87+ icu
88+ GIT_REPOSITORY https://github.com/unicode-org/icu.git
89+ GIT_TAG release-75-1
90+ GIT_SHALLOW TRUE
91+)
92+
93 #FetchContent_Declare(
94 # https://github.com/madler/zlib.git
95 #)
102 include_directories("${harfbuzz_SOURCE_DIR}/include")
103 include_directories("${hashmap_SOURCE_DIR}")
104 include_directories("${png_SOURCE_DIR}")
105+#include_directories("${icu_SOURCE_DIR}")
106
107 include_directories("${check_SOURCE_DIR}/src")
108 include_directories("${check_BINARY_DIR}")
examples/text.c M +6 -4
8 options.clear_color.b = 0.02;
9 AlbaWindow* window = alba_create_window(&options);
10
11- const AlbaString text1 = alba_create_string("7 lm francesco", 0);
12+ const AlbaString text1 = alba_create_string("7 lm francesco ß AVA fi ff", 0);
13 alba_draw_text(window, (AlbaVector){100, 100}, text1, (AlbaTextStyle){.font_size = 28});
14
15- // alba_draw_text(window, (AlbaVector){100, 150}, (AlbaColor)WHITE, 0, "ß 🍔");
16+ const AlbaString text2 = alba_create_string("Дуо вёжи дёжжэнтиюнт ут हालाँकि प्रचलित रूप पूजा 🍔", 0);
17+ alba_draw_text(window, (AlbaVector){100, 150}, text2, (AlbaTextStyle){0});
18
19- const AlbaString text2 = alba_create_string(
20+ const AlbaString text3 = alba_create_string(
21 "DESCRIPTION\n The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free(). The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free(). If the multiplication of nmemb and size would result in integer overflow, then calloc() returns an error. By contrast, an integer overflow would not be detected in the following call to malloc(), with the result that an incorrectly sized block of memory would be allocated: malloc(nmemb * size); The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc(), or realloc(). If the area pointed to was moved, a free(ptr) is done. The reallocarray() function changes the size of the memory block pointed to by ptr to be large enough for an array of nmemb elements, each of which is size bytes. It is equivalent to the call realloc(ptr, nmemb * size); However, unlike that realloc() call, reallocarray() fails safely in the case where the multiplication would overflow. If such an overflow occurs, reallocarray() returns NULL, sets errno to ENOMEM, and leaves the original block of memory unchanged. RETURN VALUE The malloc() and calloc() functions return a pointer to the allocated memory, which is suitably aligned for any built-in type. On error, these functions return NULL. N",
22 0
23 );
24- alba_draw_text(window, (AlbaVector){100, 200}, text2, (AlbaTextStyle){0});
25+ alba_draw_text(window, (AlbaVector){100, 200}, text3, (AlbaTextStyle){0});
26
27 while (!alba_window_should_close(window))
28 {
27
28 alba_string_release(&text1);
29 alba_string_release(&text2);
30+ alba_string_release(&text3);
31
32 alba_window_release(window);
33 alba_release();
src/atlas.c M +5 -5
11 {
12 const AlbaGlyph* a = va;
13 const AlbaGlyph* b = vb;
14- return a->character - b->character;
15+ return a->codepoint - b->codepoint;
16 }
17
18 void free_glyph(void* vglyph)
36 alba_array_reserve(&atlas->glyph_sizes, capacity * 4);
37 }
38
39-void atlas_append(Atlas* atlas, const FT_Face face, const uint32_t character, const AlbaTextStyle style)
40+void atlas_append(Atlas* atlas, const FT_Face face, const uint32_t codepoint, const AlbaTextStyle style)
41 {
42 AlbaGlyph glyph = {
43- .character = character,
44+ .codepoint = codepoint,
45 .style = style,
46 };
47 if (hashmap_get(atlas->glyphs, &glyph) == NULL)
48 {
49- const FT_Long glyph_index = FT_Load_Char(face, character, FT_LOAD_RENDER);
50+ const FT_Long glyph_index = FT_Load_Glyph(face, codepoint, FT_LOAD_RENDER);
51
52 const FT_Bitmap* bitmap = &face->glyph->bitmap;
53 glyph.glyph_index = glyph_index;
192 printf(
193 "error: font atlas too big (> 8192*8192 pixels). "
194 "Consider reducing the number of fonts, text sizes "
195- "(especially large sizes) or characters in use."
196+ "(especially large sizes) or different characters in use."
197 );
198 exit(1);
199 }
src/internal.h M +8 -4
7
8 #include "GLFW/glfw3.h"
9 #include "hashmap.h"
10+#include "hb.h"
11
12 #define NO_TEXTURE {-1, -1}
13
14 // Window
15 typedef struct
16 {
17- AlbaString string;
18+ AlbaString string; // needed?
19 AlbaVector position;
20 // Make part of style?
21- FT_Face face;
22+ FT_Face face; // needed?
23 AlbaTextStyle style;
24+ uint32_t glyph_count;
25+ hb_glyph_info_t* glyphs_infos;
26+ hb_glyph_position_t* glyph_positions;
27 } Text;
28
29 typedef struct
78 typedef struct
79 {
80 // Key properties
81- uint32_t character;
82+ uint32_t codepoint;
83 AlbaTextStyle style;
84 // Other properties used during atlas creation
85 // and text rendering
100
101 Atlas create_atlas(uint32_t capacity);
102 void atlas_reserve(Atlas* atlas, uint32_t capacity);
103-void atlas_append(Atlas* atlas, FT_Face face, uint32_t character, AlbaTextStyle style);
104+void atlas_append(Atlas* atlas, FT_Face face, uint32_t codepoint, AlbaTextStyle style);
105 void atlas_generate_image(Atlas* atlas);
106 void atlas_release(const Atlas* atlas);
107
src/text.c M +49 -20
4 #include "internal.h"
5
6 #include "freetype/ftglyph.h"
7+#include "hb.h"
8+#include "hb-ft.h"
9
10 extern char _binary_Roboto_Regular_ttf_start[];
11 extern char _binary_Roboto_Regular_ttf_end[];
45 pthread_mutex_unlock(&freetype_mutex);
46 }
47
48-void atlas_add_chars(Atlas* atlas, const AlbaString string, const AlbaTextStyle style)
49+void atlas_add_chars(
50+ Atlas* atlas,
51+ const uint32_t glyph_count, const hb_glyph_info_t* glyph_infos,
52+ const AlbaTextStyle style
53+)
54 {
55- const char* text = alba_string_to_char(&string);
56- for (uint64_t i = 0; i < string.length; i++)
57+ for (uint32_t i = 0; i < glyph_count; i++)
58 {
59- atlas_append(atlas, roboto, text[i], style); // TODO: unicode
60+ atlas_append(atlas, roboto, glyph_infos[i].codepoint, style);
61 }
62 }
63
69 DrawCall* draw_call
70 )
71 {
72- const AlbaString string = text->string;
73 const AlbaTextStyle style = text->style;
74 AlbaArray* vertices = &draw_call->new_vertices;
75 AlbaArray* attributes = &draw_call->new_attributes;
76 AlbaArray* indices = &draw_call->new_indices;
77
78- alba_array_reserve(vertices, vertices->length + string.length * 4);
79- alba_array_reserve(attributes, attributes->length + string.length * 4);
80- alba_array_reserve(indices, indices->length + string.length * 6);
81+ alba_array_reserve(vertices, vertices->length + text->glyph_count * 4);
82+ alba_array_reserve(attributes, attributes->length + text->glyph_count * 4);
83+ alba_array_reserve(indices, indices->length + text->glyph_count * 6);
84
85- const char* string_char = alba_string_to_char(&string);
86 AlbaVector current = text->position;
87- for (uint64_t i = 0; i < string.length; i++)
88+ for (uint32_t i = 0; i < text->glyph_count; i++)
89 {
90 // TODO: mutex?
91- const FT_Long character = string_char[i]; // TODO: unicode
92+ const uint32_t codepoint = text->glyphs_infos[i].codepoint;
93 const AlbaGlyph* glyph = hashmap_get(
94 atlas->glyphs,
95 &(AlbaGlyph){
96- .character = character,
97+ .codepoint = codepoint,
98 .style = style
99 }
100 );
101 if (glyph == NULL)
102 {
103- fprintf(stderr, "error: unable to find glyph for character '%s'\n", (char*)&character);
104+ fprintf(stderr, "error: unable to find glyph for codepoint '%s'\n", (char*)&codepoint);
105 exit(1);
106 }
107+
108+ const hb_glyph_position_t* pos = &text->glyph_positions[i];
109 const FT_Glyph_Metrics metrics = glyph->metrics;
110
111 // All these / 64 are because FreeType reports metrics in 1/64th of pixel
112 const AlbaVector origin = {
113- current.x + metrics.horiBearingX / 64 / window->scale.x,
114- current.y - metrics.horiBearingY / 64 / window->scale.y,
115+ current.x + pos->x_offset / 64 + metrics.horiBearingX / 64 / window->scale.x,
116+ current.y - metrics.horiBearingY / 64 / window->scale.y, // TODO: offset
117 };
118 // Divide by scaling to correct the scaling applied by the shader.
119 // We do not want scaling text geometry to avoid making text blurry.
138 vertex_count + 3
139 });
140
141- current.x += metrics.horiAdvance / 64 / window->scale.x;
142+ current.x += pos->x_advance / 64 / window->scale.x;
143+ // TODO: vertical
144 }
145 }
146
164 if (style.font_size == 0) style.font_size = 16;
165 if (alba_color_is_transparent(&style.color)) style.color = (AlbaColor)WHITE;
166
167+ const char* chars = alba_string_to_char(&string);
168+ hb_buffer_t* buffer = hb_buffer_create();
169+
170+ // TODO: remove assumption that string is in a single script
171+ const hb_script_t script = HB_SCRIPT_LATIN;
172+ hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
173+ hb_buffer_set_script(buffer, script);
174+
175+ // TODO: remove assumption that string is in a single language
176+ hb_buffer_set_language(buffer, hb_language_from_string("en", -1));
177+
178+ hb_buffer_add_utf8(buffer, chars, string.length, 0, string.length);
179+
180 pthread_mutex_lock(&freetype_mutex);
181+ // This is necessary now as we will render codepoints in the next call
182 const FT_Error error = FT_Set_Pixel_Sizes(
183 roboto,
184 style.font_size * window->scale.x,
189 fprintf(stderr, "error: cound not set Roboto face size");
190 }
191
192- atlas_add_chars(&atlas, string, style);
193- pthread_mutex_unlock(&freetype_mutex);
194+ const hb_feature_t features[] = {
195+ {HB_TAG('l', 'i', 'g', 'a'), 1, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END},
196+ };
197+
198+ hb_font_t* hb_font = hb_ft_font_create_referenced(roboto); // TODO: free
199+ hb_shape(hb_font, buffer, features, 1);
200
201- const Text text_obj = {
202+ Text text = {
203 .string = string,
204 .position = pos,
205 .face = roboto,
206 .style = style,
207 };
208+ text.glyphs_infos = hb_buffer_get_glyph_infos(buffer, &text.glyph_count);
209+ text.glyph_positions = hb_buffer_get_glyph_positions(buffer, &text.glyph_count);
210+
211+ atlas_add_chars(&atlas, text.glyph_count, text.glyphs_infos, style);
212+ pthread_mutex_unlock(&freetype_mutex);
213
214 DrawCall* draw_call = alba_array_last(&window->draw_calls);
215 if (draw_call->texture_set)
216 {
217 draw_call = window_create_draw_call(window);
218 }
219- alba_array_append(&draw_call->new_texts, &text_obj);
220+ alba_array_append(&draw_call->new_texts, &text);
221 draw_call->text_dirty = 1;
222 }
223