src/text.c
 1#include "alba.h"
 2
 3#include <pthread.h>
 4
 5#include "freetype/ftglyph.h"
 6
 7#include "internal.h"
 8
 9extern char _binary_Roboto_Regular_ttf_start[];
10extern char _binary_Roboto_Regular_ttf_end[];
11
12static FT_Library freetype = NULL;
13static FT_Face roboto = NULL;
14Atlas atlas;
15pthread_mutex_t freetype_mutex = PTHREAD_MUTEX_INITIALIZER;
16
17void initialize_freetype()
18{
19    // already initialized
20    if (freetype != NULL) return;
21
22    pthread_mutex_lock(&freetype_mutex);
23    if (FT_Init_FreeType(&freetype))
24    {
25        printf("fatal error: initializeing FreeType failed");
26        pthread_mutex_unlock(&freetype_mutex);
27        exit(1);
28    }
29
30    FT_Error error = FT_New_Memory_Face(
31        freetype,
32        _binary_Roboto_Regular_ttf_start,
33        _binary_Roboto_Regular_ttf_end - _binary_Roboto_Regular_ttf_start,
34        0, // face index
35        &roboto
36    );
37    if (error)
38    {
39        printf("error: cound not load built in Roboto font");
40    }
41    error = FT_Set_Pixel_Sizes(roboto, 0 /* width, same as height */, 16);
42    if (error)
43    {
44        printf("error: cound not set Roboto face size");
45    }
46
47    atlas = atlas_new(1024);
48
49    pthread_mutex_unlock(&freetype_mutex);
50}
51
52void draw_text(AlbaWindow* window, const float x, const float y, uint64_t length, const char* text)
53{
54    initialize_freetype();
55
56    if (length == 0)
57    {
58        length = strlen(text);
59    }
60
61    pthread_mutex_lock(&freetype_mutex);
62    for (uint64_t i = 0; i < length; i++)
63    {
64        const FT_Long glyph_index = FT_Get_Char_Index(roboto, text[i]); // TODO: unicode
65        atlas_append(&atlas, roboto, glyph_index);
66    }
67    pthread_mutex_unlock(&freetype_mutex);
68
69
70    FT_Error error = FT_Load_Char(roboto, '7', FT_LOAD_RENDER);
71    printf("%d\n", roboto->glyph->bitmap.width);
72    error = FT_Load_Char(roboto, 'l', FT_LOAD_RENDER);
73    printf("%d\n", roboto->glyph->bitmap.width);
74    error = FT_Load_Char(roboto, 'm', FT_LOAD_RENDER);
75    printf("%d\n", roboto->glyph->bitmap.width);
76
77    WGPUTextureDescriptor texture_options = {0};
78    texture_options.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst;
79    texture_options.format = WGPUTextureFormat_BGRA8UnormSrgb;
80    texture_options.dimension = WGPUTextureDimension_2D;
81    texture_options.size.width = window->width;
82    texture_options.size.height = window->height;
83    texture_options.size.depthOrArrayLayers = 1;
84    texture_options.sampleCount = 1;
85    texture_options.mipLevelCount = 1;
86    const WGPUTexture render_target = wgpuDeviceCreateTexture(window->device, &texture_options);
87}