Generate atlas picture

Francesco Pasa 10 months ago

CMakeLists.txt   M +15 -1

69         GIT_SHALLOW TRUE
70 )
71 
72-FetchContent_MakeAvailable(glfw freetype harfbuzz hashmap check)
73+# PNG
74+# TODO: zlib
75+FetchContent_Declare(
76+        png
77+        GIT_REPOSITORY https://github.com/pnggroup/libpng.git
78+        GIT_TAG v1.6.43
79+        GIT_SHALLOW TRUE
80+)
81+
82+#FetchContent_Declare(
83+#        https://github.com/madler/zlib.git
84+#)
85+
86+FetchContent_MakeAvailable(glfw freetype harfbuzz hashmap check png)
87 #include_directories("${wayland_SOURCE_DIR}/src")
88 #include_directories("${x11_SOURCE_DIR}/include")
89 include_directories("${glfw_SOURCE_DIR}/include")
90 include_directories("${freetype_SOURCE_DIR}/include")
91 include_directories("${harfbuzz_SOURCE_DIR}/include")
92 include_directories("${hashmap_SOURCE_DIR}")
93+include_directories("${png_SOURCE_DIR}")
94 
95 include_directories("${check_SOURCE_DIR}/src")
96 include_directories("${check_BINARY_DIR}")

examples/text.c   M +2

 9     AlbaWindow* window = create_window(&options);
10 
11     draw_text(window, 0, 0, 0, "7 lm ß 🍔");
12+    draw_text(window, 100, 100, 0,
13+              "DESCRIPTION        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");
14 
15     while (!window_should_close(window))
16     {

include/alba.h   M +1 -1

21 void dynarray_extend(DynArray* array, uint64_t size, const void* data);
22 void dynarray_release(const DynArray* array);
23 void dynarray_clear(DynArray* array);
24-void dynarray_sort(const DynArray* array, uint32_t (*smaller_than_pivot)(void* pivot, void* elem));
25+void dynarray_sort(const DynArray* array, uint32_t (*is_before_pivot)(void* pivot, void* elem));
26 
27 // Misc
28 typedef struct

src/atlas.c   M +165 -9

 1 #include "internal.h"
 2 
 3+#include <png.h>
 4+
 5 typedef struct
 6 {
 7     uint32_t character;
 8     FT_Long glyph_index;
 9     FT_Bitmap bitmap;
10+    uint32_t x0, y0, x1, y1;
11 } Glyph;
12 
13 uint64_t hash_glyph(const void* item, const uint64_t seed0, const uint64_t seed1)
22     return a->character - b->character;
23 }
24 
25+void free_glyph(const void* vglyph)
26+{
27+    const Glyph* glyph = vglyph;
28+    free(glyph->bitmap.buffer);
29+}
30+
31 Atlas atlas_new(const uint32_t capacity)
32 {
33     Atlas atlas = {0};
34-    atlas.glyphs = hashmap_new(sizeof(Glyph), capacity, 0, 0, hash_glyph, compare_glyph, NULL, NULL);
35+    atlas.glyphs = hashmap_new(sizeof(Glyph), capacity, 0, 0, hash_glyph, compare_glyph, free_glyph, NULL);
36     if (capacity != 0)
37     {
38         atlas_reserve(&atlas, capacity);
48 {
49     const FT_Long glyph_index = FT_Load_Char(face, character, FT_LOAD_RENDER);
50 
51-    const Glyph glyph = {
52+    const FT_Bitmap* bitmap = &face->glyph->bitmap;
53+    Glyph glyph = {
54         .character = character,
55         .glyph_index = glyph_index,
56-        .bitmap = face->glyph->bitmap,
57+        .bitmap = *bitmap,
58     };
59+
60+    // Copy buffer
61+    glyph.bitmap.buffer = malloc(bitmap->rows * bitmap->pitch);
62+    memcpy(glyph.bitmap.buffer, bitmap->buffer, bitmap->rows * bitmap->pitch);
63+
64     const uint32_t hash = hash_glyph(&glyph, 0, 0); // Execute hash only once
65     if (hashmap_get_with_hash(atlas->glyphs, &glyph, hash) == NULL)
66     {
 67     }
 68 }
 69 
 70+uint32_t sort_by_height_desc(void* vpivot, void* velem)
 71+{
 72+    const Glyph** pivot = vpivot;
 73+    const Glyph** elem = velem;
 74+    return (*elem)->bitmap.rows > (*pivot)->bitmap.rows;
 75+}
 76+
 77+void copy_bitmap(const FT_Bitmap src, void* dst, const uint32_t x, const uint32_t y, const uint32_t dst_row_stride)
 78+{
 79+    for (uint32_t i = 0; i < src.rows; i++)
 80+    {
 81+        memcpy(dst + x + (y + i) * dst_row_stride, src.buffer + i * src.pitch, sizeof(uint8_t) * src.pitch);
 82+    }
 83+}
 84+
 85+void write_png(const char* output_file_path, const int width, const int height, const int depth, void* data)
 86+{
 87+    FILE* fp = fopen(output_file_path, "wb");
 88+    if (fp == NULL)
 89+    {
 90+        printf("error: opening file '%s'.", output_file_path);
 91+        exit(1);
 92+    }
 93+
 94+    png_structp write = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
 95+    if (write == NULL)
 96+    {
 97+        printf("error: creating png write struct.");
 98+        exit(1);
 99+    }
100+    png_infop info = png_create_info_struct(write);
101+    if (info == NULL)
102+    {
103+        png_destroy_write_struct(&write, (png_infopp)NULL);
104+        printf("error: creating png info struct.");
105+        exit(1);
106+    }
107+
108+    png_init_io(write, fp);
109+    png_set_IHDR(
110+        write, info, width, height, depth,
111+        depth == 8 ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_RGBA,
112+        PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT
113+    );
114+
115+    const png_bytepp row_pointers = (png_bytepp)png_malloc(write, sizeof(png_bytepp) * height);
116+    for (int i = 0; i < height; i++)
117+    {
118+        row_pointers[i] = (png_bytep)png_malloc(write, width);
119+    }
120+    for (int hi = 0; hi < height; hi++)
121+    {
122+        for (int wi = 0; wi < width; wi++)
123+        {
124+            row_pointers[hi][wi] = ((unsigned char*)data)[(wi + width * hi) * depth / 8];
125+        }
126+    }
127+
128+    png_write_info(write, info);
129+    png_write_image(write, row_pointers);
130+    png_write_end(write, info);
131+    png_destroy_write_struct(&write, &info);
132+
133+    fclose(fp);
134+}
135+
136 void atlas_generate_image(Atlas* atlas)
137 {
138     if (atlas->dirty == 0) return;
139 
140+    // Sort caracters by height
141     size_t iter = 0;
142     Glyph* glyph;
143-    DynArray glyphs = dynarray_new(sizeof(Glyph), hashmap_count(atlas->glyphs));
144+    DynArray glyphs = dynarray_new(sizeof(Glyph*), hashmap_count(atlas->glyphs));
145     while (hashmap_iter(atlas->glyphs, &iter, (void**)&glyph))
146     {
147-        dynarray_append(&glyphs, glyph);
148+        dynarray_append(&glyphs, &glyph);
149+    }
150+    dynarray_sort(&glyphs, sort_by_height_desc);
151+
152+    // Calculate minimum size that fits the characters
153+    uint32_t image_size = 256;
154+    for (; image_size <= 8192; image_size *= 2)
155+    {
156+        const uint32_t stride = image_size;
157+        uint32_t x = 0;
158+        uint32_t y = 0;
159+        uint32_t row_height = 0;
160+        for (uint32_t i = 0; i < glyphs.length; i++)
161+        {
162+            glyph = ((Glyph**)glyphs.data)[i];
163+
164+            // Go to new line
165+            if (x + glyph->bitmap.width > image_size)
166+            {
167+                x = 0;
168+                y += row_height;
169+            }
170+            // store max row_height
171+            if (x == 0)
172+            {
173+                row_height = glyph->bitmap.rows;
174+                if (y + row_height > image_size) break;
175+            }
176+
177+            x += glyph->bitmap.width;
178+        }
179+
180+        if (y + row_height < image_size)
181+        {
182+            break;
183+        }
184+    }
185+
186+    if (image_size > 8192)
187+    {
188+        printf(
189+            "error: font atlas too big (> 8192*8192 pixels). "
190+            "Consider reducing the number of fonts, text sizes "
191+            "(especially large sizes) or characters in use."
192+        );
193+        exit(1);
194+    }
195+
196+    atlas->width = image_size;
197+    atlas->height = image_size;
198+    atlas->image = reallocarray(atlas->image, atlas->width * atlas->height, sizeof(uint8_t));
199+    memset(atlas->image, 0, atlas->width * atlas->height * sizeof(uint8_t));
200+
201+    const uint32_t stride = image_size;
202+    uint32_t x = 0;
203+    uint32_t y = 0;
204+    uint32_t row_height = 0;
205+    for (uint32_t i = 0; i < glyphs.length; i++)
206+    {
207+        glyph = ((Glyph**)glyphs.data)[i];
208+
209+        if (x + glyph->bitmap.width > image_size)
210+        {
211+            x = 0;
212+            y += row_height;
213+        }
214+        if (x == 0)
215+        {
216+            row_height = glyph->bitmap.rows;
217+        }
218+
219+        copy_bitmap(glyph->bitmap, atlas->image, x, y, stride);
220+        glyph->x0 = x;
221+        glyph->y0 = y;
222+        glyph->x1 = x + glyph->bitmap.width;
223+        glyph->y1 = y + glyph->bitmap.rows;
224+
225+        x += glyph->bitmap.width;
226     }
227-    dynarray_sort(&glyphs, compare_glyph);
228 
229-    atlas->width = 1024;
230-    atlas->height = 1024;
231-    atlas->image = reallocarray(atlas->image, atlas->width * atlas->height * 4, sizeof(uint8_t));
232+    dynarray_release(&glyphs);
233 }
234 
235 void atlas_release(const Atlas* atlas)

src/dynarray.c   M +6 -6

58 
59 static void quicksort(
60     const uint64_t element_size, const uint64_t length, void* data,
61-    uint32_t (*smaller_than_pivot)(void* pivot, void* elem), void* temp
62+    uint32_t (*is_before_pivot)(void* pivot, void* elem), void* temp
63 )
64 {
65     if (length < 2) return;
68     for (uint64_t i = 0; i < length; i++)
69     {
70         void* current = data + i * element_size;
71-        if (smaller_than_pivot(pivot, current))
72+        if (is_before_pivot(pivot, current))
73         {
74             if (larger == NULL) continue;
75             swap(element_size, larger, current, temp);
 88 
 89     const uint64_t size_before = (pivot - data);
 90     const uint64_t num_elem_before = size_before / element_size;
 91-    quicksort(element_size, num_elem_before, data, smaller_than_pivot, temp);
 92-    quicksort(element_size, length - num_elem_before - 1, data + size_before + element_size, smaller_than_pivot, temp);
 93+    quicksort(element_size, num_elem_before, data, is_before_pivot, temp);
 94+    quicksort(element_size, length - num_elem_before - 1, data + size_before + element_size, is_before_pivot, temp);
 95 }
 96 
 97-void dynarray_sort(const DynArray* array, uint32_t (*smaller_than_pivot)(void* pivot, void* elem))
 98+void dynarray_sort(const DynArray* array, uint32_t (*is_before_pivot)(void* pivot, void* elem))
 99 {
100     void* temp = malloc(array->element_size);
101-    quicksort(array->element_size, array->length, array->data, smaller_than_pivot, temp);
102+    quicksort(array->element_size, array->length, array->data, is_before_pivot, temp);
103     free(temp);
104 }

src/text.c   M +1 -1

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+    error = FT_Set_Pixel_Sizes(roboto, 0 /* width, same as height */, 18);
43     if (error)
44     {
45         printf("error: cound not set Roboto face size");