Add fontIndex parameter to fontstash that controls which font in a TTC to load

This commit is contained in:
Karl Zylinski
2025-10-10 23:40:29 +02:00
parent 79912b3a98
commit a4350b41ae
3 changed files with 13 additions and 5 deletions

View File

@@ -323,11 +323,15 @@ __AtlasAddWhiteRect :: proc(ctx: ^FontContext, w, h: int) -> bool {
// push a font to the font stack
// optionally init with ascii characters at a wanted size
//
// 'fontIndex' controls which font you want to load within a multi-font format such
// as TTC. Leave it as zero if you are loading a single-font format such as TTF.
AddFontMem :: proc(
ctx: ^FontContext,
name: string,
data: []u8,
freeLoadedData: bool,
fontIndex: int = 0,
) -> int {
append(&ctx.fonts, Font{})
res := &ctx.fonts[len(ctx.fonts) - 1]
@@ -335,10 +339,10 @@ AddFontMem :: proc(
res.freeLoadedData = freeLoadedData
res.name = strings.clone(name)
// Get offset of first font (if the font is a TTC then it can contain multiple fonts)
// Note: There is currently no support for specifying any other font than first one.
font_offset := stbtt.GetFontOffsetForIndex(raw_data(res.loadedData), 0)
stbtt.InitFont(&res.info, raw_data(res.loadedData), font_offset)
num_fonts := stbtt.GetNumberOfFonts(raw_data(data))
font_index_clamped := num_fonts > 0 ? clamp(i32(fontIndex), 0, num_fonts-1) : 0
font_offset := stbtt.GetFontOffsetForIndex(raw_data(data), font_index_clamped)
stbtt.InitFont(&res.info, raw_data(data), font_offset)
ascent, descent, line_gap: i32
stbtt.GetFontVMetrics(&res.info, &ascent, &descent, &line_gap)

View File

@@ -4,10 +4,13 @@ package fontstash
import "core:log"
import "core:os"
// 'fontIndex' controls which font you want to load within a multi-font format such
// as TTC. Leave it as zero if you are loading a single-font format such as TTF.
AddFontPath :: proc(
ctx: ^FontContext,
name: string,
path: string,
fontIndex: int = 0,
) -> int {
data, ok := os.read_entire_file(path)
@@ -15,6 +18,6 @@ AddFontPath :: proc(
log.panicf("FONT: failed to read font at %s", path)
}
return AddFontMem(ctx, name, data, true)
return AddFontMem(ctx, name, data, true, fontIndex)
}

View File

@@ -5,6 +5,7 @@ AddFontPath :: proc(
ctx: ^FontContext,
name: string,
path: string,
fontIndex: int = 0,
) -> int {
panic("fontstash.AddFontPath is unsupported on the JS target")
}