text

package
v0.4.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 30 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package text is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package text draws bitmap fonts (AngelCode BMFont) through sprite batches, signed-distance-field fonts that stay sharp at any size on the screen or in 3D world space (SDFFont, WorldText), and platform-rendered text through core.Drawing.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendRichToBatch

func AppendRichToBatch(batch *sprite.Batch, layout RichLayout, pos core.Point, opts RichOptions) int

AppendRichToBatch appends sprites from layout whose resolved atlas matches batch.Atlas (both bitmap glyphs and inline icons on that atlas) into batch, positioned at pos with per-glyph effects evaluated at opts.Elapsed.

It returns the number of sprites appended to batch. Placements requiring a different atlas or faux-italic shear transform are skipped.

func BreakLines

func BreakLines(s string, max int) []string

BreakLines splits text into lines of at most max runes, breaking at the last space or tab that fits and otherwise between runes, so CJK text without spaces is split rune by rune.

func DefaultPunctuationPause

func DefaultPunctuationPause() map[rune]float32

DefaultPunctuationPause returns a standard dialogue punctuation pause table (4x step after sentence terminators, 2x step after clause separators).

func DrawPlatform

func DrawPlatform(d *core.Drawing, text string, x, y float32, style PlatformStyle)

DrawPlatform draws text at (x, y) into d using core.Drawing.FillText.

It draws inside the drawing's active transform stack so text scales automatically with a game view's virtual resolution transform, and wraps its style changes in Save/Restore so fill color, alpha, alignment, and baseline never leak to subsequent draw calls.

func DrawRich

func DrawRich(d *core.Drawing, font *Font, rt RichText, pos core.Point, opts RichOptions)

DrawRich lays out and draws rt at pos into d.

When font is non-nil, bitmap glyph rendering is used (with cached pixel tinting for colored spans when the page image provides Pixels or Data, and sprite.Batch grouping for glyphs and inline icons). When font is nil and opts.Platform is set, platform-text rich span rendering is used.

func DrawRichLayout

func DrawRichLayout(d *core.Drawing, layout RichLayout, pos core.Point, opts RichOptions)

DrawRichLayout draws a previously computed RichLayout at pos into d, applying per-glyph effects evaluated at opts.Elapsed.

func DrawRichPlatform

func DrawRichPlatform(d *core.Drawing, rt RichText, pos core.Point, style PlatformStyle, opts RichOptions)

DrawRichPlatform lays out and draws rt at pos into d using platform text (core.Drawing.FillText) for styled text spans and inline images/atlas frames for icons.

func Ellipsize

func Ellipsize(s string, max int, mode Overrun) string

Ellipsize truncates text to at most max runes according to mode; text that already fits is returned unchanged.

func EvalGlyphTransform

func EvalGlyphTransform(effect GlyphEffect, glyphIndex int, elapsed float32) (dx, dy float32, colorOverride *core.Color)

EvalGlyphTransform evaluates effect for glyphIndex at time elapsed (in seconds).

The result is completely deterministic for any (effect.Seed, glyphIndex, elapsed) tuple and uses pure integer/float math without global RNG state.

func GenerateSDF

func GenerateSDF(alpha []uint8, width, height, distanceRange int) []uint8

GenerateSDF converts a binary alpha mask into a deterministic single-channel signed-distance field. Distances are encoded into [0,255], with 128 at the contour and range pixels spanning the requested distance range.

func GraphemeClusters

func GraphemeClusters(s string) []string

GraphemeClusters splits s into user-perceived characters according to Unicode extended grapheme cluster rules. A cluster keeps combining marks, regional-indicator flags, and emoji ZWJ sequences together.

func LineBreakOpportunities

func LineBreakOpportunities(s string, style LineBreakStyle) []int

LineBreakOpportunities returns the UTF-8 byte offsets in s where Unicode UAX #14 (with CJK kinsoku per style and Southeast Asian syllable breaking) allows a line break, excluding offset 0 and including len(s) for non-empty input.

func LogMissingGlyphsEnabled

func LogMissingGlyphsEnabled() bool

LogMissingGlyphsEnabled reports whether debug missing-glyph logging is currently enabled. It always returns false under -tags release.

func MeasurePlatform

func MeasurePlatform(d *core.Drawing, text string, style PlatformStyle) core.Size

MeasurePlatform returns the bounding width and height of text laid out with style on d.

func MeasureRich

func MeasureRich(font *Font, rt RichText, opts RichOptions) core.Size

MeasureRich returns the bounding width and height of rt laid out with font and opts.

func SetLogMissingGlyphs

func SetLogMissingGlyphs(enabled bool)

SetLogMissingGlyphs enables or disables logging each rune skipped by Font, SDFFont, or rich-text layout because the font has no glyph for it. Each missing rune is logged at most once per font instance.

Under -tags release, SetLogMissingGlyphs is a no-op and missing-glyph logging is compiled out.

func SetMissingGlyphLogger

func SetMissingGlyphLogger(fn func(face string, r rune))

SetMissingGlyphLogger sets a custom handler called once per missing rune and font when SetLogMissingGlyphs(true) is active. Passing nil restores the default log.Print output. Under -tags release, this is a no-op.

Types

type Align

type Align uint8

Align controls horizontal alignment of laid-out text lines.

const (
	// AlignLeft aligns lines to the left edge (x). This is the zero value.
	AlignLeft Align = iota
	// AlignCenter centers each line horizontally.
	AlignCenter
	// AlignRight aligns lines to the right edge.
	AlignRight
)

type EffectKind

type EffectKind uint8

EffectKind identifies a per-glyph animation effect.

const (
	// EffectNone disables per-glyph motion and color overrides.
	EffectNone EffectKind = iota
	// EffectWave displaces glyphs vertically along a smooth sine wave.
	EffectWave
	// EffectShake jitters glyphs deterministically in X and Y.
	EffectShake
	// EffectCustom invokes GlyphEffect.Custom to compute offsets and color overrides.
	EffectCustom
)

type Facing

type Facing uint8

Facing is how text placed in a 3D world turns.

const (
	// FacingBillboard turns the text to face the camera, upright on the screen, as name labels and damage numbers do. This is the zero value.
	FacingBillboard Facing = iota
	// FacingFixed lays the text in a plane of the world that WorldText.Rot sets, as a sign on a wall is: seen from the side it is foreshortened, seen from behind it is mirrored unless CullBackFace is set.
	FacingFixed
)

type FieldType

type FieldType uint8

FieldType is how a signed-distance-field atlas stores the distance to a glyph's outline.

const (
	// FieldSDF is a true signed distance field in one channel, read from red (a grayscale image's gray).
	FieldSDF FieldType = iota
	// FieldPSDF is a pseudo signed distance field in one channel, read from red, as FieldSDF is.
	FieldPSDF
	// FieldMSDF is a multi-channel signed distance field: the outline is the median of red, green and blue, which keeps corners sharp.
	FieldMSDF
	// FieldMTSDF is FieldMSDF with a true signed distance field in alpha, which outlines read for rounder corners.
	FieldMTSDF
)

func (FieldType) String

func (t FieldType) String() string

String returns the name msdf-atlas-gen and msdf-bmfont-xml give the field type: sdf, psdf, msdf or mtsdf.

type Font

type Font struct {
	// Face is the font face name from the info record.
	Face string
	// Size is the font size from the info record.
	Size float32
	// LineHeight is the distance between consecutive lines, in points.
	LineHeight float32
	// Base is the distance from the top of a line to the characters' baseline, in points.
	Base float32
	// Pages maps each BMFont page ID to the sprite.Atlas holding that page's glyphs.
	Pages map[int]*sprite.Atlas
	// Glyphs maps each rune to its Glyph metrics and frame.
	Glyphs map[rune]Glyph
	// Kernings maps pairs of consecutive runes to their horizontal kerning adjustment.
	Kernings map[KerningPair]float32
	// contains filtered or unexported fields
}

Font is a parsed AngelCode BMFont: one sprite.Atlas per texture page, glyph metrics, and kerning pairs.

func LoadBMFont

func LoadBMFont(data []byte, pageImage func(id int, file string) core.ImageSource) (*Font, error)

LoadBMFont parses AngelCode BMFont data in either plain-text or XML format.

For each texture page defined in the font, pageImage is called with the page ID and filename (in ascending page ID order) to obtain its core.ImageSource. If pageImage is nil, each page's atlas receives a zero core.ImageSource.

Its errors are *loaderr.Error values that give the line of the record at fault and how to fix it; a caller that read data from a file names it with loaderr.WithFile.

func LoadBMFontImage

func LoadBMFontImage(img core.ImageSource, data []byte) (*Font, error)

LoadBMFontImage parses a single-page AngelCode BMFont (plain-text or XML) backed by img. It returns an error if the font declares more than one page.

Example

LoadBMFontImage reads a bitmap font for one page image; Measure and Layout place its glyphs with their advances and kerning.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/text"
	"github.com/nsgo-dev/nsgo/core"
)

// font is a small BMFont in the text format that tools such as BMFont and Hiero export.
const font = `info face="Demo" size=16
common lineHeight=16 base=12 scaleW=64 scaleH=16 pages=1
page id=0 file="demo.png"
chars count=3
char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=0 xadvance=5 page=0 chnl=15
char id=65 x=0 y=0 width=8 height=10 xoffset=1 yoffset=2 xadvance=10 page=0 chnl=15
char id=66 x=8 y=0 width=8 height=10 xoffset=0 yoffset=2 xadvance=9 page=0 chnl=15
kernings count=1
kerning first=65 second=66 amount=-2
`

func main() {
	f, err := text.LoadBMFontImage(core.ImageSource{URI: "asset:demo.png"}, []byte(font))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(f.Face, f.LineHeight, f.Kerning('A', 'B'))
	fmt.Println(f.Measure("AB A", text.Options{}))
	for _, g := range f.Layout("AB", 0, 0, text.Options{}) {
		fmt.Println(string(g.Rune), g.X)
	}
}
Output:
Demo 16 -2
{32 16}
A 1
B 8

func (*Font) Draw

func (f *Font) Draw(d *core.Drawing, s string, x, y float32, opts Options)

Draw draws s at (x, y) into d through sprite.Batch (one batch per texture page used, preserving order; single-page fonts use one sprite.Batch).

When opts.Effects sets an outline, drop shadow, underline, or strikethrough, outline and shadow glyph silhouettes are cached per glyph and size so unchanged text draws without per-frame allocations.

func (*Font) Kerning

func (f *Font) Kerning(first, second rune) float32

Kerning returns the horizontal kerning adjustment when second follows first, or 0 if no kerning pair is defined.

func (*Font) Layout

func (f *Font) Layout(s string, x, y float32, opts Options) []GlyphPlacement

Layout computes the screen placements of all visible glyphs in s starting at (x, y).

func (*Font) Measure

func (f *Font) Measure(s string, opts Options) core.Size

Measure returns the bounding width and height of s laid out with opts.

func (*Font) MissingRunes

func (f *Font) MissingRunes(s string) []rune

MissingRunes returns the sorted, deduplicated non-control runes in s that f has no glyph for. Control characters (such as newlines and tabs) are ignored.

type Glyph

type Glyph struct {
	// ID is the Unicode code point of the glyph.
	ID rune
	// Frame is the glyph's rectangle in its page's sprite.Atlas.
	Frame sprite.Frame
	// XOffset and YOffset displace the glyph's drawn rectangle from the cursor.
	XOffset, YOffset float32
	// XAdvance is how far the cursor advances after this glyph.
	XAdvance float32
	// Page is the BMFont texture page ID holding this glyph.
	Page int
}

Glyph is one character in a bitmap font: its atlas frame, placement offsets, cursor advance, and texture page ID.

type GlyphEffect

type GlyphEffect struct {
	Kind      EffectKind
	Seed      uint64
	Amplitude float32
	Frequency float32
	Speed     float32
	// Custom is invoked when Kind == EffectCustom.
	Custom GlyphEffectFunc
}

GlyphEffect configures a deterministic per-glyph animation effect.

type GlyphEffectFunc

type GlyphEffectFunc func(effect GlyphEffect, glyphIndex int, elapsed float32) (dx, dy float32, colorOverride *core.Color)

GlyphEffectFunc computes a deterministic per-glyph translation (dx, dy) and optional color override for EffectCustom.

type GlyphPlacement

type GlyphPlacement struct {
	// Rune is the character this placement came from.
	Rune rune
	// Glyph is the font's glyph metrics and atlas frame.
	Glyph Glyph
	// X and Y are the top-left position of the drawn glyph rectangle, in points.
	X, Y float32
	// W and H are the drawn width and height of the glyph rectangle, in points.
	W, H float32
	// Line is the zero-based line index containing this glyph.
	Line int
}

GlyphPlacement is one visible glyph positioned by Font.Layout.

type Icon

type Icon struct {
	// Image is the texture containing the icon. When empty and Atlas != nil,
	// Atlas.Image is used.
	Image core.ImageSource
	// Atlas optionally identifies the sprite.Atlas holding Frame for sprite.Batch grouping.
	Atlas *sprite.Atlas
	// Frame is the sub-rectangle in Image/Atlas. When Frame.W == 0 && Frame.H == 0,
	// the entire Image is drawn.
	Frame sprite.Frame
	// Width and Height are the icon's drawn size in points at scale 1.
	// When 0, they default to Frame.Width/Frame.Height (or Frame.W/Frame.H, or Image size).
	Width, Height float32
	// Advance is the horizontal cursor advance in points at scale 1.
	// When <= 0, it defaults to Width.
	Advance float32
	// BaselineOffset shifts the icon vertically relative to the text baseline
	// (positive moves down, negative moves up). With 0, the bottom of the icon
	// sits on the text baseline.
	BaselineOffset float32
}

Icon describes an inline image or sprite atlas frame embedded inside rich text.

type IconResolver

type IconResolver func(name string) (Icon, bool)

IconResolver resolves an inline icon name (from [icon=name]) to an Icon.

func AtlasIconResolver

func AtlasIconResolver(atlas *sprite.Atlas) IconResolver

AtlasIconResolver returns an IconResolver that looks up named frames in atlas.

type KerningPair

type KerningPair struct {
	First, Second rune
}

KerningPair identifies an ordered pair of consecutive runes that carry a horizontal kerning adjustment.

type LineBreakStyle

type LineBreakStyle uint8

LineBreakStyle controls CJK prohibited-character (kinsoku) strictness during UAX #14 line breaking.

const (
	// LineBreakStrict follows Unicode UAX #14 default rules (CJ resolved to NS):
	// closing punctuation, Japanese small kana (っ, ゃ, ゅ, ょ, ...), prolonged sound mark (ー),
	// and iteration marks cannot start a line, and opening brackets cannot end a line.
	LineBreakStrict LineBreakStyle = iota
	// LineBreakNormal relaxes conditional Japanese starters (small kana and prolonged sound mark ー)
	// so breaks may occur before them, while still prohibiting closing punctuation at line start
	// and opening brackets at line end.
	LineBreakNormal
)

type LineLayout

type LineLayout struct {
	// Lines are the laid-out logical lines after wrapping, MaxLines capping, and Overrun handling.
	Lines []string
	// MaxLineWidth is the widest measured line width in Lines, in points.
	MaxLineWidth float32
	// Truncated reports whether Overrun cut any text (by clip or ellipsis).
	Truncated bool
	// Overflow reports whether the input text exceeded MaxWidth or MaxLines before overrun handling.
	Overflow bool
}

LineLayout is the result of LayoutLines.

func LayoutLines

func LayoutLines(s string, opts LineLayoutOptions, measure func(string) float32) LineLayout

LayoutLines splits s into lines using Unicode UAX #14 line breaking (with CJK kinsoku and Southeast Asian syllable breaking), applying Wrap, MaxLines, and Overrun against widths returned by measure.

type LineLayoutOptions

type LineLayoutOptions struct {
	// MaxWidth is the maximum line width in points; <= 0 disables width-based wrapping and clipping.
	MaxWidth float32
	// Wrap selects the line wrapping strategy when MaxWidth > 0 (WrapDefault resolves to WrapWordSmart).
	Wrap Wrap
	// LineBreak selects CJK kinsoku strictness (LineBreakStrict or LineBreakNormal).
	LineBreak LineBreakStyle
	// Overrun controls how text exceeding MaxWidth or MaxLines is truncated.
	Overrun Overrun
	// MaxLines caps the number of output lines when > 0.
	MaxLines int
	// Ellipsis overrides the ellipsis string appended for OverrunEllipsis and OverrunWordEllipsis.
	// Empty defaults to "…".
	Ellipsis string
}

LineLayoutOptions configures LayoutLines.

type Options

type Options struct {
	// Effects configures outline, drop shadow, underline, and strikethrough for drawn text.
	Effects TextEffects
	// MaxWidth wraps lines to fit within MaxWidth points when > 0, and defines
	// the alignment box [x, x+MaxWidth] for AlignCenter and AlignRight.
	// When MaxWidth <= 0, lines do not wrap and AlignCenter/AlignRight align
	// relative to x directly (centered at x, or right edge at x).
	MaxWidth float32
	// Wrap selects how lines break when MaxWidth > 0 (WrapDefault uses WrapWordSmart).
	Wrap Wrap
	// LineBreak controls CJK prohibited-character (kinsoku) strictness (LineBreakStrict or LineBreakNormal).
	LineBreak LineBreakStyle
	// Overrun controls how text exceeding MaxWidth or MaxLines is clipped or ellipsized.
	Overrun Overrun
	// MaxLines caps the number of laid-out lines when > 0.
	MaxLines int
	// Direction controls bidirectional visual ordering for laid-out lines (DirectionAuto detects from the line's first strong character).
	Direction RichDirection
	// Align is the horizontal alignment of each line.
	Align Align
	// Scale multiplies glyph positions and sizes; 0 means 1.
	// A negative scale measures and draws nothing.
	Scale float32
	// Alpha is the text opacity from 0 to 1; 0 means 1 (fully opaque).
	// A negative alpha draws nothing.
	Alpha float32
	// LineSpacing is extra vertical space added between lines, in points.
	LineSpacing float32
	// Z is passed to each sprite in the underlying sprite.Batch.
	Z int
}

Options configures how a Font measures, lays out, and draws text.

Its zero value draws left-aligned at scale 1 and full opacity with no wrapping.

type Overrun

type Overrun uint8

Overrun controls how text exceeding its available width or MaxLines is represented.

const (
	// OverrunNone leaves overflowing lines uncut (only capping line count when MaxLines > 0).
	// This is the zero value.
	OverrunNone Overrun = iota
	// OverrunClip cuts overflowing text at the available width and MaxLines without adding an ellipsis.
	OverrunClip
	// OverrunEllipsis truncates overflowing text by extended grapheme cluster and appends an ellipsis
	// ("…" when the font provides it, otherwise "...").
	OverrunEllipsis
	// OverrunWordEllipsis truncates overflowing text at the last UAX #14 break or word boundary that
	// leaves room for an ellipsis, falling back to OverrunEllipsis when the first segment alone does not fit.
	OverrunWordEllipsis
)

func ParseOverrun

func ParseOverrun(s string) (Overrun, bool)

ParseOverrun parses a canonical overrun name ("clip", "ellipsis", "word_ellipsis", or ""/"none").

func (Overrun) String

func (o Overrun) String() string

String returns the canonical snake_case name of o ("none", "clip", "ellipsis", or "word_ellipsis").

type PlatformStyle

type PlatformStyle struct {
	// Effects configures outline, drop shadow (including blur), underline, and strikethrough.
	Effects TextEffects
	// Font selects the platform font family, size, weight, italic, and language.
	// When Font.Size <= 0, core.DefaultFontSize is used.
	Font core.Font
	// Color sets the text fill color when non-zero; when 0, the drawing's
	// current fill color is kept.
	Color core.Color
	// Alpha sets the text opacity from 0 to 1; 0 means 1 (keep full opacity).
	// A negative value draws nothing.
	Alpha float32
	// Align aligns each line horizontally (AlignLeft, AlignCenter, AlignRight).
	Align Align
	// Baseline sets which line of text sits at y (zero value is core.BaselineAlphabetic).
	Baseline core.TextBaseline
	// MaxWidth wraps lines to fit within MaxWidth points when > 0, and defines
	// the alignment box [x, x+MaxWidth] for AlignCenter and AlignRight.
	// When MaxWidth <= 0, lines do not wrap and AlignCenter/AlignRight align
	// relative to x directly.
	MaxWidth float32
	// Wrap selects how lines break when MaxWidth > 0 (WrapDefault uses WrapWordSmart).
	Wrap Wrap
	// LineBreak controls CJK prohibited-character (kinsoku) strictness (LineBreakStrict or LineBreakNormal).
	LineBreak LineBreakStyle
	// Overrun controls how text exceeding MaxWidth or MaxLines is clipped or ellipsized.
	Overrun Overrun
	// MaxLines caps the number of laid-out lines when > 0.
	MaxLines int
	// Direction optionally declares the base text direction (DirectionAuto detects from the line's first strong character).
	Direction RichDirection
	// LineHeight overrides the distance between consecutive lines in points when > 0.
	// When <= 0, it uses the font's measured line height from d.TextMetrics.
	LineHeight float32
	// LineSpacing adds extra vertical space between lines, in points.
	LineSpacing float32
}

PlatformStyle configures platform-rendered text drawn with DrawPlatform.

Its zero value draws in core.DefaultFontSize at full opacity, left-aligned, on the alphabetic baseline, keeping the drawing's current fill color, with no wrapping.

type RichDirection

type RichDirection uint8

RichDirection controls bidirectional ordering in rich layout.

const (
	DirectionAuto RichDirection = iota
	DirectionLTR
	DirectionRTL
)

type RichLayout

type RichLayout struct {
	// Size is the overall bounding width and height of the laid-out rich text.
	Size core.Size
	// Lines holds per-line metrics and alignment offsets.
	Lines []RichLine
	// Placements holds every visible glyph and inline icon in reading order.
	Placements []RichPlacement
	// TotalUnits is the total number of revealable units (non-newline glyphs + icons).
	TotalUnits int
	// contains filtered or unexported fields
}

RichLayout is the laid-out geometry of a RichText.

func LayoutRich

func LayoutRich(font *Font, rt RichText, opts RichOptions) RichLayout

LayoutRich computes line wrapping, alignment, and per-glyph/per-icon placements for rt using bitmap font and opts.

Inline icons are measured and wrapped identically to glyphs using their resolved advance width, and aligned to each line's baseline.

func LayoutRichPlatform

func LayoutRichPlatform(d *core.Drawing, rt RichText, style PlatformStyle, opts RichOptions) RichLayout

LayoutRichPlatform lays out rt using platform text measurements from d, treating inline icons as glyphs aligned to the text baseline.

type RichLine

type RichLine struct {
	// Index is the zero-based line index.
	Index int
	// X is the aligned starting X offset of the line relative to origin.
	X float32
	// Y is the top Y coordinate of the line relative to origin.
	Y float32
	// Width is the measured advance width of the line in points.
	Width float32
	// Height is the total line height in points.
	Height float32
	// Baseline is the distance from Y down to the line's baseline in points.
	Baseline float32
}

RichLine summarizes one wrapped line of a RichLayout.

type RichLink struct {
	ID         string
	Start, End int
}

RichLink is a clickable link span in rich markup. Start and End are rune offsets in PlainText.

func ParseRichLinks(src string) []RichLink

ParseRichLinks returns the [link=id]...[/link] spans of src. It is ParseRich(src).Links, so Start and End are rune offsets into the PlainText ParseRich produces for the same markup: rich-style and link tags count zero, escaped brackets count once, icons and pauses count zero, and markup ParseRich keeps as literal text (unknown, mismatched or unclosed tags) counts as that text. A link containing another link is dropped along with the inner link because links cannot be nested.

type RichOptions

type RichOptions struct {
	// Options holds MaxWidth, Align, Scale, Alpha, LineSpacing, and Z.
	Options
	// Color is the default foreground color when a token has no [color=...] tag.
	// Zero means untinted for bitmap fonts, or the drawing's current fill color
	// for platform text.
	Color core.Color
	// Icons resolves [icon=name] tags. When nil or unresolved, icons are skipped.
	Icons IconResolver
	// BoldFont, ItalicFont, and BoldItalicFont are optional alternate bitmap fonts
	// used for [b], [i], and [b][i] spans. When nil, faux-bold or faux-italic
	// rendering is applied using the base font.
	BoldFont       *Font
	ItalicFont     *Font
	BoldItalicFont *Font
	// Elapsed is the animation time in seconds used when evaluating per-glyph
	// effects ([wave], [shake], or EffectCustom).
	Elapsed float32
	// Platform optionally supplies platform text rendering settings when drawing
	// via DrawRich with a nil bitmap Font.
	Platform *PlatformStyle
	// Direction selects the base direction for rich layout. DirectionAuto
	// resolves it from the first strong character in each line.
	Direction RichDirection
}

RichOptions configures layout and rendering of RichText.

Its zero value draws all tokens left-aligned at scale 1 and full opacity with no wrapping.

type RichPlacement

type RichPlacement struct {
	// Index is the zero-based revealable unit index used by Typewriter and
	// EvalGlyphTransform.
	Index int
	// Kind is TokenGlyph or TokenIcon.
	Kind RichTokenKind
	// Rune is the first character of Text when Kind == TokenGlyph.
	Rune rune
	// Text is what the placement draws when Kind == TokenGlyph. A platform layout, which the platform shapes, places a whole grapheme cluster in logical order (a letter with its marks, an emoji sequence); a bitmap layout, which draws one glyph per rune, places a single rune, so a cluster of several runes has several placements sharing one Index, and at a right-to-left level a paired bracket is already mirrored.
	Text string
	// Glyph is the bitmap glyph metrics when laid out with a bitmap Font.
	Glyph Glyph
	// Font is the resolved bitmap font for this glyph (base or Bold/Italic variant).
	Font *Font
	// Icon is the resolved inline icon when Kind == TokenIcon.
	Icon Icon
	// Style is the active RichStyle on this placement.
	Style RichStyle
	// Scale is the combined scale (baseScale * tokenScale).
	Scale float32
	// X and Y are the top-left position of the drawn glyph/icon rectangle, in points.
	X, Y float32
	// W and H are the drawn width and height of the glyph/icon rectangle, in points.
	W, H float32
	// BaselineY is the Y coordinate of this placement's line baseline, in points.
	BaselineY float32
	// Line is the zero-based line index containing this placement.
	Line int
	// FauxBold is true when Bold is active without a dedicated BoldFont/BoldItalicFont.
	FauxBold bool
	// FauxItalic is true when Italic is active without a dedicated ItalicFont/BoldItalicFont.
	FauxItalic bool
	// PlatformFont is set when laid out via LayoutRichPlatform.
	PlatformFont core.Font
	// contains filtered or unexported fields
}

RichPlacement is one laid-out visible glyph or inline icon in a RichLayout. Positions are relative to the layout's origin (0, 0).

type RichRun

type RichRun struct {
	Kind RichTokenKind
	// Text holds the run's runes when Kind == TokenGlyph.
	Text string
	// IconName, IconWidth, IconHeight are set when Kind == TokenIcon.
	IconName              string
	IconWidth, IconHeight float32
	// PauseSeconds is set when Kind == TokenPause.
	PauseSeconds float32
	// Style is the shared RichStyle for this run.
	Style RichStyle
}

RichRun groups contiguous glyphs sharing identical style into a string, or represents a single inline icon or pause token.

type RichStyle

type RichStyle struct {
	// Color is the token's foreground color; 0 means inherit the default color.
	Color core.Color
	// Scale multiplies the base text scale; 0 means 1.
	Scale float32
	// Bold requests bold rendering (BoldFont/BoldItalicFont, faux-bold, or
	// core.FontWeightBold on platform text).
	Bold bool
	// Italic requests italic rendering (ItalicFont/BoldItalicFont, faux-italic
	// skew, or core.Font.Italic on platform text).
	Italic bool
	// Effect configures a deterministic per-glyph animation effect.
	Effect GlyphEffect
	// Effects configures outline, drop shadow, underline, and strikethrough for this token.
	Effects TextEffects
}

RichStyle holds the active visual attributes of a parsed rich text token.

type RichText

type RichText struct {
	Tokens []RichToken
	// Links holds the [link=id]...[/link] spans in source order, with rune offsets into PlainText.
	Links []RichLink
}

RichText is a parsed rich text document consisting of styled tokens.

func ParseRich

func ParseRich(src string) RichText

ParseRich parses forgiving inline rich text markup into a RichText.

Supported tags:

  • [color=#RRGGBB] / [color=#RRGGBBAA] / [color=gold] ... [/color]
  • [scale=1.25] ... [/scale], [size=1.25] ... [/size]
  • [b] ... [/b], [i] ... [/i], [u] ... [/u], [s] ... [/s]
  • [outline=2 color=#000] ... [/outline]
  • [shadow=1,1 color=#0008] ... [/shadow] (optional blur=N)
  • [icon=coin] or [icon=coin w=16 h=16]
  • [wave amp=3 freq=4 speed=6] ... [/wave]
  • [shake amp=2 speed=30] ... [/shake]
  • [pause=0.2]
  • [link=codex.burn] ... [/link]
  • [[ escapes a literal '['

A link tag adds no text: its span is recorded in RichText.Links with rune offsets into PlainText, the same spans ParseRichLinks returns. Links cannot be nested, so a link that contains another link is dropped together with the inner link, while the text of both stays.

Any invalid, unknown, malformed, mismatched, or unclosed markup never errors or panics and falls back cleanly to plain text.

Example

ParseRich reads inline markup for colors, emphasis, icons and pauses; markup it cannot read stays as plain text instead of failing.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/text"
)

func main() {
	rt := text.ParseRich("You found [color=gold]50 coins[/color] [icon=coin]!")
	fmt.Println(rt.PlainText())
	kinds := map[text.RichTokenKind]string{text.TokenGlyph: "glyph", text.TokenIcon: "icon", text.TokenPause: "pause"}
	for _, run := range rt.Runs() {
		fmt.Printf("%s %q %q\n", kinds[run.Kind], run.Text, run.IconName)
	}
	fmt.Println(text.ParseRich("[colr=red]typo").PlainText())
}
Output:
You found 50 coins !
glyph "You found " ""
glyph "50 coins" ""
glyph " " ""
icon "" "coin"
glyph "!" ""
[colr=red]typo

func (RichText) Empty

func (rt RichText) Empty() bool

Empty reports whether rt has no tokens.

func (RichText) PlainText

func (rt RichText) PlainText() string

PlainText returns all text runes in rt with markup tags, icons, and pauses removed.

func (RichText) Runs

func (rt RichText) Runs() []RichRun

Runs groups contiguous glyph tokens with matching style into string runs, preserving inline icons and pauses in order.

type RichToken

type RichToken struct {
	Kind RichTokenKind
	// Rune is set when Kind == TokenGlyph.
	Rune rune
	// IconName is set when Kind == TokenIcon.
	IconName string
	// IconWidth and IconHeight override the resolved icon's intrinsic dimensions when > 0.
	IconWidth, IconHeight float32
	// PauseSeconds is the pause duration in seconds when Kind == TokenPause.
	PauseSeconds float32
	// Style holds the color, scale, bold, italic, and effect active on this token.
	Style RichStyle
}

RichToken is one parsed unit in a RichText document.

type RichTokenKind

type RichTokenKind uint8

RichTokenKind distinguishes text glyphs, inline icons, and typewriter pauses.

const (
	// TokenGlyph is a single Unicode rune with an active RichStyle.
	TokenGlyph RichTokenKind = iota
	// TokenIcon is an inline icon ([icon=name ...]) with an active RichStyle.
	TokenIcon
	// TokenPause is a zero-width typewriter pause ([pause=seconds]).
	TokenPause
)

type SDFFont

type SDFFont struct {
	// Face is the font face name.
	Face string
	// Size is the font's em size in atlas pixels: the size the atlas was generated at.
	Size float32
	// LineHeight is the distance between consecutive lines, in atlas pixels.
	LineHeight float32
	// Base is the distance from the top of a line to the baseline, in atlas pixels.
	Base float32
	// Field is how the atlas stores the distance.
	Field FieldType
	// DistanceRange is the width, in atlas pixels, of the band around each outline the field covers. With a DistanceRangeMiddle of 0, a field value of 0 is DistanceRange/2 pixels outside the outline, 0.5 on it and 1 DistanceRange/2 pixels inside.
	DistanceRange float32
	// DistanceRangeMiddle is how far, in atlas pixels, the middle of the field's band lies inside the outline: msdf-atlas-gen's distanceRangeMiddle, non-zero for an atlas generated with an asymmetric range (-apxrange or -aemrange). The outline is at the field value 0.5 - DistanceRangeMiddle/DistanceRange, and the field reaches DistanceRange/2 - DistanceRangeMiddle atlas pixels outside it.
	DistanceRangeMiddle float32
	// Glyphs maps each rune to its metrics and its rectangle in its page, all in atlas pixels.
	//
	// Measure, Layout, Draw and LayoutWorld read Size, LineHeight, Base, Glyphs and Kernings on every call, and a glyph's image is cached under its rectangle and the field's settings, so these fields can be changed between calls.
	Glyphs map[rune]Glyph
	// Kernings maps pairs of consecutive runes to their horizontal kerning adjustment, in atlas pixels.
	Kernings map[KerningPair]float32
	// CacheBytes bounds the memory of resolved glyph images kept between draws; 0 means 16 MiB. The least recently drawn glyph images go first.
	CacheBytes int
	// contains filtered or unexported fields
}

SDFFont is a signed-distance-field font: glyph metrics in atlas pixels and, for each texture page, the distance field those glyphs are drawn from.

Its glyphs stay sharp at any size, because a glyph is resolved from the field at the size it is drawn at rather than stretched from one bitmap. Draw and DrawWorld keep the glyphs they resolve in a cache bounded by CacheBytes, so an SDFFont is not safe for concurrent use: draw with it from one goroutine, as a canvas's Draw does.

func LoadSDFFont

func LoadSDFFont(data []byte, page func(id int, file string) (image.Image, error)) (*SDFFont, error)

LoadSDFFont parses a signed-distance-field font in any of the forms the common generators write:

  • msdf-atlas-gen's JSON (-json), whose glyphs are named by Unicode code point (-charset or the default, not -glyphset);
  • AngelCode BMFont in plain text, XML or JSON with a distanceField record, as msdf-bmfont-xml writes.

For each texture page, in ascending page ID order, page is called with the page ID and the file the font names for it (empty for msdf-atlas-gen's single atlas) and returns the page's decoded image, such as image/png's. LoadSDFFont reads the distance out of the images, so it does not keep them.

func LoadSDFFontImage

func LoadSDFFontImage(img image.Image, data []byte) (*SDFFont, error)

LoadSDFFontImage parses a single-page signed-distance-field font, as LoadSDFFont does, whose page is img. It returns an error if the font declares more than one page.

func (*SDFFont) AppendWorldQuads

func (f *SDFFont) AppendWorldQuads(dst []WorldQuad, cam *scene3d.Camera, t WorldText) []WorldQuad

AppendWorldQuads lays out t and appends one WorldQuad per visible glyph (plus drop-shadow quads when Options.Effects.Shadow is set) to dst for depth-tested GPU SDF rendering, returning the extended slice.

FacingFixed text with CullBackFace set and a non-nil cam is skipped when seen from behind, matching SDFFont.LayoutWorld. The existing SDFFont.DrawWorld remains available for 2D overlays.

func (*SDFFont) CachedGlyphs

func (f *SDFFont) CachedGlyphs() (count, bytes int)

CachedGlyphs returns how many resolved glyph images the font keeps and their size in bytes.

func (*SDFFont) ClearCache

func (f *SDFFont) ClearCache()

ClearCache drops every resolved glyph image the font keeps.

func (*SDFFont) Draw

func (f *SDFFont) Draw(d *core.Drawing, s string, x, y float32, opts SDFOptions)

Draw draws s at (x, y), the top left of its first line, into d, each glyph resolved from the distance field at the size it is drawn at, so it stays sharp at any Size and PixelScale.

The current transform of d is not known to Draw: under a scaling transform, set PixelScale to the device pixels a point then covers.

func (*SDFFont) DrawLayout

func (f *SDFFont) DrawLayout(d *core.Drawing, l WorldLayout)

DrawLayout draws world-space text that LayoutWorld projected into d.

func (*SDFFont) DrawWorld

func (f *SDFFont) DrawWorld(d *core.Drawing, cam *scene3d.Camera, viewport core.Bounds, t WorldText)

DrawWorld projects t through cam onto viewport, as LayoutWorld does, and draws it into d. To draw overlapping labels back to front, lay them out with LayoutWorld, sort them by Depth and draw them with DrawLayout instead.

Example
// Load an msdf-atlas-gen atlas (its JSON and its decoded PNG) once.
font, err := text.LoadSDFFontImage(testAtlas(false), sdfAtlasJSON)
if err != nil {
	panic(err)
}
cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 2, Z: 8}, math3d.DegToRad(60), 16.0/9, 0.1, 100)
cam.LookAt(math3d.Vec3{}, math3d.Vec3Up())
viewport := core.Bounds{Size: core.Size{Width: 640, Height: 360}}

// In a core.Canvas's Draw: a damage number over an enemy's head, and a sign on a wall.
d := &core.Drawing{}
font.DrawWorld(d, cam, viewport, text.WorldText{
	Text: "IO", Pos: math3d.Vec3{Y: 1.5}, Size: 0.5, AnchorX: 0.5, AnchorY: 1,
	Options: text.SDFOptions{Color: core.RGB(0xffd23f), Outline: 0.08, OutlineColor: core.RGB(0x000000), PixelScale: 2},
})
font.DrawWorld(d, cam, viewport, text.WorldText{
	Text: "OI", Pos: math3d.Vec3{X: 2, Y: 1}, Size: 0.4, Facing: text.FacingFixed,
	Rot: math3d.QuatFromAxisAngle(math3d.Vec3Up(), -math.Pi/4), CullBackFace: true,
})
fmt.Println(len(glyphImages(d)), "glyphs drawn")
Output:
4 glyphs drawn

func (*SDFFont) Kerning

func (f *SDFFont) Kerning(first, second rune) float32

Kerning returns the horizontal kerning adjustment, in atlas pixels, when second follows first, or 0 if no kerning pair is defined.

func (*SDFFont) Layout

func (f *SDFFont) Layout(s string, x, y float32, opts SDFOptions) []GlyphPlacement

Layout computes the placements, in points, of all visible glyphs in s starting at (x, y), the top left of its first line.

func (*SDFFont) LayoutWorld

func (f *SDFFont) LayoutWorld(cam *scene3d.Camera, viewport core.Bounds, t WorldText) (WorldLayout, bool)

LayoutWorld projects t through cam onto viewport, the camera's view in the drawing's points (as render3d.ProjectSegment's), and reports whether any of it is visible.

FacingBillboard text is hidden as a whole when its anchor is outside the camera's near and far planes. FacingFixed text is hidden glyph by glyph: a glyph reaching behind the near plane or past the far plane is left out. Glyphs wholly outside the viewport are left out of both.

func (*SDFFont) Measure

func (f *SDFFont) Measure(s string, opts SDFOptions) core.Size

Measure returns the bounding width and height, in points, of s laid out with opts.

func (*SDFFont) MissingRunes

func (f *SDFFont) MissingRunes(s string) []rune

MissingRunes returns the sorted, deduplicated non-control runes in s that f has no glyph for. Control characters (such as newlines and tabs) are ignored.

func (*SDFFont) PageCount

func (f *SDFFont) PageCount() int

PageCount returns the number of distance-field texture pages in f.

func (*SDFFont) PageImage

func (f *SDFFont) PageImage(page int) *image.NRGBA

PageImage returns an uncompressed straight-alpha *image.NRGBA copy of page's distance field, ready to upload to a linear (SRGB: false) GPU texture. Single-channel fields (FieldSDF, FieldPSDF) replicate the distance across RGB with alpha 255; three-channel fields (FieldMSDF) store RGB with alpha 255; four-channel fields (FieldMTSDF) preserve all four RGBA channels verbatim. It returns nil when f is nil or has no such page.

func (*SDFFont) PageSize

func (f *SDFFont) PageSize(page int) (w, h int, ok bool)

PageSize returns the pixel dimensions of the distance-field atlas page with ID page, or (0, 0, false) when f is nil or has no such page.

type SDFOptions

type SDFOptions struct {
	// Effects configures outline (in points, used when Outline and OutlineColor below are both 0), drop shadow, underline, and strikethrough.
	Effects TextEffects
	// Size is the em size the text is drawn at, in points; 0 means the font's Size. DrawWorld ignores it and takes the size from WorldText.
	Size float32
	// MaxWidth wraps lines to fit within MaxWidth when > 0 and defines the alignment box [x, x+MaxWidth] for AlignCenter and AlignRight, as Options.MaxWidth does. It is in points for Draw and in world units for DrawWorld.
	MaxWidth float32
	// Wrap selects how lines break when MaxWidth > 0 (WrapDefault uses WrapWordSmart).
	Wrap Wrap
	// LineBreak controls CJK prohibited-character (kinsoku) strictness (LineBreakStrict or LineBreakNormal).
	LineBreak LineBreakStyle
	// Overrun controls how text exceeding MaxWidth or MaxLines is clipped or ellipsized.
	Overrun Overrun
	// MaxLines caps the number of laid-out lines when > 0.
	MaxLines int
	// Direction controls bidirectional visual ordering for laid-out lines.
	Direction RichDirection
	// Align is the horizontal alignment of each line.
	Align Align
	// LineSpacing is extra vertical space between lines, in ems.
	LineSpacing float32
	// Color is the text's fill color; 0 means opaque white.
	Color core.Color
	// Alpha is the text's opacity from 0 to 1; 0 means 1, and a negative alpha draws nothing. Changing it, as a fading damage number does, reuses the glyphs already resolved.
	Alpha float32
	// Outline is the width of an outline around each glyph, in ems; 0 draws none. It cannot reach past the font's distance field, DistanceRange/2 - DistanceRangeMiddle atlas pixels outside the outline, and stops there.
	Outline float32
	// OutlineColor is the outline's color; 0 draws no outline.
	OutlineColor core.Color
	// PixelScale is the device pixels a point covers, so glyphs are resolved at the screen's density; 0 means 1.
	PixelScale float32
}

SDFOptions configures how an SDFFont lays out and draws text.

Its zero value draws opaque white, left-aligned, at the font's own size, with no outline or wrapping.

type TextEffects

type TextEffects struct {
	// Outline is the width of an outline around each glyph, in points; 0 draws none.
	Outline float32
	// OutlineColor is the outline's color; 0 draws no outline.
	OutlineColor core.Color
	// Shadow is the offset of a drop shadow from the text, in points.
	Shadow core.Point
	// ShadowColor is the drop shadow's color; 0 draws no shadow.
	ShadowColor core.Color
	// ShadowBlur is the drop shadow's blur radius, in points (platform text only; bitmap shadows are hard).
	ShadowBlur float32
	// Underline draws a line under the text.
	Underline bool
	// Strike draws a line through the text.
	Strike bool
}

TextEffects describes style effects shared by bitmap, SDF, platform and rich text paths.

func (TextEffects) IsZero

func (e TextEffects) IsZero() bool

IsZero reports whether e enables no visual text effects.

type Typewriter

type Typewriter struct {
	// CharsPerSecond is the reveal rate in units (glyphs or inline icons) per second.
	CharsPerSecond float32
	// PunctuationPause optionally defines step multipliers after punctuation runes
	// (e.g., '.' -> 4.0 waits 3 extra character steps after revealing '.').
	// Use DefaultPunctuationPause() for common dialogue pacing, or leave nil for
	// uniform character timing.
	PunctuationPause map[rune]float32
	// OnReveal is called once as each unit becomes visible. For inline icons, r is 0.
	OnReveal func(glyphIndex int, r rune)
	// OnComplete is called strictly once when all units have been revealed.
	OnComplete func()
	// contains filtered or unexported fields
}

Typewriter reveals a RichText progressively at a deterministic rate while tracking elapsed animation time for per-glyph effects.

Example

A Typewriter reveals text a character at a time, pausing at punctuation and markup pauses, as dialogue boxes do; Skip shows the rest at once.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/text"
)

func main() {
	tw := text.NewTypewriterString("Hi.[pause=0.5] Bye", 10)
	for range 4 {
		tw.Update(0.25)
		fmt.Println(tw.VisibleCount(), "of", tw.TotalCount())
	}
	tw.Skip()
	fmt.Println(tw.Done())
}
Output:
2 of 7
3 of 7
3 of 7
5 of 7
true

func NewTypewriter

func NewTypewriter(rt RichText, charsPerSecond float32) *Typewriter

NewTypewriter creates a Typewriter revealing rt at charsPerSecond units per second.

func NewTypewriterString

func NewTypewriterString(markup string, charsPerSecond float32) *Typewriter

NewTypewriterString parses markup via ParseRich and creates a Typewriter revealing it at charsPerSecond units per second.

func (*Typewriter) Done

func (tw *Typewriter) Done() bool

Done reports whether all units have been revealed.

func (*Typewriter) Draw

func (tw *Typewriter) Draw(d *core.Drawing, font *Font, pos core.Point, opts RichOptions)

Draw draws only the currently revealed glyphs and inline icons at pos into d, keeping the full wrapped layout stable while evaluating per-glyph effects at the typewriter's Elapsed time.

When font is nil and opts.Platform is set, platform-text rendering is used.

func (*Typewriter) DrawPlatform

func (tw *Typewriter) DrawPlatform(d *core.Drawing, pos core.Point, style PlatformStyle, opts RichOptions)

DrawPlatform draws only the currently revealed glyphs and inline icons at pos into d using platform text rendering, keeping the full wrapped layout stable.

func (*Typewriter) Elapsed

func (tw *Typewriter) Elapsed() float32

Elapsed returns the total elapsed time in seconds accumulated via Update.

func (*Typewriter) Progress

func (tw *Typewriter) Progress() float32

Progress returns the reveal fraction in [0, 1]. For empty text it returns 1.

func (*Typewriter) Reset

func (tw *Typewriter) Reset(rt RichText)

Reset replaces the typewriter's RichText and resets reveal progress, timers, elapsed time, and completion state while preserving speed and callbacks.

func (*Typewriter) RichText

func (tw *Typewriter) RichText() RichText

RichText returns the Typewriter's parsed RichText.

func (*Typewriter) Skip

func (tw *Typewriter) Skip()

Skip immediately reveals all remaining units and invokes OnComplete once if it has not already fired.

func (*Typewriter) TotalCount

func (tw *Typewriter) TotalCount() int

TotalCount returns the total number of revealable units (non-newline glyphs and icons).

func (*Typewriter) Update

func (tw *Typewriter) Update(dt float32)

Update advances the typewriter deterministically by dt seconds.

Elapsed time continues advancing after the text is fully revealed so active per-glyph effects ([wave], [shake]) keep animating. OnReveal fires once per newly revealed unit and OnComplete fires strictly once when fully revealed.

func (*Typewriter) VisibleCount

func (tw *Typewriter) VisibleCount() int

VisibleCount returns the number of currently revealed units (glyphs and icons).

type WorldGlyph

type WorldGlyph struct {
	// Glyph is the font's glyph.
	Glyph Glyph
	// Transform maps the glyph's atlas rectangle, in atlas pixels from its top left, into the drawing's points. For FacingFixed text it is the affine transform closest to the perspective at the glyph's center, which, for glyphs small on the screen, the perspective across one glyph cannot tell apart.
	Transform math2d.Affine
}

WorldGlyph is one glyph of world-space text projected onto the screen.

type WorldLayout

type WorldLayout struct {
	// Depth is the anchor's depth from the camera's near plane (0) to its far plane (1), for drawing labels back to front: sort by Depth, highest first. For FacingFixed text whose anchor is behind the camera or past the far plane, it is the mean depth of the visible glyphs' centers.
	Depth float32
	// Glyphs are the glyphs that reach the viewport, in the text's order.
	Glyphs []WorldGlyph
	// Options are the WorldText's options the glyphs draw with.
	Options SDFOptions
	// contains filtered or unexported fields
}

WorldLayout is world-space text projected onto the screen by SDFFont.LayoutWorld, ready for SDFFont.DrawLayout.

type WorldQuad

type WorldQuad struct {
	// Center is the text anchor's world-space position.
	Center math3d.Vec3
	// Size is the glyph quad's width and height: in world units when FixedSize is false,
	// or in screen points when FixedSize is true (from WorldText.ScreenSize).
	Size math2d.Vec2
	// Pivot is the quad-relative pivot placing this glyph relative to Center:
	// quadCenter = Center - right*(Size.X*Pivot.X) - up*(Size.Y*Pivot.Y).
	Pivot math2d.Vec2
	// UVRect is the normalized [u0, v0, u1, v1] rectangle in the font's SDF atlas page (top-left origin).
	UVRect [4]float32
	// Page is the SDF atlas texture page index.
	Page int
	// Facing selects billboard or fixed-plane orientation.
	Facing Facing
	// Rot is the normalized world orientation when Facing is FacingFixed.
	Rot math3d.Quat
	// Color is the glyph fill color (with Options.Alpha applied).
	Color core.Color
	// OutlineColor is the outline color (with Options.Alpha applied), or 0 when no outline is drawn.
	OutlineColor core.Color
	// Outline is the outline width in normalized distance-field units (atlas outline pixels / DistanceRange),
	// clamped to the font's outer distance band.
	Outline float32
	// FixedSize is true when the text uses WorldText.ScreenSize (constant screen size in points).
	FixedSize bool
	// CullBackFace is true when FacingFixed text should cull back faces.
	CullBackFace bool
}

WorldQuad is one SDF glyph quad in 3D space emitted by SDFFont.AppendWorldQuads for depth-tested GPU SDF text batching.

type WorldText

type WorldText struct {
	// Text is the text, with "\n" between lines.
	Text string
	// Pos is the anchor's position in the world.
	Pos math3d.Vec3
	// Facing is how the text turns.
	Facing Facing
	// Rot orients FacingFixed text: its lines run along Rot's +X, its glyphs stand along +Y, and it reads from the +Z side. The zero Quat means the identity, text in the XY plane read from +Z.
	Rot math3d.Quat
	// Size is the em size in world units, so the text shrinks with distance under a perspective camera.
	Size float32
	// ScreenSize, when > 0, makes FacingBillboard text keep an em of ScreenSize points at any distance, in place of Size; Options.MaxWidth is then in points.
	ScreenSize float32
	// AnchorX and AnchorY are the point of the text's box that sits at Pos, as fractions of its width and height from its top left: (0, 0) is the top left, (0.5, 0.5) the center and (0.5, 1) the bottom middle. The box is [0, MaxWidth] wide when Options.MaxWidth > 0, else the widest line's, placed as Options.Align places a line at x.
	AnchorX, AnchorY float32
	// CullBackFace draws nothing of FacingFixed text seen from behind.
	CullBackFace bool
	// Options sets the color, outline, alignment, wrapping, opacity and pixel density; its Size is ignored and its MaxWidth is in world units.
	Options SDFOptions
}

WorldText is text placed in a 3D world, drawn by SDFFont.DrawWorld.

type Wrap

type Wrap uint8

Wrap controls how text breaks into lines when MaxWidth > 0.

const (
	// WrapDefault uses WrapWordSmart in pkg/text layouts when MaxWidth > 0, and
	// preserves single-line behavior on gameui Label and Button widgets unless a
	// wrapping mode is explicitly selected.
	WrapDefault Wrap = iota
	// WrapNone disables automatic line wrapping even when MaxWidth > 0; only explicit
	// line breaks split lines, and Overrun applies to lines exceeding MaxWidth.
	WrapNone
	// WrapWord wraps at Unicode UAX #14 line break opportunities (with CJK kinsoku
	// and Southeast Asian syllable breaking) without splitting oversized words.
	WrapWord
	// WrapWordSmart wraps at Unicode UAX #14 line break opportunities and falls back
	// to extended grapheme cluster breaking when a single unbreakable segment exceeds MaxWidth.
	WrapWordSmart
	// WrapArbitrary allows breaking at any extended grapheme cluster boundary to fit MaxWidth.
	WrapArbitrary
)

func ParseWrap

func ParseWrap(s string) (Wrap, bool)

ParseWrap parses a canonical wrap mode name (""/"none", "word", "word_smart", or "arbitrary").

func (Wrap) String

func (w Wrap) String() string

String returns the canonical snake_case name of w ("none", "word", "word_smart", or "arbitrary").

Jump to

Keyboard shortcuts

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