#include #include #include #include #include "moonbit.h" #define STB_TRUETYPE_IMPLEMENTATION #define STBTT_STATIC #include "stb_truetype.h" #define MAX_SLOTS 4 static stbtt_fontinfo fonts[MAX_SLOTS]; static unsigned char *font_data[MAX_SLOTS]; /* Load a TTF file into `slot`. Returns 0 on success. */ MOONBIT_FFI_EXPORT int32_t mp_font_load(int32_t slot, moonbit_bytes_t path_bytes) { char path[512]; int32_t len = Moonbit_array_length(path_bytes); size_t n = (size_t)len < sizeof(path) - 1 ? (size_t)len : sizeof(path) - 1; memcpy(path, path_bytes, n); path[n] = '\0'; if (slot < 0 || slot >= MAX_SLOTS) return -1; FILE *f = fopen(path, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET); if (sz <= 0) { fclose(f); return -1; } unsigned char *buf = (unsigned char *)malloc((size_t)sz); if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(buf); return -1; } fclose(f); if (!stbtt_InitFont(&fonts[slot], buf, stbtt_GetFontOffsetForIndex(buf, 0))) { free(buf); return -1; } free(font_data[slot]); font_data[slot] = buf; return 0; } /* info = [w, h, xoff, yoff (top-left of bitmap relative to pen/baseline), advance] in pixels. */ MOONBIT_FFI_EXPORT void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info) { stbtt_fontinfo *fi = &fonts[slot]; float scale = stbtt_ScaleForMappingEmToPixels(fi, (float)size); int adv, lsb, x0, y0, x1, y1; int g = stbtt_FindGlyphIndex(fi, cp); stbtt_GetGlyphHMetrics(fi, g, &adv, &lsb); stbtt_GetGlyphBitmapBox(fi, g, scale, scale, &x0, &y0, &x1, &y1); info[0] = x1 - x0; info[1] = y1 - y0; info[2] = x0; info[3] = y0; info[4] = (int32_t)(adv * scale + 0.5f); } /* Render the 8-bit coverage bitmap (w*h bytes, w/h from mp_font_metrics) into buf. */ MOONBIT_FFI_EXPORT void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf) { stbtt_fontinfo *fi = &fonts[slot]; float scale = stbtt_ScaleForMappingEmToPixels(fi, (float)size); if (w <= 0 || h <= 0 || Moonbit_array_length(buf) < w * h) return; stbtt_MakeGlyphBitmap(fi, (unsigned char *)buf, w, h, w, scale, scale, stbtt_FindGlyphIndex(fi, cp)); } /* 1 when `slot` has a glyph for code point `cp` (not .notdef), 0 otherwise. */ MOONBIT_FFI_EXPORT int32_t mp_font_has_glyph(int32_t slot, int32_t cp) { if (slot < 0 || slot >= MAX_SLOTS || !font_data[slot]) return 0; return stbtt_FindGlyphIndex(&fonts[slot], cp) != 0 ? 1 : 0; }