Diese Seite ist noch nicht auf Deutsch übersetzt und wird daher auf Englisch angezeigt.
2D-Systemel10n
game/l10n provides game localization built on NSGo's core package and the Go standard library: versioned YAML and JSON string tables with BCP-47 fallback and CLDR plurals, script-aware FontSet[F], RTL visual reordering and HUD mirroring, and per-language asset catalogs with selective group reloads.
import "github.com/nsgo-dev/game/pkg/l10n"
String tables, interpolation, and CLDR plurals
Load per-locale versioned YAML string tables with Catalog.LoadYAML (or flat, nested, or CLDR plural JSON tables with Catalog.LoadJSON) into a Catalog with a fallback locale, then wrap it in a reactive Localizer bound to a *core.Scope:
# yaml-language-server: $schema=https://game.nsgo.dev/schemas/l10n.v1.json
version: 1
locale: en
strings:
hud.score: 'Score: {score}'
menu.play: Play
plurals:
coins:
zero: No coins
one: '{count} coin'
other: '{count} coins'
| Field | Meaning |
|---|---|
version |
Required; must be 1 (StringTableVersion). |
locale |
Required; normalized BCP-47 locale tag (such as en or zh-Hans). |
strings |
Optional map of message key to localized string template. |
plurals |
Optional map of message key to CLDR plural categories (zero, one, two, few, many, other). |
cat := l10n.NewCatalog("en")
_ = cat.LoadYAML(enYAML)
_ = cat.LoadYAML(zhHansYAML)
loc := l10n.NewLocalizer(cx, cat)
loc.SetLocale("zh-Hans") // or omit to follow the system locale
title := loc.T("menu.play")
score := loc.T("hud.score", l10n.Param("score", 420))
coins := loc.Plural("coins", 3)
_, _, _ = title, score, coins
YAML decoding is strict: unknown fields, invalid plural categories, duplicate keys, keys defined in both strings and plurals, empty keys or plural maps, null values, trailing YAML documents, YAML anchors/aliases/merge keys, missing or unsupported versions (or non-decimal forms like 0x1), and non-canonical locales (such as zh_hans instead of zh-Hans) are refused without modifying the catalog. EncodeYAML and Catalog.MarshalYAML emit deterministic 2-space YAML prefixed with # yaml-language-server: $schema=https://game.nsgo.dev/schemas/l10n.v1.json (SchemaComment) and sorted keys, so EncodeYAML(ParseYAML(b)) == b byte for byte. ParseYAML, ValidateStringTable, ApplyStringTable, and Catalog.StringTable operate directly on *StringTable values for tooling such as the editor's Localization panel.
Existing JSON string tables continue to load with Catalog.LoadJSON:
cat := l10n.NewCatalog("en")
_ = cat.LoadJSON("en", []byte(`{
"menu": {"play": "Play"},
"hud": {"score": "Score: {score}"},
"coins": {"zero": "No coins", "one": "{count} coin", "other": "{count} coins"}
}`))
_ = cat.LoadJSON("zh-Hans", []byte(`{
"menu": {"play": "开始游戏"},
"hud": {"score": "得分:{score}"},
"coins": {"other": "{count} 枚金币"}
}`))
Lookups walk the normalized BCP-47 fallback chain (for example zh-Hans-CN -> zh-Hans -> zh -> fallback locale) and return the key itself if missing everywhere. You can also populate entries programmatically via cat.Set and cat.SetPlural.
Script-aware FontSet[F]
Pair mixed-script text with per-script or per-locale fonts (any font type F, such as *text.BitmapFont or core.Font):
fonts := l10n.NewFontSet(latinFont)
fonts.SetScript(l10n.ScriptCJK, cjkFont)
fonts.SetScript(l10n.ScriptArabic, arabicFont)
fonts.SetLocale("ja", jpFont)
// Split mixed strings into contiguous runs, each paired with its resolved font:
runs := fonts.RunsForText(loc.Locale(), "Score: 120 得分")
for _, run := range runs {
drawRun(run.Text, run.Font)
}
Inspect scripts directly with RuneScript, DetectScript, SegmentByScript, and LocaleScript.
RTL visual ordering and layout mirroring
Query text direction from a locale (LocaleDirection), scope (EnvDirection), or string (TextDirection). For custom canvas text renderers that draw glyphs left-to-right, convert logical strings to visual order with VisualOrder (or loc.Visual(s)):
dir := loc.Direction()
visual := loc.Visual(loc.T("hud.greeting"))
aligned := l10n.LayoutAlignment("start", dir) // "left" in LTR, "right" in RTL
x := l10n.MirrorX(16, iconW, screenW, dir)
_, _, _ = visual, aligned, x
Per-language asset catalogs
Manage localized voiceovers, textures, or title banners with AssetCatalog, discovered automatically from an io/fs.FS (locales/<locale>/<name>, <name>.<locale>.<ext>, or <name>_<locale>.<ext>) or loaded from a YAML asset manifest:
assets, err := l10n.DiscoverFS(embedFS, "en")
if err != nil {
return err
}
assets.RegisterGroup("voice", "voice/intro.wav", "voice/boss.wav")
// Reload only asset groups whose resolved paths actually change on language switch:
stop := assets.OnReload(func(groups []string, locale string) {
reloadAssetGroups(groups, locale)
})
defer stop()
assets.SetLocale("ja")
resolved, ok := assets.Resolve("voice/intro.wav", assets.Locale())
_, _ = resolved, ok
// Audit missing variants in tests or CI:
for _, rep := range assets.CheckMissing("ja", "zh-Hans", "ar") {
if !rep.Complete() {
log.Printf("%s missing %v (%.0f%%)", rep.Locale, rep.Missing, rep.Coverage*100)
}
}
Use assets.WatchLocale(cx, localeSignal, reloadFn) to connect locale changes directly to a reactive core.Signal[string].
Asset manifests
An asset manifest is a versioned YAML file that lists each logical asset's per-locale paths and the groups to reload on a language switch:
version: 1
base_locale: en
assets:
voice/intro.wav:
en: locales/en/voice/intro.wav
ja: locales/ja/voice/intro.wav
zh-Hans: locales/zh-Hans/voice/intro.wav
groups:
voice:
- voice/intro.wav
| Field | Meaning |
|---|---|
version |
Required; must be 1. |
base_locale |
Optional fallback locale; replaces the catalog's base locale when set. |
assets |
Logical asset name to a map of locale to path. Each asset has at least one variant and no empty path. |
groups |
Group name to the asset names it reloads, without duplicates. A group may name assets listed elsewhere, such as ones found by DiscoverFS. |
Load one into a catalog with LoadAssetManifestYAML, which merges it over what the catalog already holds, and write a catalog back with MarshalAssetManifestYAML:
if err := assets.LoadAssetManifestYAML(data); err != nil {
return err
}
out, err := assets.MarshalAssetManifestYAML()
Decoding is strict: an unknown field, a duplicate key, a second YAML document, a missing or unsupported version or one not written as 1 (such as 1.0 or 0x1), YAML anchors, aliases and << merge keys, an unclean asset name such as ./ui/a.png, or a locale that is not a normalized BCP-47 tag such as zh_hans (write zh-Hans) is refused with an error that names it, and nothing is merged. Output is deterministic: fields in schema order, keys sorted, group members sorted and no timestamps, so a manifest that was saved this way loads and saves back byte for byte. Saving writes this canonical form rather than the input's text, so the first save of a hand-written manifest drops comments and rewrites flow style, quoting, ordering and empty assets or groups entries; every save after that leaves the file unchanged. ParseAssetManifest, ValidateAssetManifest, EncodeAssetManifest, ApplyAssetManifest and AssetCatalog.AssetManifest work on the AssetManifest value directly for tools that edit manifests.