aboutsummaryrefslogtreecommitdiff
path: root/font.c
diff options
context:
space:
mode:
authorRiley Beckett <rbeckettvt@gmail.com>2025-10-12 16:55:23 -0400
committerRiley Beckett <rbeckettvt@gmail.com>2025-10-12 16:55:23 -0400
commitd71f3c26c26c22ac6782944f5732274abe64f8f8 (patch)
tree3ff3c5e0a4df4b7f365004a0c4ecb25d65085eba /font.c
parent91759767b0c7793060f447fd545b639cf91b7ae3 (diff)
Create atlas for font rendering
Diffstat (limited to 'font.c')
-rw-r--r--font.c64
1 files changed, 64 insertions, 0 deletions
diff --git a/font.c b/font.c
index 9198b3a..2a082b3 100644
--- a/font.c
+++ b/font.c
@@ -59,6 +59,70 @@ bool init_freetype(client_state* state, const char* file) {
fprintf(stderr, "Failed to set font size\n");
return false;
}
+ return true;
+}
+
+bool init_atlas(client_state* state) {
+ FT_Int32 load_flags = FT_LOAD_RENDER | FT_LOAD_TARGET_(FT_RENDER_MODE_SDF);
+ for (int i = 32; i < 128; i++) {
+ if (FT_Load_Char(state->ft_face, i, load_flags)) {
+ fprintf(stderr, "Failed to render character %c\n", (char)i);
+ }
+ printf("%c: %u, %u\n", (char)i, state->ft_face->glyph->bitmap.width, state->ft_face->glyph->bitmap.rows);
+ state->atlas.width += state->ft_face->glyph->bitmap.width;
+ state->atlas.height = MAX(state->atlas.height, state->ft_face->glyph->bitmap.rows);
+ }
+
+ glActiveTexture(GL_TEXTURE0);
+ glGenTextures(1, &state->atlas.texture);
+ glBindTexture(GL_TEXTURE_2D, state->atlas.texture);
+
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+ glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ glTexImage2D(
+ GL_TEXTURE_2D,
+ 0,
+ GL_RED,
+ (GLsizei) state->atlas.width,
+ (GLsizei) state->atlas.height,
+ 0,
+ GL_RED,
+ GL_UNSIGNED_BYTE,
+ NULL);
+
+ uint32_t x = 0;
+ for (int i = 32; i < 128; i++) {
+ if (FT_Load_Char(state->ft_face, i, load_flags)) {
+ fprintf(stderr, "Failed to render character %c\n", (char)i);
+ }
+
+ if (FT_Render_Glyph(state->ft_face->glyph, FT_RENDER_MODE_NORMAL)) {
+ fprintf(stderr, "ERROR: could not render glyph of a character with code %d\n", i);
+ }
+
+ state->atlas.metrics[i].advance_x = (float)state->ft_face->glyph->advance.x / 64;
+ state->atlas.metrics[i].advance_y = (float)state->ft_face->glyph->advance.y / 64;
+ state->atlas.metrics[i].bitmap_width = state->ft_face->glyph->bitmap.width;
+ state->atlas.metrics[i].bitmap_height = state->ft_face->glyph->bitmap.rows;
+ state->atlas.metrics[i].texture_offset = x;
+
+ glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ glTexSubImage2D(
+ GL_TEXTURE_2D,
+ 0,
+ x,
+ 0,
+ state->ft_face->glyph->bitmap.width,
+ state->ft_face->glyph->bitmap.rows,
+ GL_RED,
+ GL_UNSIGNED_BYTE,
+ state->ft_face->glyph->bitmap.buffer);
+ x += state->ft_face->glyph->bitmap.width;
+ }
return true;
}