Skip to content

Instantly share code, notes, and snippets.

@framkant
Created November 1, 2024 12:33
Show Gist options
  • Save framkant/4cdbe75a3a00269fee1c7df56b853e6d to your computer and use it in GitHub Desktop.
Save framkant/4cdbe75a3a00269fee1c7df56b853e6d to your computer and use it in GitHub Desktop.
Use custom fonts ini nuklear when used via sokol
// General nuklear info
// check https://github.com/Immediate-Mode-UI/Nuklear/blob/master/nuklear.h
// row 3950 and therabouts
// 1. Setup/init
snk_setup(&(snk_desc_t){
.dpi_scale = sapp_dpi_scale(),
.logger.func = slog_func,
});
// Initialize the font atlas
struct nk_font_atlas atlas;
nk_font_atlas_init_default(&atlas);
nk_font_atlas_begin(&atlas);
float scale = sapp_dpi_scale(); // For DPI scaling, needed for proper hidpi
struct nk_font* font_regular = nk_font_atlas_add_from_file(&atlas, "data/fonts/DroidSans.ttf", 8 * scale, 0);
if (!font_regular) {
fprintf(stderr, "Failed to load font from file.\n");
exit(EXIT_FAILURE);
}
struct nk_font* font_mono = nk_font_atlas_add_from_file(&atlas, "data/fonts/SourceCodePro-Regular.ttf", 8 * scale, 0);
if (!font_mono) {
fprintf(stderr, "Failed to load font from file.\n");
exit(EXIT_FAILURE);
}
// Bake to texture
int font_width, font_height;
const void* font_image = nk_font_atlas_bake(&atlas, &font_width, &font_height, NK_FONT_ATLAS_RGBA32);
if (!font_image) {
fprintf(stderr, "Failed to bake font atlas.\n");
exit(EXIT_FAILURE);
}
// Create the font texture
sg_image font_sg_image = sg_make_image(&(sg_image_desc){
.width = font_width,
.height = font_height,
.pixel_format = SG_PIXELFORMAT_RGBA8,
.data.subimage[0][0] = {
.ptr = font_image,
.size = (size_t)(font_width * font_height) * sizeof(uint32_t)
},
.label = "custom-font-image"
});
// Create a sampler
sg_sampler font_sg_smp = sg_make_sampler(&(sg_sampler_desc){
.min_filter = SG_FILTER_LINEAR,
.mag_filter = SG_FILTER_LINEAR,
.wrap_u = SG_WRAP_CLAMP_TO_EDGE,
.wrap_v = SG_WRAP_CLAMP_TO_EDGE,
.label = "custom-font-sampler",
});
// Keep in mem
app_state.font_regular = font_regular;
app_state.font_mono = font_mono;
// Check if the texture atlas sampler was created successfully
if (font_sg_smp.id == SG_INVALID_ID) {
fprintf(stderr, "Failed to create font sampler.\n");
exit(EXIT_FAILURE);
}
// Check if the texture atlas image was created successfully
if (font_sg_image.id == SG_INVALID_ID) {
fprintf(stderr, "Failed to create font texture.\n");
exit(EXIT_FAILURE);
}
// Make a image + sample pair to use as font object and keep
app_state.font_tex = snk_make_image(&(snk_image_desc_t){
.image = font_sg_image,
.sampler = font_sg_smp,
});
// End atlas creation and free data, we have a texture now that we use instead
nk_font_atlas_end(&atlas, snk_nkhandle(app_state.font_tex), NULL);
// Clean up the font atlas since we will not add more fonts
nk_font_atlas_cleanup(&atlas);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment