Skip to content

Bitmap Font Generator — TypeScript source

Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// bitmap-font — pure charset parser + BMFont TEXT emitter (FEAT-036). No
// canvas, no opentype: the font-geometry decisions stay unit-testable and the
// island owns all rasterizing (mirrors the sprite-packer carve-out). This file
// is statically imported by the island; opentype.js itself is loaded ONLY via
// the island's dynamic import so the eager ToolRouter chunk stays font-free.

/** Error shape mirrors PdfToolError (src/lib/pdf-errors.ts). */
export type FontErrorCode = 'invalid';

export class FontError extends Error {
  code: FontErrorCode;
  constructor(code: FontErrorCode, message: string) {
    super(message);
    this.code = code;
  }
}

/** Max valid Unicode scalar value. */
const MAX_CODEPOINT = 0x10ffff;

const ASCII = 'ascii';
const LATIN1 = 'latin1';
const DIGITS = 'digits';

/** Inclusive [lo, hi] codepoint range expanded to a sorted list. */
function range(lo: number, hi: number): number[] {
  const out: number[] = [];
  for (let cp = lo; cp <= hi; cp++) out.push(cp);
  return out;
}

/** Named charsets, as documented in the tool docs. */
const PRESETS: Record<string, number[]> = {
  [ASCII]: range(32, 126),
  [LATIN1]: [...range(32, 126), ...range(160, 255)],
  [DIGITS]: range(48, 57),
};

/**
 * Parse a charset spec into a deduped, sorted codepoint list.
 *
 * Grammar (whitespace-tolerant, comma-separated items):
 *  - `ascii`  → U+0020–U+007E
 *  - `latin1` → U+0020–U+007E plus U+00A0–U+00FF
 *  - `digits` → U+0030–U+0039
 *  - item     → `A` | `A-B` where each side is decimal (`65`, `65-90`) or
 *               `U+HEX` (`U+41`, `U+4E00-9FFF`; the range end may drop the
 *               `U+` prefix when the start carries it).
 * Throws FontError('invalid') on empty specs, garbage tokens, inverted or
 * out-of-Unicode-range bounds (anything below 0 or above U+10FFFF).
 */
export function parseCharset(spec: string): number[] {
  const trimmed = spec.trim();
  if (trimmed === '') throw new FontError('invalid', 'Charset is empty — name a preset or list codepoint ranges.');
  const preset = PRESETS[trimmed.toLowerCase()];
  if (preset) return [...preset];

  const seen = new Set<number>();
  for (const raw of trimmed.split(',')) {
    const token = raw.trim().replace(/\s+/g, '');
    const bounds = parseToken(token);
    for (let cp = bounds.lo; cp <= bounds.hi; cp++) seen.add(cp);
  }
  return [...seen].sort((a, b) => a - b);
}

/** One comma item → inclusive bounds, or FontError when garbage. */
function parseToken(token: string): { lo: number; hi: number } {
  // Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
  const hex = /^u\+([0-9a-f]+)(?:-([0-9a-f]+))?$/i.exec(token);
  // Decimal form: N or N-N.
  const dec = /^(\d+)(?:-(\d+))?$/.exec(token);
  if (!hex && !dec) {
    throw new FontError('invalid', `"${token}" is not a codepoint or range — use 65-90 or U+4E00-9FFF.`);
  }
  const radix = hex ? 16 : 10;
  const [, loRaw, hiRaw] = (hex ?? dec)!;
  const lo = Number.parseInt(loRaw, radix);
  const hi = hiRaw !== undefined ? Number.parseInt(hiRaw, radix) : lo;
  if (lo > MAX_CODEPOINT || hi > MAX_CODEPOINT) {
    throw new FontError('invalid', `"${token}" is outside Unicode (max U+10FFFF).`);
  }
  if (lo > hi) throw new FontError('invalid', `"${token}" runs backwards — put the smaller codepoint first.`);
  return { lo, hi };
}

/** One char entry in the emitted .fnt (geometry already scaled to pixels). */
export interface FntChar {
  codepoint: number;
  x: number;
  y: number;
  w: number;
  h: number;
  xoffset: number;
  yoffset: number;
  xadvance: number;
}

/** One kerning pair in the emitted .fnt (pixel amount, may be negative). */
export interface FntKerning {
  first: number;
  second: number;
  amount: number;
}

/**
 * Emit a BMFont TEXT-format document (https://www.angelcode.com/products/bmfont/doc/font_file_format.html).
 * Pages are always 1 (`sheet.png`); fields not owned by the caller get the
 * spec defaults a rasterized (anti-aliased, Unicode) export would carry.
 * `padding` is broadcast to all four sides (`N,N,N,N`), `spacing` stays 1,1.
 */
export function fntText(
  info: { face: string; size: number; padding: number },
  common: { lineHeight: number; base: number; scaleW: number; scaleH: number },
  chars: FntChar[],
  kernings: FntKerning[],
): string {
  const p = info.padding;
  const lines = [
    `info face="${info.face}" size=${info.size} bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=${p},${p},${p},${p} spacing=1,1 outline=0`,
    `common lineHeight=${common.lineHeight} base=${common.base} scaleW=${common.scaleW} scaleH=${common.scaleH} pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0`,
    'page id=0 file="sheet.png"',
    `chars count=${chars.length}`,
    ...chars.map(
      (c) =>
        `char id=${c.codepoint} x=${c.x} y=${c.y} width=${c.w} height=${c.h} xoffset=${c.xoffset} yoffset=${c.yoffset} xadvance=${c.xadvance} page=0 chnl=15`,
    ),
    `kernings count=${kernings.length}`,
    ...kernings.map((k) => `kerning first=${k.first} second=${k.second} amount=${k.amount}`),
  ];
  return lines.join('\n');
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →