Skip to content

Instantly share code, notes, and snippets.

@JettMonstersGoBoom
Last active May 1, 2019 01:55
Show Gist options
  • Save JettMonstersGoBoom/0232c0e70e9b39f3369c934bff290d84 to your computer and use it in GitHub Desktop.
Save JettMonstersGoBoom/0232c0e70e9b39f3369c934bff290d84 to your computer and use it in GitHub Desktop.
// found pngs here https://opengameart.org/content/the-collection-of-8-bit-fonts-for-grafx2-r2
TigrFont *tigrGrafx2Font(const char *filename)
{
TigrFont *font = (TigrFont *)calloc(1, sizeof(TigrFont));
Tigr *fbit = tigrLoadImage(filename);
font->bitmap = fbit;
font->numGlyphs = 128-32;
font->glyphs = (TigrGlyph *)calloc(font->numGlyphs, sizeof(TigrGlyph));
// top line of font is markers
TPixel mark_color = tigrGet(fbit,0,0);
// scan bitmap
int chr = 0;
int chrx = 1;
for (int x=0;x<fbit->w;x++)
{
TPixel marker = tigrGet(fbit,x,0);
// check this pixel for the marker color
if ((marker.r == mark_color.r) && (marker.g == mark_color.g) && (marker.b == mark_color.b))
{
TigrGlyph *g;
// if we found a marker , this is the end of the current chr
// chrx is the left edge. x is the right edge
g = &font->glyphs[chr];
g->x = chrx;
g->y = 1;
g->h = fbit->h-1;
g->w = x-chrx;
g->code = chr+32; // ASCII
chrx=x+1;
chr++;
}
}
// often there's only upper case
// so duplicate the A-Z to a-z
if (chr==64)
{
for (int c=64;c<96;c++)
{
TigrGlyph *g,*s;
g = &font->glyphs[c];
s = &font->glyphs[c-32];
g->x = s->x;
g->y = s->y;
g->h = s->h;
g->w = s->w;
g->code = c+32; // ASCII
}
}
return font;
}
//////// changes to tigr.c
void tigrPrint(Tigr *dest, TigrFont *font, int x, int y, TPixel color, const char *text, ...)
{
char tmp[1024];
TigrGlyph *g;
va_list args;
const char *p;
int start = x, c;
tigrSetupFont(font);
// Expand the formatting string.
va_start(args, text);
vsnprintf(tmp, sizeof(tmp), text, args);
tmp[sizeof(tmp)-1] = 0;
va_end(args);
// Print each glyph.
p = tmp;
while (*p)
{
p = tigrDecodeUTF8(p, &c);
if (c == '\r')
continue;
if (c == '\n') {
x = start;
y += tigrTextHeight(font, "");
continue;
}
// NEW
if (c == ' ') {
x += get(font, '!')->w;
continue;
}
g = get(font, c);
tigrBlitTint(dest, font->bitmap, x, y, g->x, g->y, g->w, g->h, color);
x += g->w;
}
}
int tigrTextWidth(TigrFont *font, const char *text)
{
int x = 0, w = 0, c;
tigrSetupFont(font);
while (*text)
{
text = tigrDecodeUTF8(text, &c);
if (c == '\n' || c == '\r') {
x = 0;
} else if (c == ' ') { // NEW
x += get(font, '!')->w;
} else {
x += get(font, c)->w;
w = (x > w) ? x : w;
}
}
return w;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment