text

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 24, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const AsciiGlyphCount = 128

Variables

View Source
var AllocPageFn func() int

AllocPageFn allocates and returns a new atlas page index. Wired by root.

View Source
var NextPageFn func() int

NextPageFn returns the next available atlas page index. Wired by root.

View Source
var RegisterPageFn func(pageIndex int, img *ebiten.Image)

RegisterPageFn registers an atlas page image. Wired by root.

Functions

func GenerateSDFFromBitmaps

func GenerateSDFFromBitmaps(glyphs []GlyphBitmap, opts SDFGenOptions) (*image.NRGBA, []byte, error)

GenerateSDFFromBitmaps creates an SDF atlas from pre-rasterized glyph bitmaps. This is the core algorithm used by both runtime and offline generation paths. Each GlyphBitmap should have its Img field set to the rasterized glyph.

Returns the atlas image and metrics JSON.

func LoadDistanceFieldFontFromTTF

func LoadDistanceFieldFontFromTTF(ttfData []byte, opts SDFGenOptions) (*distanceFieldFont, *ebiten.Image, *image.NRGBA, []byte, error)

LoadDistanceFieldFontFromTTF generates an SDF font atlas at runtime from TTF/OTF data. Uses pure-Go rasterization (golang.org/x/image/font/opentype) so it can be called before the Ebitengine game loop starts. Returns the font, the atlas as an ebiten.Image (caller must register via Scene.RegisterPage), the raw atlas as an *image.NRGBA (for saving to disk), and any error.

func LoadDistanceFieldFontFromTTFMSDF

func LoadDistanceFieldFontFromTTFMSDF(ttfData []byte, opts SDFGenOptions) (*distanceFieldFont, *ebiten.Image, *image.NRGBA, error)

LoadDistanceFieldFontFromTTFMSDF generates an MSDF atlas from TTF/OTF data. It extracts glyph outlines, computes per-channel signed distances, and packs the results into an atlas. Distances are encoded in R, G, B channels; the MSDF shader reads median(R,G,B) to recover sharp edges and corners.

EXPERIMENTAL — MSDF produces inconsistent rendering quality compared to SDF. Multi-contour glyphs (0, 8, @, etc.) exhibit anti-aliasing artifacts and channel divergence that degrades text appearance. The pipeline is architecturally complete (edge coloring, contour combiner, error correction) but the output quality does not match the reference msdfgen implementation. Use LoadDistanceFieldFontFromTTF (single-channel SDF) for production use.

func LoadFontFromPath

func LoadFontFromPath(path string) ([]byte, error)

LoadFontFromPath reads a TTF/OTF file from disk.

func LoadFontFromSystem

func LoadFontFromSystem(name string) ([]byte, error)

LoadFontFromSystem searches OS system font directories for a font by name.

Types

type AtlasEntry

type AtlasEntry struct {
	Style    FontStyle
	BakeSize float64
	PNG      []byte
	JSON     []byte
}

AtlasEntry holds the raw PNG and JSON bytes for one baked atlas (style + bake size).

type FontFamily

type FontFamily struct {
	// contains filtered or unexported fields
}

FontFamily holds SDF atlases for multiple styles and bake sizes, or wraps a pixel font. It is the only public font type in willow.

func NewFontFamilyFromFontBundle

func NewFontFamilyFromFontBundle(data []byte) (*FontFamily, error)

NewFontFamilyFromFontBundle loads a pre-baked .fontbundle archive and returns a FontFamily. A .fontbundle is a zip with entries named {style}_{size}.png / {style}_{size}.json. For file loading, chain with os.ReadFile:

ff, err := willow.NewFontFamilyFromFontBundle(must(os.ReadFile("my.fontbundle")))

func NewFontFamilyFromPixelFont

func NewFontFamilyFromPixelFont(img *ebiten.Image, cellW, cellH int, chars string) *FontFamily

NewFontFamilyFromPixelFont wraps a pixel spritesheet into a FontFamily.

func NewFontFamilyFromTTF

func NewFontFamilyFromTTF(cfg FontFamilyConfig) (*FontFamily, error)

NewFontFamilyFromTTF creates a FontFamily from TTF/OTF data. All style variants are provided in the config struct. BakeSizes defaults to [64, 256].

func (*FontFamily) Atlases

func (ff *FontFamily) Atlases() []AtlasEntry

Atlases returns all retained raw PNG+JSON atlas entries (for fontgen CLI).

func (*FontFamily) IsPixelMode

