//- font files // NOTE: first one that exists wins. noto is on basically every linux desktop. global_variable const char *font_paths_regular[] = { "/usr/share/fonts/noto/NotoSans-Regular.ttf", "/usr/share/fonts/noto/NotoSans-Regular.otf", "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf", "/usr/share/fonts/TTF/DejaVuSans.ttf", "/usr/share/fonts/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", }; global_variable const char *font_paths_semibold[] = { "/usr/share/fonts/noto/NotoSans-SemiBold.ttf", "/usr/share/fonts/noto/NotoSans-Medium.ttf", "/usr/share/fonts/truetype/noto/NotoSans-SemiBold.ttf", "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", "/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", }; global_variable const char *font_paths_mono[] = { "/usr/share/fonts/jetbrains-mono/JetBrainsMono-Regular.ttf", "/usr/share/fonts/noto/NotoSansMono-Regular.ttf", "/usr/share/fonts/truetype/noto/NotoSansMono-Regular.ttf", "/usr/share/fonts/TTF/DejaVuSansMono.ttf", "/usr/share/fonts/dejavu/DejaVuSansMono.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", }; internal String8 font_load_first(Arena *arena, const char **paths, u32 count) { for(u32 index = 0; index < count; ++index) { String8 path = str8(paths[index]); if(FileExists(arena, path)) { String8 data = FileLoad(arena, path); if(data.size > 0) { return data; } } } return str8_zero(); } //- hashing // NOTE: fnv-1a, 64 bit. text is short (names), good enough and branch free // NOTE: 8 bytes per step (fnv-1a was one byte per multiply, a 4 cycle dependency per byte) internal u64 hash_bytes(const u8 *data, u64 size, u64 seed) { u64 hash = (0x9E3779B97F4A7C15ull ^ seed) + size; u64 index = 0; for(; index + 8 <= size; index += 8) { u64 word = 0; MemCpy(&word, data + index, 8); hash = (hash ^ word) * 0xFF51AFD7ED558CCDull; hash ^= hash >> 32; } if(index < size) { u64 word = 0; MemCpy(&word, data + index, size - index); hash = (hash ^ word) * 0xC4CEB9FE1A85EC53ull; } hash ^= hash >> 29; hash *= 0xBF58476D1CE4E5B9ull; hash ^= hash >> 32; return hash ? hash : 1; } //- init internal void font_reset_caches(FontSystem *fonts) { MemSetZero(fonts->atlas, FONT_ATLAS_SIZE * FONT_ATLAS_SIZE); MemSetZero(fonts->glyphs, sizeof(GlyphEntry) * FONT_GLYPH_SLOTS); fonts->glyph_count = 0; fonts->shelf_x = 1; fonts->shelf_y = 1; fonts->shelf_h = 0; fonts->dirty_y0 = 0; fonts->dirty_y1 = FONT_ATLAS_SIZE; ++fonts->atlas_generation; // every run's cached placement is stale now } internal void font_reset_runs(FontSystem *fonts) { MemSetZero(fonts->runs, sizeof(ShapedRun) * FONT_RUN_SLOTS); fonts->run_count = 0; arena_clear(fonts->run_arena); ++fonts->runs_generation; // every recent entry points at a cleared run now } internal b32 font_init(Arena *arena, FontSystem *fonts) { MemSetZero(fonts, sizeof(*fonts)); if(FT_Init_FreeType(&fonts->library) != 0) { Log("freetype init failed"); return false; } fonts->font_data[FONT_REGULAR] = font_load_first(arena, font_paths_regular, ArrayCount(font_paths_regular)); fonts->font_data[FONT_SEMIBOLD] = font_load_first(arena, font_paths_semibold, ArrayCount(font_paths_semibold)); fonts->font_data[FONT_MONO] = font_load_first(arena, font_paths_mono, ArrayCount(font_paths_mono)); if(fonts->font_data[FONT_REGULAR].size == 0) { Log("no usable font found (install noto-fonts or dejavu)"); return false; } for(u32 kind = 0; kind < FONT_KIND_COUNT; ++kind) { if(fonts->font_data[kind].size == 0) { fonts->font_data[kind] = fonts->font_data[FONT_REGULAR]; } } for(u32 kind = 0; kind < FONT_KIND_COUNT; ++kind) fonts->face_index[kind] = -1; fonts->buffer = hb_buffer_create(); fonts->atlas = PushArrayAligned(arena, u8, FONT_ATLAS_SIZE * FONT_ATLAS_SIZE); fonts->glyphs = PushArrayAligned(arena, GlyphEntry, FONT_GLYPH_SLOTS); fonts->runs = PushArrayAligned(arena, ShapedRun, FONT_RUN_SLOTS); fonts->run_arena = ArenaCreate(MiB(8)); fonts->recent = PushArrayAligned(arena, RecentRun, FONT_RECENT_SLOTS); fonts->scale = 1.0f; fonts->runs_generation = 1; // zeroed entries (generation 0) never match fonts->atlas_generation = 1; for(u32 kind = 0; kind < FONT_KIND_COUNT; ++kind) fonts->last_face[kind] = FONT_NO_FACE; font_reset_caches(fonts); return true; } internal void font_drop_faces(FontSystem *fonts) { for(u32 index = 0; index < fonts->face_count; ++index) { hb_font_destroy(fonts->faces[index].hb); FT_Done_Face(fonts->faces[index].face); } fonts->face_count = 0; for(u32 kind = 0; kind < FONT_KIND_COUNT; ++kind) fonts->last_face[kind] = FONT_NO_FACE; font_reset_caches(fonts); font_reset_runs(fonts); } internal void font_set_scale(FontSystem *fonts, f32 scale) { if(scale == fonts->scale) { return; } // NOTE: every physical size changes, drop all faces and caches fonts->scale = scale; font_drop_faces(fonts); } // NOTE: swap the font file behind a kind. a no-op unless it actually changed, so the ui can call // it every frame with whatever the settings say. internal void font_set_data(FontSystem *fonts, FontKind kind, String8 data) { if(data.size == 0 || data.data == fonts->font_data[kind].data) { return; } fonts->font_data[kind] = data; fonts->face_index[kind] = -1; font_drop_faces(fonts); } // NOTE: a .ttc collection holds many faces (iosevka: 100+, the first one is "Thin"). pick the // one whose style is plain "Regular", once per file, not once per size. internal s32 font_pick_face(FontSystem *fonts, String8 data) { FT_Face face = NULL; if(FT_New_Memory_Face(fonts->library, data.data, (FT_Long)data.size, -1, &face) != 0) { return 0; } FT_Long count = face->num_faces; FT_Done_Face(face); for(FT_Long index = 0; index < count; ++index) { if(FT_New_Memory_Face(fonts->library, data.data, (FT_Long)data.size, index, &face) != 0) continue; b32 regular = face->style_name && strcmp(face->style_name, "Regular") == 0; FT_Done_Face(face); if(regular) return (s32)index; } return 0; } internal u32 font_face_lookup(FontSystem *fonts, FontKind kind, f32 size); internal u32 font_face(FontSystem *fonts, FontKind kind, f32 size) { if(fonts->last_face[kind] != FONT_NO_FACE && fonts->last_size[kind] == size) { return fonts->last_face[kind]; } u32 face = font_face_lookup(fonts, kind, size); fonts->last_size[kind] = size; fonts->last_face[kind] = face; return face; } internal u32 font_face_lookup(FontSystem *fonts, FontKind kind, f32 size) { u32 px = (u32)(size * fonts->scale + 0.5f); for(u32 index = 0; index < fonts->face_count; ++index) { if(fonts->faces[index].kind == kind && fonts->faces[index].px == px) { return index; } } if(fonts->face_count >= FONT_MAX_FACES) { // NOTE: font sizes are user settings now, so faces can pile up while someone drags a size // around. start over: drop every face and both caches, they refill on demand. font_drop_faces(fonts); } FontFace *face = &fonts->faces[fonts->face_count]; String8 data = fonts->font_data[kind]; if(fonts->face_index[kind] < 0) { fonts->face_index[kind] = font_pick_face(fonts, data); } if(FT_New_Memory_Face(fonts->library, data.data, (FT_Long)data.size, fonts->face_index[kind], &face->face) != 0) { return 0; } FT_Set_Pixel_Sizes(face->face, 0, px); face->hb = hb_ft_font_create_referenced(face->face); hb_ft_font_set_load_flags(face->hb, FT_LOAD_DEFAULT | FT_LOAD_TARGET_LIGHT); face->kind = kind; face->px = px; face->ascent = (f32)face->face->size->metrics.ascender / 64.0f; face->descent = (f32)-face->face->size->metrics.descender / 64.0f; face->line_height = (f32)face->face->size->metrics.height / 64.0f; return fonts->face_count++; } //- glyph atlas internal GlyphEntry *font_glyph(FontSystem *fonts, u32 face_index, u32 glyph) { u32 key = ((face_index << 20) | (glyph & 0xFFFFF)) + 1; u32 slot = (key * 2654435761u) & (FONT_GLYPH_SLOTS - 1); for(;;) { GlyphEntry *entry = &fonts->glyphs[slot]; if(entry->key == key) { return entry; } if(entry->key == 0) { break; } slot = (slot + 1) & (FONT_GLYPH_SLOTS - 1); } if(fonts->glyph_count >= FONT_GLYPH_SLOTS * 3 / 4) { font_reset_caches(fonts); return font_glyph(fonts, face_index, glyph); } //- rasterize FontFace *face = &fonts->faces[face_index]; if(FT_Load_Glyph(face->face, glyph, FT_LOAD_DEFAULT | FT_LOAD_TARGET_LIGHT) != 0 || FT_Render_Glyph(face->face->glyph, FT_RENDER_MODE_LIGHT) != 0) { return NULL; } FT_GlyphSlot slot_data = face->face->glyph; FT_Bitmap *bitmap = &slot_data->bitmap; u32 w = Min(bitmap->width, 255u); u32 h = Min(bitmap->rows, 255u); //- pack, 1px gutter so bilinear never bleeds a neighbour in if(fonts->shelf_x + w + 1 > FONT_ATLAS_SIZE) { fonts->shelf_x = 1; fonts->shelf_y += fonts->shelf_h + 1; fonts->shelf_h = 0; } if(fonts->shelf_y + h + 1 > FONT_ATLAS_SIZE) { font_reset_caches(fonts); return font_glyph(fonts, face_index, glyph); } u32 x = fonts->shelf_x; u32 y = fonts->shelf_y; for(u32 row = 0; row < h; ++row) { MemCpy(fonts->atlas + (u64)(y + row) * FONT_ATLAS_SIZE + x, bitmap->buffer + (s64)row * bitmap->pitch, w); } fonts->shelf_x += w + 1; fonts->shelf_h = Max(fonts->shelf_h, h); if(fonts->dirty_y0 >= fonts->dirty_y1) { fonts->dirty_y0 = (s32)y; fonts->dirty_y1 = (s32)(y + h); } else { fonts->dirty_y0 = Min(fonts->dirty_y0, (s32)y); fonts->dirty_y1 = Max(fonts->dirty_y1, (s32)(y + h)); } GlyphEntry *entry = &fonts->glyphs[slot]; entry->key = key; entry->x = (u16)x; entry->y = (u16)y; entry->w = (u8)w; entry->h = (u8)h; entry->bearing_x = (s16)slot_data->bitmap_left; entry->bearing_y = (s16)slot_data->bitmap_top; ++fonts->glyph_count; return entry; } //- shaping internal ShapedRun *font_shape_slow(FontSystem *fonts, u32 face_index, String8 text); internal ShapedRun *font_shape(FontSystem *fonts, u32 face_index, String8 text) { u64 key = ((u64)(uintptr_t)text.data >> 3) ^ ((u64)text.size << 40) ^ ((u64)face_index << 56); RecentRun *recent = &fonts->recent[(u32)((key * 0x9E3779B97F4A7C15ull) >> 54) & (FONT_RECENT_SLOTS - 1)]; if(recent->generation == fonts->runs_generation && recent->text == text.data && recent->size == text.size && recent->face == face_index && memcmp(recent->run->text, text.data, text.size) == 0) { return recent->run; } ShapedRun *run = font_shape_slow(fonts, face_index, text); // NOTE: shaping can clear the run table (bumping the generation), so record after recent->text = text.data; recent->size = (u32)text.size; recent->face = face_index; recent->run = run; recent->generation = fonts->runs_generation; return run; } internal ShapedRun *font_shape_slow(FontSystem *fonts, u32 face_index, String8 text) { u64 hash = hash_bytes(text.data, text.size, face_index * 0x9E3779B97F4A7C15ull); u32 slot = (u32)hash & (FONT_RUN_SLOTS - 1); for(;;) { ShapedRun *run = &fonts->runs[slot]; if(run->hash == hash && run->face == face_index && run->text_size == text.size && memcmp(run->text, text.data, text.size) == 0) { return run; } if(run->hash == 0) { break; } slot = (slot + 1) & (FONT_RUN_SLOTS - 1); } if(fonts->run_count >= FONT_RUN_SLOTS / 2 || arena_position(fonts->run_arena) > MiB(6)) { font_reset_runs(fonts); return font_shape_slow(fonts, face_index, text); } FontFace *face = &fonts->faces[face_index]; hb_buffer_clear_contents(fonts->buffer); hb_buffer_add_utf8(fonts->buffer, (const char *)text.data, (int)text.size, 0, (int)text.size); hb_buffer_guess_segment_properties(fonts->buffer); hb_shape(face->hb, fonts->buffer, NULL, 0); u32 count = 0; hb_glyph_info_t *infos = hb_buffer_get_glyph_infos(fonts->buffer, &count); hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(fonts->buffer, &count); ShapedRun *run = &fonts->runs[slot]; run->hash = hash; run->face = face_index; run->glyph_count = count; run->text_size = (u32)text.size; run->text = PushArray(fonts->run_arena, u8, Max(text.size, 1ull)); MemCpy(run->text, text.data, text.size); run->glyphs = PushArray(fonts->run_arena, ShapedGlyph, Max(count, 1u)); run->placed = PushArray(fonts->run_arena, RunGlyph, Max(count, 1u)); run->atlas_generation = 0; // placed on first draw f32 pen = 0.0f; for(u32 index = 0; index < count; ++index) { ShapedGlyph *out = &run->glyphs[index]; out->glyph = infos[index].codepoint; out->face = face_index; out->x = pen + (f32)positions[index].x_offset / 64.0f; out->y = -(f32)positions[index].y_offset / 64.0f; pen += (f32)positions[index].x_advance / 64.0f; } run->width = pen; ++fonts->run_count; return run; } //- public internal f32 font_measure(FontSystem *fonts, FontKind kind, f32 size, String8 text) { u32 face = font_face(fonts, kind, size); ShapedRun *run = font_shape(fonts, face, text); return run->width / fonts->scale; } internal f32 font_line_height(FontSystem *fonts, FontKind kind, f32 size) { return fonts->faces[font_face(fonts, kind, size)].line_height / fonts->scale; } internal f32 font_ascent(FontSystem *fonts, FontKind kind, f32 size) { return fonts->faces[font_face(fonts, kind, size)].ascent / fonts->scale; } internal void draw_run(DrawList *list, FontSystem *fonts, u32 face, ShapedRun *run, u32 glyph_count, f32 x, f32 baseline, u32 color) { // NOTE: snap the origin to the physical grid, glyph bitmaps are rendered for whole pixels f32 ox = floorf(x * fonts->scale + 0.5f); f32 oy = floorf(baseline * fonts->scale + 0.5f); // NOTE: place the whole run once per atlas generation. rasterizing can fill the atlas and // reset it halfway through, then the earlier placements are stale: go again (rare, bounded: // one run always fits an empty atlas). for(u32 attempt = 0; run->atlas_generation != fonts->atlas_generation && attempt < 3; ++attempt) { u32 generation = fonts->atlas_generation; for(u32 index = 0; index < run->glyph_count; ++index) { GlyphEntry *glyph = font_glyph(fonts, run->glyphs[index].face, run->glyphs[index].glyph); RunGlyph *place = &run->placed[index]; if(glyph) { *place = RunGlyph{glyph->x, glyph->y, glyph->w, glyph->h, glyph->bearing_x, glyph->bearing_y}; } else { *place = RunGlyph{}; } } if(fonts->atlas_generation == generation) run->atlas_generation = generation; } for(u32 index = 0; index < glyph_count; ++index) { ShapedGlyph *shaped = &run->glyphs[index]; RunGlyph *glyph = &run->placed[index]; if(glyph->w == 0 || glyph->h == 0) { continue; } f32 x0 = floorf(ox + shaped->x + 0.5f) + glyph->bearing_x; f32 y0 = floorf(oy + shaped->y + 0.5f) - glyph->bearing_y; draw_glyph_physical(list, x0, y0, x0 + glyph->w, y0 + glyph->h, glyph->x, glyph->y, color); } } internal f32 draw_text(DrawList *list, FontSystem *fonts, FontKind kind, f32 size, f32 x, f32 baseline, String8 text, u32 color) { if(text.size == 0) { return 0.0f; } u32 face = font_face(fonts, kind, size); ShapedRun *run = font_shape(fonts, face, text); draw_run(list, fonts, face, run, run->glyph_count, x, baseline, color); return run->width / fonts->scale; } internal f32 draw_text_fit(DrawList *list, FontSystem *fonts, FontKind kind, f32 size, f32 x, f32 baseline, f32 max_width, String8 text, u32 color) { if(text.size == 0) { return 0.0f; } u32 face = font_face(fonts, kind, size); ShapedRun *run = font_shape(fonts, face, text); f32 limit = max_width * fonts->scale; if(run->width <= limit) { draw_run(list, fonts, face, run, run->glyph_count, x, baseline, color); return run->width / fonts->scale; } ShapedRun *dots = font_shape(fonts, face, str8("…")); f32 available = limit - dots->width; u32 keep = 0; while(keep < run->glyph_count && run->glyphs[keep].x < available) { ++keep; } keep = (keep > 0) ? keep - 1 : 0; draw_run(list, fonts, face, run, keep, x, baseline, color); f32 cut = (keep < run->glyph_count) ? run->glyphs[keep].x : run->width; draw_run(list, fonts, face, dots, dots->glyph_count, x + cut / fonts->scale, baseline, color); return (cut + dots->width) / fonts->scale; }