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.
In this repository69 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- debuggingSkill
- frb-build-verificationSkill
- frb-pixel-harnessSkill
- gum-architecture-layersSkill
- gum-bundleSkill
- gum-cliSkill
- gum-cross-platform-unificationSkill
- gum-docs-writingSkill
- gum-file-pathsSkill
- gum-forms-behaviorsSkill
- gum-forms-controlsSkill
- gum-forms-default-visualsSkill
- gum-forms-itemscontrolSkill
- gum-forms-theme-importSkill
- gum-iconsSkill
- gum-issue-creationSkill
- gum-kernsmith-integrationsSkill
- gum-layout-engineSkill
- gum-layoutSkill
- gum-localizationSkill
- gum-monogame-renderingSkill
- gum-monthly-releaseSkill
- gum-project-versioningSkill
- gum-property-assignmentSkill
- gum-raylib-renderingSkill
- gum-releaseSkill
- gum-runtime-animation-chainsSkill
- gum-runtime-bindingSkill
- gum-runtime-fontsSkill
- gum-runtime-hot-reloadSkill
- gum-runtime-syntax-versionSkill
- gum-runtime-systemmanagers-initSkill
- gum-runtime-topologySkill
- gum-runtime-variable-referencesSkill
- gum-samplesSkill
- gum-serviceSkill
- gum-source-linked-projectSkill
- gum-themingSkill
- gum-tool-animationsSkill
- gum-tool-codegenSkill
- gum-tool-copy-pasteSkill
- gum-tool-delete-logicSkill
- gum-tool-dialogsSkill
- gum-tool-errorsSkill
- gum-tool-file-watchSkill
- gum-tool-import-from-gumxSkill
- gum-tool-loggingSkill
- gum-tool-outputSkill
- gum-tool-pluginsSkill
- gum-tool-save-classesSkill
- gum-tool-screenshotsSkill
- gum-tool-selectionSkill
- gum-tool-tree-viewSkill
- gum-tool-undoSkill
- gum-tool-variable-gridSkill
- gum-tool-variable-referencesSkill
- gum-tool-viewmodelsSkill
- gum-unit-testsSkill
- gum-variable-deep-diveSkill
- The first 60 shown.
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
- Very specific: line 41
Size estimation: Before generating, AssignEstimatedNeededSizeOn either runs a binary-search optimization (GetOptimizedSizeFor, controlled …
- Very specific: line 44
File-watch suppression: Before writing, all expected output paths (.bmfc, .fnt, .png pages) are registered with …
- Distinctive: line 58
When OutlineThickness is 0: alpha=0, RGB channels=4 (glyph in alpha channel).
- Distinctive: line 59
When OutlineThickness > 0: alpha=1, RGB channels=0 (outline uses color channels).
- Very specific: line 69
Default: 32-126,160-255 (ASCII + Latin-1 Supplement)
- Very specific: line 90
All font generation now routes through HeadlessFontGenerationService.
≈ “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.
Files
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):
BmFontExeFileGeneratorshells out to the embeddedbmfont.exe(Windows-only). Legacy path; does not support dropshadow at all —BmfcTemplate.bmfchas no dropshadow placeholders, soBmfcSave.HasDropshadow/Dropshadow*fields are silently ignored on this backend.KernSmithFileGeneratorcalls 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 | KernSmithFileGeneratorFontManager 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 viaTask.WhenAllfor 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
- Property collection:
FontReferenceCollector.BuildBmfcSave(GumCommon/Bundle/FontReferenceCollector.cs) reads font properties through agetValuecallback and returns aBmfcSaveor null. It is the single source of truth for building aBmfcSavefrom 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,CollectFontsFromNestedTextInstancesrecursively descends usingRecursiveVariableFinderto resolve font properties through exposed variables, inheritance, and categorized states a container assigns through an exposed variable (e.g.StyleCategoryState). A conditionalVariableReferencesrow on a component instance that drives a font variable inside the component has every branch collected (CollectFontsFromNestedTextInstancesAllBranches). - Deduplication:
CollectRequiredFontsiterates all elements/states/instances and deduplicates byFontCacheFileName(a deterministic name encoding all font parameters). - Size estimation: Before generating,
AssignEstimatedNeededSizeOneither runs a binary-search optimization (GetOptimizedSizeFor, controlled byAutoSizeFontOutputsproject setting) or uses a heuristic lookup table (EstimateBlocksNeeded) based on effective font size. - Template expansion:
BmfcSave.Save()loadsContent/BmfcTemplate.bmfc, replaces placeholders, and writes the.bmfcfile alongside the target.fntpath. - bmfont.exe invocation:
CreateBitmapFontFilesIfNecessaryAsynclaunchesbmfont.exe -c "<bmfc>" -o "<fnt>"viaProcess.StartwithUseShellExecute = true. The process is awaited async (WaitForExitAsync) or synchronously depending oncreateTask. - File-watch suppression: Before writing, all expected output paths (.bmfc, .fnt, .png pages) are registered with
IFontGenerationCallbacks.OnIgnoreFileChangeso 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 withGumProjectSave.GetFontRanges(family)(family entry, else global entry, else null so the caller usesBmfcSave.GetEffectiveDefaultRanges()). The scalarFontRangesis 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 readFontRangeEntryCheckerfor 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 GenerateRangesFromFilecan 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
| File | Purpose |
Tools/Gum.Presentation/Services/Fonts/IFontManager.cs | Interface for the tool-facing font manager |
Tools/Gum.Presentation/Services/Fonts/FontManager.cs | Tool facade — delegates to headless service via DI |
Tools/Gum.ProjectServices/FontGeneration/HeadlessFontGenerationService.cs | Core generation logic — collection, size estimation, bmfont.exe invocation |
Tools/Gum.ProjectServices/FontGeneration/IHeadlessFontGenerationService.cs | Interface for the headless service |
Tools/Gum.ProjectServices/FontGeneration/IFontGenerationCallbacks.cs | Callback interface (output, spinner, file-watch ignore) |
Tools/Gum.Presentation/Services/Fonts/ToolFontGenerationCallbacks.cs | Tool-specific callback implementation |
RenderingLibrary/Graphics/Fonts/BmfcSave.cs | Font data model, .bmfc serialization, cache file naming, range utilities |
GumCommon/Bundle/FontReferenceCollector.cs | Builds 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.bmfc | Template with placeholders for bmfont.exe config |
GumProjectFontGenerator/Program.cs | Standalone 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.
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
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.