func (ff *FontFamily) IsPixelMode() bool

IsPixelMode returns true if this FontFamily wraps a pixel spritesheet font.

func (*FontFamily) LineHeight

func (ff *FontFamily) LineHeight(displaySize float64, bold, italic bool) float64

LineHeight returns the font's native line height in atlas pixels for the resolved style.

func (*FontFamily) MeasureString

func (ff *FontFamily) MeasureString(text string, displaySize float64, bold, italic bool) (w, h float64)

MeasureString returns the width and height of text in atlas pixels for the resolved style.

func (*FontFamily) PixelCellSize

func (ff *FontFamily) PixelCellSize() (int, int)

PixelCellSize returns cellW, cellH for the pixel font.

func (*FontFamily) PixelPage

func (ff *FontFamily) PixelPage() uint16

PixelPage returns the atlas page for the pixel font.

func (*FontFamily) SDFDistanceRange

func (ff *FontFamily) SDFDistanceRange(displaySize float64, bold, italic bool) float64

SDFDistanceRange returns the distance range for the resolved SDF font.

func (*FontFamily) SDFFontSize

func (ff *FontFamily) SDFFontSize(displaySize float64, bold, italic bool) float64

SDFFontSize returns the design bake size for the resolved SDF font.

func (*FontFamily) SDFIsMultiChannel

func (ff *FontFamily) SDFIsMultiChannel(displaySize float64, bold, italic bool) bool

SDFIsMultiChannel returns true if the resolved SDF font is MSDF.

func (*FontFamily) SDFLineHeight

func (ff *FontFamily) SDFLineHeight(displaySize float64, bold, italic bool) float64

SDFLineHeight returns the line height for the resolved SDF font.

func (*FontFamily) SDFPage

func (ff *FontFamily) SDFPage(displaySize float64, bold, italic bool) uint16

SDFPage returns the atlas page index for the resolved SDF font.

func (*FontFamily) TTFData

func (ff *FontFamily) TTFData(bold, italic bool) []byte

TTFData returns the original TTF/OTF byte data for the resolved style variant. Returns nil for pixel fonts or if no TTF data was retained.

func (*FontFamily) TrimCell

func (ff *FontFamily) TrimCell(top, right, bottom, left int)

TrimCell trims pixels from each side of every pixel-font cell. No-op if this FontFamily was not created from a pixel font.

type FontFamilyConfig

type FontFamilyConfig struct {
	Regular    []byte    // required — TTF/OTF data for the regular style
	Bold       []byte    // optional — TTF/OTF data for bold
	Italic     []byte    // optional — TTF/OTF data for italic
	BoldItalic []byte    // optional — TTF/OTF data for bold-italic
	BakeSizes  []float64 // optional — defaults to [64, 256]
}

FontFamilyConfig configures a FontFamily created from TTF/OTF data.

type FontStyle

type FontStyle int

FontStyle identifies a typographic style variant.

const (
	FontStyleRegular FontStyle = iota
	FontStyleBold
	FontStyleItalic
	FontStyleBoldItalic
)

type Glyph

type Glyph struct {
	ID       rune
	X, Y     uint16
	Width    uint16
	Height   uint16
	XOffset  int16
	YOffset  int16
	XAdvance int16
	Page     uint16
}

Glyph holds glyph metrics and atlas position.

type GlyphBitmap

type GlyphBitmap struct {
	ID       rune
	Img      *image.Alpha // rasterized glyph (grayscale)
	XOffset  int
	YOffset  int
	XAdvance int
	// contains filtered or unexported fields
}

GlyphBitmap holds a rasterized glyph and its metrics for atlas packing.

type GlyphPos

type GlyphPos struct {
	X, Y   float64
	Region types.TextureRegion
	Page   uint16
}

GlyphPos is the computed screen position and region for a single glyph.

type SDFGenOptions

type SDFGenOptions struct {
	// Size is the font size in pixels for rasterization.
	Size float64
	// DistanceRange is the pixel range of the distance field (typically 4-8).
	DistanceRange float64
	// Chars is the set of characters to include. Empty means printable ASCII (32-126).
	Chars string
	// AtlasWidth is the maximum atlas width in pixels. Default 1024.
	AtlasWidth int
	// PageIndex is the atlas page index for the generated font. Default 0.
	PageIndex uint16
	// MSDF enables multi-channel SDF generation.
	MSDF bool
}

SDFGenOptions configures SDF atlas generation.

func (*SDFGenOptions) Defaults

func (o *SDFGenOptions) Defaults()

Defaults fills in zero-valued options with sensible defaults.

type TextBlock

type TextBlock struct {
	// Content is the text string to render. Supports embedded newlines.
	Content string
	// Font is the font family used for measurement and rendering.
	Font *FontFamily
	// FontSize is the desired display size in pixels. Applied at render time as a
	// scale factor (FontSize / Font.LineHeight()), independent of ScaleX/ScaleY.
	// Defaults to 16. Set to 0 or negative to use the font's native atlas size.
	FontSize float64
	// Bold selects the bold variant when resolving the font.
	Bold bool
	// Italic selects the italic variant when resolving the font.
	Italic bool
	// Align controls horizontal alignment within the wrap width or measured bounds.
	Align types.TextAlign
	// WrapWidth is the maximum line width in screen pixels before word wrapping.
	// Internally converted to atlas pixels via FontScale. Zero means no wrapping.
	WrapWidth float64
	// Color is the fill color for the text glyphs.
	Color types.Color
	// LineHeight overrides the font's default line height. Zero uses the font's native value.
	LineHeight float64
	// Sharpness tightens the SDF edge smoothstep window. 0.0 = default rendering,
	// 1.0 = sharpest (half the default smoothing width). Values around 0.5–0.7
	// give crisp edges without aliasing on most display densities.
	Sharpness float64

	// Cached layout (unexported)
	LayoutDirty bool
	MeasuredW   float64
	MeasuredH   float64
	Lines       []TextLine // cached line layout

	// SDF rendering fields
	TextEffects   *TextEffects    // nil = no effects (plain fill)
	SdfVerts      []ebiten.Vertex // local-space glyph quads, rebuilt on layout change
	SdfInds       []uint16        // glyph index buffer
	SdfVertCount  int             // active vertex count
	SdfIndCount   int             // active index count
	SdfUniforms   map[string]any  // cached uniform map (allocated once, updated in place)
	SdfShader     *ebiten.Shader  // cached SDF vs MSDF shader selection
	UniformsDirty bool            // triggers uniform rebuild
}

TextBlock holds text content, formatting, and cached layout state.

func (*TextBlock) EffectiveLineHeight

func (tb *TextBlock) EffectiveLineHeight() float64

EffectiveLineHeight returns the effective line height in atlas pixels.

func (*TextBlock) FontScale

func (tb *TextBlock) FontScale() float64

FontScale returns the scale factor that maps native atlas pixels to display pixels. Returns 1.0 when FontSize is zero/negative or Font is nil.

func (*TextBlock) Invalidate

func (tb *TextBlock) Invalidate()

Invalidate invalidates the cached layout and SDF image, forcing recomputation on the next frame.

func (*TextBlock) Layout

func (tb *TextBlock) Layout() []TextLine

Layout recomputes glyph positions if dirty. Returns the cached lines.

func (*TextBlock) LayoutPixel

func (tb *TextBlock) LayoutPixel(glyphLookup func(r rune) (x, y uint16, found bool), page uint16, cellW, cellH, padLeft, padTop, advW, advH int)

LayoutPixel computes glyph positions for a pixel font (monospaced grid).

func (*TextBlock) LayoutSDF

func (tb *TextBlock) LayoutSDF(glyphLookup func(r rune) *Glyph, kernLookup func(first, second rune) int16, page uint16)

LayoutSDF computes glyph positions for an SDF font.

func (*TextBlock) MeasureDisplay

func (tb *TextBlock) MeasureDisplay(text string) (width, height float64)

MeasureDisplay returns the display-pixel width and height of the rendered text, accounting for FontSize scaling.

func (*TextBlock) RebuildLocalVerts

func (tb *TextBlock) RebuildLocalVerts(lineHeight float64)

RebuildLocalVerts builds local-space vertex/index buffers from the laid-out glyph positions.

type TextEffects

type TextEffects struct {
	OutlineWidth   float64 // 0 = no outline
	OutlineColor   types.Color
	GlowWidth      float64 // 0 = no glow
	GlowColor      types.Color
	ShadowOffset   types.Vec2 // (0,0) = no shadow
	ShadowColor    types.Color
	ShadowSoftness float64
}

TextEffects configures text effects (outline, glow, shadow) rendered in a single shader pass. All widths are in distance-field units (relative to the font's DistanceRange).

type TextLine

type TextLine struct {
	Glyphs []GlyphPos
	Width  float64
}

TextLine stores one line of laid-out glyphs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL