agentleFS
vchelaruvchelaru/Gum/.claude/skills/gum-tool-font-generation/SKILL.md

gum-tool-font-generation

Skill659 starsChanged 2 months agoMITView on GitHub

Gum bitmap font generation — tool converts font properties into .fnt/.png via bmfont.exe or KernSmith. Triggers: BmfcSave, HeadlessFontGenerationService, FontManager, FontFileGeneratorSelector, KernSmithFileGenerator, BmfcTemplate.bmfc, texture size estimation, dropshadow.

The file

We split this skill into the rules it gives an agent

6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Size estimation: Before generating, AssignEstimatedNeededSizeOn either runs a binary-search optimization (GetOptimizedSizeFor, controlled …

    line 41
  2. Very specific:

    File-watch suppression: Before writing, all expected output paths (.bmfc, .fnt, .png pages) are registered with …

    line 44
  3. Distinctive:

    When OutlineThickness is 0: alpha=0, RGB channels=4 (glyph in alpha channel).

    line 58
  4. Distinctive:

    When OutlineThickness > 0: alpha=1, RGB channels=0 (outline uses color channels).

    line 59
  5. Very specific:

    Default: 32-126,160-255 (ASCII + Latin-1 Supplement)

    line 69
  6. Very specific:

    All font generation now routes through HeadlessFontGenerationService.

    line 90

≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Font Generation Pipeline

Gum generates BMFont-format bitmap fonts (.fnt + .png atlas). Pipeline: collect font properties → build BmfcSave → pick a generator backend → produce .fnt + .png. Two interchangeable IFontFileGenerator backends exist, chosen per-project via GumProjectSave.FontGenerator (FontGeneratorType.BmFont, the default for back-compat, or .KernSmith):

  • BmFontExeFileGenerator shells out to the embedded bmfont.exe (Windows-only). Legacy path; does not support dropshadow at all — BmfcTemplate.bmfc has no dropshadow placeholders, so BmfcSave.HasDropshadow/Dropshadow* fields are silently ignored on this backend.
  • KernSmithFileGenerator calls the KernSmith library in-process (cross-platform, no external exe, supports dropshadow). This is the newer, recommended backend.

FontFileGeneratorSelector picks between them at generation time (project isn't loaded yet when DI wires services up, so selection can't happen at construction).

Architecture

FontManager (tool facade)
  └─ HeadlessFontGenerationService (core logic, headless)
       ├─ BmfcSave (data model + .bmfc serialization)
       │    └─ BmfcTemplate.bmfc (template file with placeholders, bmfont.exe only)
       └─ FontFileGeneratorSelector → BmFontExeFileGenerator | KernSmithFileGenerator

FontManager is the tool-facing entry point. It wires IFontGenerationCallbacks (UI output, spinner, file-watch suppression) and delegates all real work to HeadlessFontGenerationService via IHeadlessFontGenerationService.

HeadlessFontGenerationService is platform-checked for the bmfont.exe backend only (throws PlatformNotSupportedException off-Windows when FontGeneratorType.BmFont is selected). It owns:

  • Collecting all unique fonts a project needs (CollectRequiredFonts)
  • Deciding whether a font file already exists or needs (re)generation
  • Invoking the selected IFontFileGenerator — one call per font, all awaited via Task.WhenAll for parallelism
  • Texture size estimation (heuristic) and optimization (binary search over AvailableSizes)

Texture-size estimation is bmfont.exe-specific and does not run for KernSmith. EstimateBlocksNeeded's heuristic (and the dropshadow blindness that falls out of it) only matters for BmFontExeFileGenerator. IFontFileGenerator.RequiresSizeEstimation (false on KernSmithFileGenerator, true on BmFontExeFileGenerator) gates the whole AssignEstimatedNeededSizeOn call in HeadlessFontGenerationService — KernSmith instead sizes its own atlas via FontGeneratorOptions.AutofitTexture.

BmfcSave holds the six font properties (FontName, FontSize, OutlineThickness, UseSmoothing, IsItalic, IsBold) plus ranges, spacing, and output dimensions. Its Save() method loads BmfcTemplate.bmfc and does string replacement to produce the .bmfc file that bmfont.exe consumes. It also owns FontCacheFileName which determines the output path.

Generation Flow

  1. Property collection: FontReferenceCollector.BuildBmfcSave (GumCommon/Bundle/FontReferenceCollector.cs) reads font properties through a getValue callback and returns a BmfcSave or null. It is the single source of truth for building a BmfcSave from variables - don't add a second copy alongside it. For direct Text instances a plain state lookup is enough, but for component instances containing Text, CollectFontsFromNestedTextInstances recursively descends using RecursiveVariableFinder to resolve font properties through exposed variables, inheritance, and categorized states a container assigns through an exposed variable (e.g. StyleCategoryState). A conditional VariableReferences row on a component instance that drives a font variable inside the component has every branch collected (CollectFontsFromNestedTextInstancesAllBranches).
  2. Deduplication: CollectRequiredFonts iterates all elements/states/instances and deduplicates by FontCacheFileName (a deterministic name encoding all font parameters).
  3. Size estimation: Before generating, AssignEstimatedNeededSizeOn either runs a binary-search optimization (GetOptimizedSizeFor, controlled by AutoSizeFontOutputs project setting) or uses a heuristic lookup table (EstimateBlocksNeeded) based on effective font size.
  4. Template expansion: BmfcSave.Save() loads Content/BmfcTemplate.bmfc, replaces placeholders, and writes the .bmfc file alongside the target .fnt path.
  5. bmfont.exe invocation: CreateBitmapFontFilesIfNecessaryAsync launches bmfont.exe -c "<bmfc>" -o "<fnt>" via Process.Start with UseShellExecute = true. The process is awaited async (WaitForExitAsync) or synchronously depending on createTask.
  6. File-watch suppression: Before writing, all expected output paths (.bmfc, .fnt, .png pages) are registered with IFontGenerationCallbacks.OnIgnoreFileChange so the file watcher doesn't trigger reloads.

Font Cache Naming

BmfcSave.FontCacheFileName produces paths like FontCache/Font18Arial.fnt. The name encodes all parameters that affect output:

  • Base: Font{size}{name} (spaces in font name → underscores)
  • Suffixes: _o{N} (outline), _noSmooth, _Italic, _Bold

This means two elements with identical font settings share one cached file.

A font file adds _ttf, then, only when GumProjectSave.UsesPathHashedFontCacheNames (project Version 6 or later), an 8-digit FNV-1a hash of the path as the Text typed it (BmfcSave.GetPathHash, slashes normalized), so same-named files in different folders get separate atlases. Older projects keep the unhashed name because their shipped .fnt files use it, so the runtime never checks two names. Every place that builds a name or a BmfcSave must pass the project's flag (BmfcSave.IncludePathHashInCacheName; CustomSetPropertyOnRenderable.ApplyFontCacheNaming does it for the runtime paths). BmfcSave.FontFile is often already resolved to an absolute path by then, so the hash comes from FontFileAsReferenced, the typed path; hashing the absolute path makes the tool bake a name the runtime never looks up and makes the same project generate different names on each machine (HeadlessFontGenerationService resolves FontFile after collection and records the typed path first). The Forms theme templates ship pre-baked file fonts in FontCache, named with the hash.

Channel Behavior (Outline vs No-Outline)

When OutlineThickness is 0: alpha=0, RGB channels=4 (glyph in alpha channel). When OutlineThickness > 0: alpha=1, RGB channels=0 (outline uses color channels).

Texture Size Optimization

GetOptimizedSizeFor does a binary search over AvailableSizes (32x32 up to 8192x8192) to find the smallest texture that keeps the font on a single page. Each probe generates the font to a temp directory and parses the pages= line from the resulting .fnt file.

The heuristic fallback (EstimateBlocksNeeded) uses a lookup table mapping effective font size to a number of 256-pixel blocks, then factors the block count into width x height.

Character Ranges

  • Default: 32-126,160-255 (ASCII + Latin-1 Supplement)
  • Project ranges live in GumProjectSave.FontRangeEntries (one entry per font family; a null/empty family is the project-wide default). Look up with GumProjectSave.GetFontRanges(family) (family entry, else global entry, else null so the caller uses BmfcSave.GetEffectiveDefaultRanges()). The scalar FontRanges is a legacy shim over the global entry and is still written on every save for older tools; the list is only written once a family has its own entry. The Fonts page of the Settings window (see Key Files) edits every entry, with the default row first.
  • Ranges are validated (no spaces, proper start < end), with automatic fallback to default. The Fonts page of the Settings window flags an invalid range, a row with no font or a repeated font, and a font no Text uses, and bakes nothing while a range is invalid. A hand-edited project is reported by HeadlessErrorChecker (GUM0010 unmatched entry, GUM0011 invalid range); both read FontRangeEntryChecker for which entries match a used font
  • Space character (32) is always included via EnsureRangesContainSpace
  • Large range sets are split across multiple chars= lines (max 10 blocks per line) for bmfont.exe compatibility
  • GenerateRangesFromFile can derive ranges from a text file's unique characters

Re-baking When Ranges Change

The cache file name does not encode ranges, so existence alone can't say a .fnt is current. After either generator succeeds, HeadlessFontGenerationService appends one line to the text .fnt recording the requested ranges (gum ranges="32-126,160-255", FontRangesStamp). CreateBitmapFontFilesIfNecessaryAsync re-bakes an existing file when the recorded codepoints differ from the ranges asked for now (compared as sets, so spelling doesn't matter). A .fnt with no line (older bakes, bmfont.exe output, XML/binary format) is treated as current, unless the font's ranges came from its own FontRangeEntries entry (BmfcSave.RangesAreFontSpecific, set from GumProjectSave.GetFontRanges(font, out isFontSpecific)): a per-font entry is newer than any unstamped bake, so that file can't have used it and re-bakes once. ParsedFontFile skips the unknown gum tag, as it does KernSmith's own trailing kernsmith line; the page scan matches the text page id= anywhere in the file, so never put that in a stamped value. The glyph ids in the file can't stand in for the requested ranges, since a font that lacks a glyph omits it.

Embedded Resources

bmfont.exe and BmfcTemplate.bmfc are embedded in the Gum.ProjectServices assembly and extracted on first use by EnsureToolsExtracted into FileManager.UserApplicationDataForThisApplication/FontTools, never the install folder (it may be read-only). The template uses placeholder tokens like FontNameVariable, FontSizeVariable, {UseSmoothing}, etc.

Standalone CLI

GumProjectFontGenerator is a standalone console app that loads a .gumx project and generates all missing fonts. It uses HeadlessFontGenerationService directly with no callbacks.

Font Creation Paths

All font generation now routes through HeadlessFontGenerationService. There are two call sites:

On-demand: CustomSetPropertyOnRenderable resolves IFontManager via DI (Builder.Get<IFontManager>()) and calls CreateFontIfNecessary(BmfcSave) when a font property changes. The BBCode path (GetAndCreateFontIfNecessary) uses the same pattern for inline font tags.

Bulk (tool-only): CreateAllMissingFontFiles scans the entire project on load or "regenerate fonts" and generates all missing font files in parallel.

BBCode runs. The tool generates fonts for BBCode runs when the wireframe draws a Text: ApplyFontVariables resolves each run's font stack and calls IFontManager.CreateFontIfNecessary. The bulk collection (FontReferenceCollector, CollectRequiredFonts, gumcli fonts) replays the same stack model through the shared helper BbCodeFontStacks (GumRuntime/BbCodeFontStacks.cs), seeded from the Text's own font, over every state's Text value. A change to which tags affect the font goes in that helper so both paths change together.

Both delegate to HeadlessFontGenerationService. Legacy IRuntimeFontService, GenerateMissingFontsForReferencingElements, and the embedded bmfont.exe in RenderingLibrary have been removed.

The two paths overlap at project load. The bulk pass runs on background tasks while the wireframe resolves fonts synchronously on the UI thread. HeadlessFontGenerationService.TryCreateFontFor keeps one in-flight generation per target .fnt (_inFlight): an async caller joins it, a sync caller gets FontFileStatus.Generating (it cannot block, the in-flight continuations need the UI thread) and GetOrCreateBakedFont then returns null without caching or blacklisting. FontCacheLogic reloads wireframe content once the bulk pass reports it generated anything, so text that resolved mid-flight picks the files up.

Key Files

FilePurpose
Tools/Gum.Presentation/Services/Fonts/IFontManager.csInterface for the tool-facing font manager
Tools/Gum.Presentation/Services/Fonts/FontManager.csTool facade — delegates to headless service via DI
Tools/Gum.ProjectServices/FontGeneration/HeadlessFontGenerationService.csCore generation logic — collection, size estimation, bmfont.exe invocation
Tools/Gum.ProjectServices/FontGeneration/IHeadlessFontGenerationService.csInterface for the headless service
Tools/Gum.ProjectServices/FontGeneration/IFontGenerationCallbacks.csCallback interface (output, spinner, file-watch ignore)
Tools/Gum.Presentation/Services/Fonts/ToolFontGenerationCallbacks.csTool-specific callback implementation
RenderingLibrary/Graphics/Fonts/BmfcSave.csFont data model, .bmfc serialization, cache file naming, range utilities
GumCommon/Bundle/FontReferenceCollector.csBuilds every BmfcSave a project needs from its variables
Tools/Gum.Presentation/Plugins/InternalPlugins/FontsPlugin/The Fonts settings page's FontsViewModel (ranges table plus generation settings), FontsChangeLogic, and its rows in SettingsWindow/FontsRows.cs; the plugin and page view are Avalonia-head only (Tool/Gum.Avalonia/Plugins/Fonts/, Settings/FontsSettingsPageView.cs, FontRangesDisplay.cs), so the frozen WPF head has no Fonts settings page
Gum/Content/BmfcTemplate.bmfcTemplate with placeholders for bmfont.exe config
GumProjectFontGenerator/Program.csStandalone CLI for batch font generation

Off Windows: BmFont requests resolve to KernSmith

bmfont.exe only runs on Windows, but GumProjectSave.FontGenerator defaults to BmFont for back-compat. FontGeneratorResolver (Gum.ProjectServices) maps the requested type to the effective one: BmFont on macOS/Linux becomes KernSmith; everything else passes through. FontFileGeneratorSelector and the CLI fonts command both go through it, and the selector takes an optional isBmFontSupported delegate so tests can exercise the substitution on any OS. Packages published for macOS/Linux do not embed bmfont.exe at all: the release workflow passes -p:EmbedBmFont=false for non-win-* RIDs (the SDK strips RuntimeIdentifier from library references, so a custom global property is the channel), and FontGeneratorResolver.IsBmFontSupported also requires BmFontExeFileGenerator.IsEmbeddedInThisAssembly. BmFontEmbeddingTests (RepoHygiene) pins the csproj condition; smoke-test-package.sh checks each packaged Gum.ProjectServices.dll. Plain dotnet build/test keeps the resource.

KernSmith output differs slightly from bmfont output, so a project generated on Windows and then on macOS will have different .fnt/.png bytes unless it already uses KernSmith.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.