importsettings

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: 16 Imported by: 1 module, 0 packages

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 importsettings is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package importsettings reads and writes import settings sidecars: a small YAML file beside an image, a sound, a font or a model, named after it with ".import.yaml" appended (Path), that says how game assets imports it.

An image's sidecar holds its texture compression format, mipmaps, sRGB and sampling filter, which a texture target encodes it with, and the grid an atlas target slices a sprite sheet into frames along. A sound's sidecar holds its output format, sample rate, channels, loudness, bitrate and loop points, which an audio target converts it with. A font's sidecar holds the size, characters and padding a font target bakes it into a bitmap font with, and a model's the scale and whether to keep animations that a model target packs it into one GLB file with. A setting in the sidecar overrides the target's setting in game.yaml, so a person edits one asset's import by editing the file beside it, and game assets rebuilds the targets that read the asset when its sidecar changes. The single-file commands game tex and game audio read the sidecar beside their input too, under the flags given on the command line.

Any asset's sidecar may also hold a credit section: the asset's author, its license as an SPDX license expression (ValidateLicense), where it was obtained, and a notice the license requires to be shipped with it. Package credits lists these in the credits file game release writes beside the release's packages.

Parse decodes a version 1 sidecar and runs Validate, refusing unknown fields, other versions, a sidecar with no section or with more than one of image, audio, font and model, values out of range, and a credit without an author or with a license that is not an SPDX license expression. Encode validates a File and writes deterministic 2-space YAML in a fixed key order, after a first line that points a YAML language server at SchemaURL, which Parse reads back unchanged.

Index

Examples

Constants

View Source
const AssetSourceCurrentVersion = 2

AssetSourceCurrentVersion is the newest YAML schema version of generated asset source sidecars (*.source.yaml) (2), validating generator kind against the six known media families and requiring clean project-relative paths in files.

View Source
const AssetSourceSchemaComment = "# yaml-language-server: $schema=" + AssetSourceSchemaURL

AssetSourceSchemaComment is the first line EncodeAssetSource writes for version 1 sidecars: a YAML comment pointing a YAML language server at AssetSourceSchemaURL. ParseAssetSource ignores it like any other comment.

View Source
const AssetSourceSchemaCommentV2 = "# yaml-language-server: $schema=" + AssetSourceSchemaURLV2

AssetSourceSchemaCommentV2 is the first line EncodeAssetSource writes for version 2 sidecars, pointing a YAML language server at AssetSourceSchemaURLV2.

View Source
const AssetSourceSchemaURL = "https://nsgo.games/schemas/source.v1.json"

AssetSourceSchemaURL is where the JSON Schema of version 1 asset source sidecars is published. EncodeAssetSource names it in a yaml-language-server comment on the first line of version 1 files so editors and AI tools validate and complete source files as they are written.

View Source
const AssetSourceSchemaURLV2 = "https://nsgo.games/schemas/source.v2.json"

AssetSourceSchemaURLV2 is where the JSON Schema of version 2 asset source sidecars is published.

View Source
const AssetSourceSuffix = ".source.yaml"

AssetSourceSuffix is appended to a generated asset's file name to name its provenance and license sidecar, such as slime_frost.png.source.yaml beside slime_frost.png.

View Source
const AssetSourceVersion = 1

AssetSourceVersion is the oldest YAML schema version of generated asset source sidecars (*.source.yaml) that this package reads and writes (1).

View Source
const CurrentVersion = 2

CurrentVersion is the newest sidecar schema version this package reads and writes. Version 2 adds the optional plugin section for editor plugin asset importers.

View Source
const DefaultCollisionMaxVertices = 8

DefaultCollisionMaxVertices is the default maximum vertex count per baked convex collision polygon, matching physics.MaxPolygonVertices.

View Source
const FilterKey = "game.filter"

FilterKey is the key of a KTX2 texture's key/value data that game assets and game tex write Image.Filter under and render3d.LoadKTX2 reads.

View Source
const MaxCollisionVertices = 8

MaxCollisionVertices is the maximum vertex count of a baked convex collision polygon, matching physics.MaxPolygonVertices.

View Source
const MaxImageSize = 16384

MaxImageSize is the largest Image.MaxSize a sidecar may set.

View Source
const MaxSliceCells = 65536

MaxSliceCells is the maximum number of cell rectangles Slice.Cells will materialize for one sprite sheet to prevent excessive memory allocation.

View Source
const MinCollisionVertices = 3

MinCollisionVertices is the minimum vertex count of a valid convex polygon.

View Source
const MinVersion = 1

MinVersion is the oldest sidecar schema version this package reads and writes. Version 1 sidecars hold image, audio, font, model, and credit sections and encode unchanged.

View Source
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL

SchemaComment is the first line Encode writes for version 1 sidecars: a YAML comment that points a YAML language server at SchemaURL. Parse ignores it like any other comment.

View Source
const SchemaCommentV2 = "# yaml-language-server: $schema=" + SchemaURLV2

SchemaCommentV2 is the first line Encode writes for version 2 sidecars: a YAML comment that points a YAML language server at SchemaURLV2.

View Source
const SchemaURL = "https://nsgo.games/schemas/import.v1.json"

SchemaURL is where the JSON Schema of version 1 sidecars is published. Encode names it in a yaml-language-server comment on a version 1 sidecar's first line, so editors that run the YAML language server validate and complete the file as it is written.

View Source
const SchemaURLV2 = "https://nsgo.games/schemas/import.v2.json"

SchemaURLV2 is where the JSON Schema of version 2 sidecars (adding the plugin section) is published.

View Source
const Suffix = ".import.yaml"

Suffix is appended to an asset's file name to name its sidecar, such as hero.png.import.yaml beside hero.png.

Variables

View Source
var CollisionModes = []string{"alpha", "box", "ellipse", "polygon", "none"}

CollisionModes are the collision generation modes an image's sidecar may name: "alpha" traces the frame's alpha channel into convex polygons, "box" fits a tight axis-aligned box, "ellipse" fits an inscribed convex polygon, "polygon" uses explicit vertex coordinates, and "none" disables collision.

View Source
var Filters = []string{"linear", "nearest"}

Filters are the sampling filters an image's sidecar may name: "linear" blends neighboring texels when the image is scaled, "nearest" keeps each texel sharp, as pixel art wants.

Functions

func AssetSourcePath

func AssetSourcePath(asset string) string

AssetSourcePath returns the slash-separated path of the source sidecar of the asset at the slash-separated path asset.

func Encode

func Encode(f *File) ([]byte, error)

Encode validates f and writes it as deterministic 2-space YAML, starting with SchemaCommentFor(f.Version), that Parse reads back unchanged.

Example

Encode writes a sound's sidecar in the canonical form, with the schema comment editors read.

package main

import (
	"fmt"

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

func main() {
	data, err := importsettings.Encode(&importsettings.File{
		Version: importsettings.MinVersion,
		Audio:   &importsettings.Audio{Rate: 22050, Loop: &importsettings.Loop{Start: 4410}},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Print(string(data))
}
Output:
# yaml-language-server: $schema=https://nsgo.games/schemas/import.v1.json
version: 1
audio:
  rate: 22050
  loop:
    start: 4410

func EncodeAssetSource

func EncodeAssetSource(s *AssetSource) ([]byte, error)

EncodeAssetSource validates s and writes deterministic 2-space YAML prefixed with the schema comment for s.Version.

func IsAssetSource

func IsAssetSource(name string) bool

IsAssetSource reports whether the file name or path name is a generated asset source sidecar (*.source.yaml), so asset scans can skip it.

func IsSidecar

func IsSidecar(name string) bool

IsSidecar reports whether the file name or path name is a sidecar, so a scan for assets can skip it.

func IsUnknownLicense

func IsUnknownLicense(license string) bool

IsUnknownLicense reports whether license is empty or explicitly marks the license as unknown/unasserted (case-insensitive: "", "unknown", "none", "noassertion", "tbd", "unspecified"). A generated asset whose source sidecar has an unknown license blocks release builds.

func Path

func Path(asset string) string

Path returns the slash-separated path of the sidecar of the asset at the slash-separated path asset.

func SchemaCommentFor

func SchemaCommentFor(version int) string

SchemaCommentFor returns the first line Encode writes for a sidecar of version: SchemaComment for version 1 and SchemaCommentV2 for version 2.

func SplitImporter

func SplitImporter(importer string) (plugin, id string, ok bool)

SplitImporter splits an importer identifier of the form "<plugin>.<id>" into its plugin name and importer ID. It reports false when importer is empty, contains spaces, control characters, path separators, or "..", has no separating dot, or leaves either side empty or dot-edged.

func ValidAssetSourceKind

func ValidAssetSourceKind(kind string) bool

ValidAssetSourceKind reports whether kind is one of the six generator families recognized in version 2 source sidecars.

func ValidateAssetSource

func ValidateAssetSource(s *AssetSource) error

ValidateAssetSource checks s against its generated asset source schema version (AssetSourceVersion=1 or AssetSourceCurrentVersion=2). Unknown or empty License values are accepted so unresolved generated assets can be represented on disk and blocked by release/credits checks.

func ValidateLicense

func ValidateLicense(expr string) error

ValidateLicense checks that expr is an SPDX license expression (SPDX specification 2.3, annex D): license identifiers such as CC-BY-4.0, each optionally followed by "+" for "or any later version" and by WITH and an exception identifier, joined by AND and OR, which are upper case, and grouped by parentheses. A license with no SPDX identifier is written LicenseRef- followed by letters, digits, dots and hyphens, optionally after DocumentRef-name: as SPDX allows. NONE and NOASSERTION are refused, since a credit names the license an asset is used under. Identifiers are checked for their form, not looked up in the SPDX license list, so a new license needs no update of this package.

Example

ValidateLicense checks the form of an SPDX license expression.

package main

import (
	"fmt"

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

func main() {
	fmt.Println(importsettings.ValidateLicense("MIT OR Apache-2.0"))
	fmt.Println(importsettings.ValidateLicense("CC BY 4.0"))
}
Output:
<nil>
license "CC BY 4.0": unexpected "BY"

Types

type AssetSource

type AssetSource struct {
	// Version is the schema version, from AssetSourceVersion (1) to AssetSourceCurrentVersion (2).
	Version int `yaml:"version" schema:"required"`
	// Kind identifies the generated media family ("images", "sound", "textures", "models", "animation", or "tiles"). Empty preserves version-1 sidecars.
	Kind string `yaml:"kind,omitempty" schema:"enum=images|sound|textures|models|animation|tiles"`
	// Files lists the project-relative generated files covered by this provenance record (including secondary files such as normal/roughness maps, material drafts, atlases, or tilesets).
	Files []string `yaml:"files,omitempty"`
	// Generator is the MCP generator server name that produced the asset, such as "pixel-gen" or "sfx-gen".
	Generator string `yaml:"generator" schema:"required,minLength=1"`
	// Model is the generator model identifier reported by the server, such as "pixflux-1".
	Model string `yaml:"model,omitempty"`
	// Prompt is the text prompt sent to the generator.
	Prompt string `yaml:"prompt" schema:"required,minLength=1"`
	// Seed is the random seed that produced this candidate, when reported by the generator.
	Seed *int64 `yaml:"seed,omitempty"`
	// References lists the project-relative asset or brief paths passed to the generator as references (for example "art/characters/slime.png", "brief.yaml#art").
	References []string `yaml:"references,omitempty"`
	// License names the license under which the generated asset is used (for example "pixellab-commercial-1.2" or "CC0-1.0"); an empty or "unknown" license blocks release builds until resolved.
	License string `yaml:"license,omitempty"`
	// CommercialUse records whether the asset's license permits commercial use.
	CommercialUse bool `yaml:"commercialUse"`
	// ApprovedBy names the person who picked and approved the generated candidate.
	ApprovedBy string `yaml:"approvedBy,omitempty"`
	// SHA256 is the lowercase hex SHA-256 digest of the picked asset bytes, so tools can tell whether the file in the project is still the generated one.
	SHA256 string `yaml:"sha256,omitempty"`
	// Parameters records the canonical generation arguments sent to the generator other than the prompt and references (for example "count", "kind", "model", "seed", "vary_seed", "refine"), written as a sorted map.
	Parameters map[string]string `yaml:"parameters,omitempty"`
	// DerivedFrom records the candidate a Vary this or Refine started from.
	DerivedFrom *AssetSourceParent `yaml:"derivedFrom,omitempty"`
	// ReferenceHashes maps each entry of References that named a readable project file to the lowercase hex SHA-256 of that file's bytes when the request was sent.
	ReferenceHashes map[string]string `yaml:"referenceHashes,omitempty"`
}

AssetSource records the provenance, generation parameters, license, and approval of an asset generated through an MCP generator server. It is written beside the picked asset as <file>.source.yaml in deterministic YAML.

func MigrateAssetSource

func MigrateAssetSource(s *AssetSource) (*AssetSource, error)

MigrateAssetSource upgrades a valid version 1 or version 2 AssetSource to AssetSourceCurrentVersion (2), returning a cloned and validated document. It keeps Files as recorded (a single-file version 1 sidecar stays without files) and normalizes any backslash paths in Files to clean slash-separated paths.

func ParseAssetSource

func ParseAssetSource(data []byte) (*AssetSource, error)

ParseAssetSource decodes and validates a versioned YAML generated asset source sidecar (*.source.yaml). Unknown fields, duplicate keys, YAML anchors/aliases/merge keys, trailing YAML documents, and missing or unsupported versions are refused.

type AssetSourceParent

type AssetSourceParent struct {
	// Asset is the project-relative path of the parent asset, such as "art/characters/slime_frost.png".
	Asset string `yaml:"asset" schema:"required,minLength=1"`
	// SHA256 is the lowercase hex SHA-256 digest of the parent candidate's bytes.
	SHA256 string `yaml:"sha256,omitempty"`
}

AssetSourceParent names the asset bytes a generated candidate was varied or refined from.

type Audio

type Audio struct {
	// Format is the output format: "wav", "aac" or "mp3".
	Format string `yaml:"format,omitempty" schema:"enum=wav|aac|mp3"`
	// Rate is the output sample rate in Hz.
	Rate int `yaml:"rate,omitempty" schema:"minimum=0"`
	// Channels is 1 for mono or 2 for stereo.
	Channels int `yaml:"channels,omitempty" schema:"minimum=0,maximum=2"`
	// PeakDB normalizes the peak to this level in dBFS; it may not be set with RMSDB. Setting either replaces the target's normalization.
	PeakDB *float64 `yaml:"peakDB,omitempty"`
	// RMSDB normalizes the loudness to this level in dBFS with soft clipping; it may not be set with PeakDB.
	RMSDB *float64 `yaml:"rmsDB,omitempty"`
	// Bitrate is the AAC or MP3 bitrate in kbps.
	Bitrate int `yaml:"bitrate,omitempty" schema:"minimum=0"`
	// Loop is the region a player repeats, written into a WAV output's smpl chunk; AAC and MP3 carry no loop points, so a sound with a loop must be converted to WAV.
	Loop *Loop `yaml:"loop,omitempty"`
}

Audio holds how a sound is converted by an audio target. Each field left out keeps the target's setting in game.yaml.

type CellCollision

type CellCollision struct {
	// Cell is the 0-based cell index (row by row from the top left), matching the frame suffix _<cell>.
	Cell int `yaml:"cell" schema:"required,minimum=0"`
	// Mode selects how collision shapes are generated for this cell: "alpha", "box", "ellipse", "polygon", or "none".
	Mode string `yaml:"mode" schema:"required,enum=alpha|box|ellipse|polygon|none"`
	// Tolerance is the alpha cutoff in [0, 255] for "alpha", "box", and "ellipse" modes.
	Tolerance int `yaml:"tolerance,omitempty" schema:"minimum=0,maximum=255"`
	// MaxVertices limits how many vertices each baked convex polygon may have (3 to 8; 0 uses 8).
	MaxVertices int `yaml:"maxVertices,omitempty" schema:"minimum=0,maximum=8"`
	// Points lists explicit polygon vertices in untrimmed frame pixels when Mode is "polygon".
	Points []Point2D `yaml:"points,omitempty"`
}

CellCollision overrides collision settings for one 0-based cell of a sliced sprite sheet.

func (*CellCollision) UnmarshalYAML

func (c *CellCollision) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML decodes a CellCollision mapping, requiring both cell and mode keys and refusing unknown or repeated keys.

type CellPivot

type CellPivot struct {
	// Cell is the 0-based cell index (row by row from the top left), matching the frame suffix _<cell>.
	Cell int `yaml:"cell" schema:"required,minimum=0"`
	// Pivot is the normalized [x, y] pivot for this cell.
	Pivot PivotPoint `yaml:"pivot" schema:"required,minItems=2"`
}

CellPivot overrides the normalized pivot for one 0-based cell of a sliced sprite sheet.

func (*CellPivot) UnmarshalYAML

func (c *CellPivot) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML decodes a CellPivot mapping, requiring both cell and pivot keys and refusing unknown or repeated keys.

type CellPoints

type CellPoints struct {
	// Cell is the 0-based cell index (row by row from the top left), matching the frame suffix _<cell>.
	Cell int `yaml:"cell" schema:"required,minimum=0"`
	// Points maps point names (such as "muzzle" or "feet") to [x, y] pixel coordinates in the untrimmed cell, overriding any default point of the same name.
	Points map[string]Point2D `yaml:"points" schema:"required"`
}

CellPoints overrides or adds named image points for one 0-based cell of a sliced sprite sheet.

func (*CellPoints) UnmarshalYAML

func (c *CellPoints) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML decodes a CellPoints mapping, requiring both cell and points keys and refusing unknown or repeated keys.

type Collision

type Collision struct {
	// Mode selects how collision shapes are generated: "alpha" (traced from pixel alpha), "box", "ellipse", "polygon" (using Points), or "none".
	Mode string `yaml:"mode,omitempty" schema:"enum=alpha|box|ellipse|polygon|none"`
	// Tolerance is the alpha cutoff in [0, 255] for "alpha", "box", and "ellipse" modes: pixels with alpha > Tolerance are treated as solid (0 treats any non-transparent pixel as solid).
	Tolerance int `yaml:"tolerance,omitempty" schema:"minimum=0,maximum=255"`
	// MaxVertices limits how many vertices each baked convex polygon may have (3 to 8; 0 uses 8).
	MaxVertices int `yaml:"maxVertices,omitempty" schema:"minimum=0,maximum=8"`
	// Points lists explicit polygon vertices in untrimmed frame pixels when Mode is "polygon" (at least 3 points; concave outlines are split into convex parts).
	Points []Point2D `yaml:"points,omitempty"`
	// Cells overrides collision settings for individual 0-based cells of a sliced sprite sheet, in ascending cell index order.
	Cells []CellCollision `yaml:"cells,omitempty"`
}

Collision configures 2D collision shapes baked into packed atlas metadata when an atlas packs the image, as a default for every frame and optional per-cell overrides for a sliced sheet.

func (*Collision) ForCell

func (c *Collision) ForCell(cell int) (CollisionSpec, bool)

ForCell returns the effective collision specification for the 0-based sliced cell, preferring an explicit override in Cells and falling back to the default, or false when neither sets an active mode (or the effective mode is "none").

func (*Collision) ForImage

func (c *Collision) ForImage() (CollisionSpec, bool)

ForImage returns the collision specification for an unsliced image, or false when no default mode is set (or mode is "none").

type CollisionSpec

type CollisionSpec struct {
	// Mode is "alpha", "box", "ellipse", "polygon", or "none".
	Mode string
	// Tolerance is the alpha cutoff in [0, 255]; pixels with alpha > Tolerance are treated as solid.
	Tolerance int
	// MaxVertices limits how many vertices each baked convex polygon may have (3 to 8; 0 defaults to 8).
	MaxVertices int
	// Points holds explicit polygon vertices in untrimmed frame pixels when Mode is "polygon".
	Points []Point2D
}

CollisionSpec is the resolved collision configuration for a single image or slice cell.

func (CollisionSpec) EffectiveMaxVertices

func (s CollisionSpec) EffectiveMaxVertices() int

EffectiveMaxVertices returns MaxVertices when set, or DefaultCollisionMaxVertices (8) when 0.

type Credit

type Credit struct {
	// Author is who made the asset, a person, a group or a company, as its license asks it to be attributed.
	Author string `yaml:"author" schema:"required,minLength=1"`
	// License is the asset's license as an SPDX license expression, such as "CC0-1.0", "CC-BY-4.0" or "MIT OR Apache-2.0"; a license with no SPDX identifier is named "LicenseRef-" followed by a name of its own, with its terms in Notice.
	License string `yaml:"license" schema:"required,minLength=1"`
	// Source is where the asset was obtained, usually a URL; empty for an asset made for the game.
	Source string `yaml:"source,omitempty"`
	// Notice is text the license requires to be shipped with the asset, such as a copyright line or a license's terms; it may span several lines.
	Notice string `yaml:"notice,omitempty"`
}

Credit records where an asset comes from, for the credits file a release ships with.

Example

A credit section records who made an asset and its license, beside an import section or, for an asset no target imports, on its own.

package main

import (
	"fmt"

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

func main() {
	f, err := importsettings.Parse([]byte(`version: 1
credit:
  author: Kenney
  license: CC0-1.0
  source: https://kenney.nl/assets/kenney-fonts
`))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(f.Credit.Author, f.Credit.License, len(f.Sections()) == 0)
}
Output:
Kenney CC0-1.0 true

type File

type File struct {
	// Version is the schema version, from MinVersion (1) to CurrentVersion (2). Version 1 sidecars encode byte-for-byte unchanged; version 2 adds Plugin.
	Version int `yaml:"version" schema:"required"`
	// Image holds the settings of an image (PNG or JPEG).
	Image *Image `yaml:"image,omitempty"`
	// Audio holds the settings of a sound (WAV).
	Audio *Audio `yaml:"audio,omitempty"`
	// Font holds the settings of a font (TrueType or OpenType) that a font target bakes into a bitmap font.
	Font *Font `yaml:"font,omitempty"`
	// Model holds the settings of a model (glTF or GLB) that a model target packs into one GLB file.
	Model *Model `yaml:"model,omitempty"`
	// Plugin holds the importer identifier and settings for an asset handled by an editor plugin (version 2).
	Plugin *Plugin `yaml:"plugin,omitempty"`
	// Credit records who made the asset and its license, which game release and game credits list in the credits file; any kind of asset may carry one.
	Credit *Credit `yaml:"credit,omitempty"`
}

File is one asset's import settings and credit. It holds at least one section: at most one of Image, Audio, Font, Model, and Plugin, for how the asset is imported, and Credit for who made it and under what license.

func Parse

func Parse(data []byte) (*File, error)

Parse decodes a sidecar and validates it.

Example

Parse reads the sidecar beside a sprite sheet, which game assets slices into frames and keeps sharp.

package main

import (
	"fmt"

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

func main() {
	f, err := importsettings.Parse([]byte(`version: 1
image:
  filter: nearest
  slice: {width: 16, height: 16, count: 6}
`))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(importsettings.Path("art/hero/run.png"))
	fmt.Println(f.Image.Filter, f.Image.Slice.Width, f.Image.Slice.Height, f.Image.Slice.Count)
}
Output:
art/hero/run.png.import.yaml
nearest 16 16 6

func (*File) Sections

func (f *File) Sections() []string

Sections returns the names of the import sections f holds, of "image", "audio", "font", "model", and "plugin" in that order; Validate allows at most one.

func (*File) Validate

func (f *File) Validate() error

Validate checks f: the version, at least one section and at most one of image, audio, font, model, and plugin, known formats and filters, values in range, and a credit with an author and a valid SPDX license expression.

type Font

type Font struct {
	// Size is the font size in pixels the glyphs are drawn at; 0 keeps the target's.
	Size int `yaml:"size,omitempty" schema:"minimum=0,maximum=2048"`
	// Chars are the characters baked into the font, each once, in any order, such as " 0123456789"; empty keeps the target's.
	Chars string `yaml:"chars,omitempty"`
	// CharsFrom lists slash-separated project-relative source files whose text characters are collected and merged into the baked set; empty keeps the target's.
	CharsFrom []string `yaml:"charsFrom,omitempty"`
	// CharsFile is a slash-separated project-relative UTF-8 plain-text file whose characters are merged into the baked set; empty keeps the target's.
	CharsFile string `yaml:"charsFile,omitempty"`
	// Padding is the transparent gap around each glyph on the font's pages, in pixels.
	Padding *int `yaml:"padding,omitempty" schema:"minimum=0"`
}

Font holds how a font target bakes a TrueType or OpenType font into an AngelCode BMFont. Each field left out keeps the target's setting in game.yaml.

Example

A font's sidecar sets the size and characters a font target bakes it with.

package main

import (
	"fmt"

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

func main() {
	f, err := importsettings.Parse([]byte(`version: 1
font:
  size: 24
  chars: " 0123456789"
`))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(f.Sections(), f.Font.Size, len(f.Font.Chars))
}
Output:
[font] 24 11

type Image

type Image struct {
	// Filter is the sampling filter written into the texture's KTX2 key/value data under FilterKey, which render3d.LoadKTX2 sets the sampler's filters from: "linear" or "nearest".
	Filter string `yaml:"filter,omitempty" schema:"enum=linear|nearest"`
	// Format is the KTX2 compression format, one of project.TextureFormats: "rgba8", "bc1", "bc3", "bc7", "etc2", "etc2-rgba", "astc4x4" or "uastc".
	Format string `yaml:"format,omitempty" schema:"enum=rgba8|bc1|bc3|bc7|etc2|etc2-rgba|astc4x4|uastc"`
	// Mipmaps writes the whole mipmap chain down to 1x1 when true and only the full-size image when false.
	Mipmaps *bool `yaml:"mipmaps,omitempty"`
	// SRGB marks the texture sRGB and filters its mipmaps in linear light when true.
	SRGB *bool `yaml:"srgb,omitempty"`
	// MaxSize is the longest side in pixels, from 1 to MaxImageSize, the image is to be downscaled to before encoding; 0 keeps its size.
	MaxSize int `yaml:"maxSize,omitempty" schema:"minimum=0,maximum=16384"`
	// Targets maps an export platform name of project.Platforms, such as ios or web, to the settings that replace these on that platform.
	Targets map[string]ImageOverride `yaml:"targets,omitempty"`
	// Slice cuts a sprite sheet into frames on a grid before an atlas packs them; nil packs the image as one frame.
	Slice *Slice `yaml:"slice,omitempty"`
	// NineSlice sets the unscaled pixel insets around the edges of a nine-slice image (or each sliced cell), written to packed atlas meta.slices entries so sprite.LoadAtlas loads them into Atlas.Slices.
	NineSlice *NineSlice `yaml:"nineSlice,omitempty"`
	// Pivot sets the normalized pivot point(s) written to TexturePacker JSON when an atlas packs the image, as a default for every frame and optional per-cell overrides for a sliced sheet.
	Pivot *Pivot `yaml:"pivot,omitempty"`
	// Collision configures per-frame 2D collision shapes baked into packed atlas metadata when an atlas packs the image, as a default for every frame and optional per-cell overrides for a sliced sheet.
	Collision *Collision `yaml:"collision,omitempty"`
	// Points maps named image points (such as "muzzle" or "feet") to [x, y] pixel coordinates in the untrimmed frame, applied to an unsliced image and as defaults for every cell of a sliced sheet.
	Points map[string]Point2D `yaml:"points,omitempty"`
	// CellPoints overrides or adds named image points for individual 0-based cells of a sliced sprite sheet, in ascending cell index order.
	CellPoints []CellPoints `yaml:"cellPoints,omitempty"`
}

Image holds how an image is imported. A texture target reads Filter, Format, Mipmaps and SRGB; an atlas target reads Slice, NineSlice, Pivot, Collision, Points and CellPoints. MaxSize and Targets are recorded and checked but not applied by game assets yet. Each field left out keeps the target's setting in game.yaml.

func (*Image) PointsForCell

func (im *Image) PointsForCell(cell int) map[string]Point2D

PointsForCell returns the effective named points for 0-based sliced cell, merging per-cell overrides on top of im.Points, or nil when none apply.

func (*Image) PointsForImage

func (im *Image) PointsForImage() map[string]Point2D

PointsForImage returns a copy of im's default named points, or nil when none are set.

type ImageOverride

type ImageOverride struct {
	// Filter replaces Image.Filter: "linear" or "nearest".
	Filter string `yaml:"filter,omitempty" schema:"enum=linear|nearest"`
	// Format replaces Image.Format, one of project.TextureFormats.
	Format string `yaml:"format,omitempty" schema:"enum=rgba8|bc1|bc3|bc7|etc2|etc2-rgba|astc4x4|uastc"`
	// MaxSize replaces Image.MaxSize.
	MaxSize int `yaml:"maxSize,omitempty" schema:"minimum=0,maximum=16384"`
	// Mipmaps replaces Image.Mipmaps.
	Mipmaps *bool `yaml:"mipmaps,omitempty"`
	// SRGB replaces Image.SRGB.
	SRGB *bool `yaml:"srgb,omitempty"`
}

ImageOverride changes image import settings for one export platform. Each field left out keeps the image's setting.

type Loop

type Loop struct {
	// Start is the first frame of the loop.
	Start int `yaml:"start" schema:"minimum=0"`
	// End is the frame after the loop's last one; 0 is the end of the sound.
	End int `yaml:"end,omitempty" schema:"minimum=0"`
}

Loop is a region of a sound in sample frames of the source file, from Start up to, but not including, End. A target that resamples the sound scales it to the new rate.

type Model

type Model struct {
	// Scale multiplies the size of every scene of the model, such as 0.01 for a model exported in centimeters; 0 keeps the target's.
	Scale float64 `yaml:"scale,omitempty" schema:"minimum=0"`
	// Animations keeps the model's animations when true and leaves them out of the GLB when false.
	Animations *bool `yaml:"animations,omitempty"`
	// TextureFormat, when set (one of project.ModelTextureFormats, such as "uastc"), converts the model's PNG and JPEG textures into KTX2 containers using KHR_texture_basisu while packing the GLB; empty keeps the target's setting.
	TextureFormat string `yaml:"textureFormat,omitempty" schema:"enum=uastc"`
	// LODs declares the model's levels of detail from finest (index 0) to coarsest, with screen-ratio (and optional distance) thresholds. When omitted, scenemodel.Build pairs glTF nodes following the _LOD1, _LOD2 naming convention with default screen-ratio thresholds.
	LODs []ModelLOD `yaml:"lods,omitempty"`
	// LODHysteresis is the optional relative deadband in [0, 0.5] used by render3d.Queue to prevent LOD popping near thresholds.
	LODHysteresis float32 `yaml:"lodHysteresis,omitempty" schema:"minimum=0,maximum=0.5"`
	// FPS is the frame rate that ModelSlice.Start and End count frames at; 0 leaves it unset. Clips, Materials, SkipNodes and FPS are recorded and checked but not applied by game assets or scenemodel yet.
	FPS float32 `yaml:"fps,omitempty" schema:"minimum=0"`
	// Clips renames, sets the loop mode of, or slices the model's animations, each naming its source animation once.
	Clips []ModelClip `yaml:"clips,omitempty"`
	// Materials maps a glTF material name to the slash-separated path, relative to the project root, of the material file that replaces it.
	Materials map[string]string `yaml:"materials,omitempty"`
	// SkipNodes names the glTF nodes to leave out, each once.
	SkipNodes []string `yaml:"skipNodes,omitempty"`
}

Model holds how a model target packs a glTF model into one GLB file and how scenemodel builds its levels of detail. Each field left out keeps the target's setting in game.yaml.

type ModelClip

type ModelClip struct {
	// From names the source animation in the glTF file.
	From string `yaml:"from"`
	// Name renames the animation; empty keeps From. A clip with Slices produces the slices' clips instead and may not set Name or Loop.
	Name string `yaml:"name,omitempty"`
	// Loop sets whether the clip loops; nil keeps the player's default.
	Loop *bool `yaml:"loop,omitempty"`
	// Slices cuts the source animation into clips by frame range, in ascending, non-overlapping order.
	Slices []ModelSlice `yaml:"slices,omitempty"`
}

ModelClip describes a named source animation and optional frame slices.

type ModelLOD

type ModelLOD struct {
	// Model optionally names a separate glTF or GLB model file (slash-separated path from the project root) providing this level's geometry; empty uses this model file.
	Model string `yaml:"model,omitempty"`
	// Node optionally names a node inside the model (this file, or Model when set) providing this level's geometry; cannot be combined with Mesh.
	Node string `yaml:"node,omitempty"`
	// Mesh optionally names a mesh inside the model (this file, or Model when set) providing this level's geometry; cannot be combined with Node.
	Mesh string `yaml:"mesh,omitempty"`
	// MinScreenRatio is the minimum projected viewport-height fraction in [0, 1] at which this level is drawn (render3d.LODLevel.MinScreenRatio). Levels must strictly decrease in MinScreenRatio; 0 marks an unbounded coarsest fallback.
	MinScreenRatio float32 `yaml:"minScreenRatio,omitempty" schema:"minimum=0,maximum=1"`
	// MaxDistance is an optional maximum camera distance in world units at which this level is drawn (render3d.LODLevel.MaxDistance); 0 disables distance-based switching for this level.
	MaxDistance float32 `yaml:"maxDistance,omitempty" schema:"minimum=0"`
}

ModelLOD describes one level of detail of a glTF model (Model.LODs), ordered from finest (LOD 0) to coarsest.

type ModelSlice

type ModelSlice struct {
	// Name names the clip the slice produces.
	Name string `yaml:"name"`
	// Start is the first frame of the slice, 0 or more.
	Start int `yaml:"start"`
	// End is the last frame of the slice, after Start.
	End int `yaml:"end"`
	// Loop sets whether the slice loops; nil keeps the player's default.
	Loop *bool `yaml:"loop,omitempty"`
}

ModelSlice cuts a named clip from the frames Start to End (both included) of a source animation, looping when Loop is true.

type NineSlice

type NineSlice struct {
	// Left is the unscaled left edge inset in source image pixels.
	Left int `yaml:"left,omitempty" schema:"minimum=0"`
	// Top is the unscaled top edge inset in source image pixels.
	Top int `yaml:"top,omitempty" schema:"minimum=0"`
	// Right is the unscaled right edge inset in source image pixels.
	Right int `yaml:"right,omitempty" schema:"minimum=0"`
	// Bottom is the unscaled bottom edge inset in source image pixels.
	Bottom int `yaml:"bottom,omitempty" schema:"minimum=0"`
}

NineSlice holds the unscaled edge insets of a nine-slice image in source image pixels. Opposite sides must not overlap (left + right < image width and top + bottom < image height).

func (NineSlice) ValidateBounds

func (n NineSlice) ValidateBounds(bounds image.Rectangle) error

ValidateBounds checks that n's insets are valid and do not overlap across bounds (left+right < width and top+bottom < height). Errors are *loaderr.Error values pointing at image.nineSlice so callers can locate them in the sidecar YAML with loaderr.Locate.

type Pivot

type Pivot struct {
	// Default is the normalized [x, y] pivot applied to an unsliced image and to every cell of a sliced sheet not listed in Cells.
	Default *PivotPoint `yaml:"default,omitempty" schema:"minItems=2"`
	// Cells overrides the normalized [x, y] pivot for individual 0-based cells of a sliced sprite sheet, in ascending cell index order.
	Cells []CellPivot `yaml:"cells,omitempty"`
}

Pivot sets the normalized pivot points written into a packed atlas's TexturePacker frame metadata. Default applies to an unsliced image and to every cell of a sliced sheet without an entry in Cells.

func (*Pivot) ForCell

func (p *Pivot) ForCell(cell int) (PivotPoint, bool)

ForCell returns the effective pivot for the 0-based sliced cell, preferring an explicit override in Cells and falling back to Default, or false when neither is set.

func (*Pivot) ForImage

func (p *Pivot) ForImage() (PivotPoint, bool)

ForImage returns the pivot for an unsliced image, or false when no default pivot is set.

type PivotPoint

type PivotPoint [2]float64

PivotPoint is a normalized [x, y] pivot coordinate as fractions of the untrimmed frame's width and height: [0, 0] is the top-left corner, [0.5, 0.5] is the center, and [0.5, 1] is bottom-center.

func (PivotPoint) MarshalYAML

func (p PivotPoint) MarshalYAML() (any, error)

MarshalYAML encodes p as a deterministic YAML flow sequence [x, y].

func (*PivotPoint) UnmarshalYAML

func (p *PivotPoint) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML decodes a [x, y] sequence of two finite numbers into p.

type Plugin

type Plugin struct {
	// Importer names the plugin and importer ID in "<plugin>.<id>" form, such as "skelkit.skeleton".
	Importer string `yaml:"importer" schema:"required,minLength=1"`
	// Settings holds the importer's key/value settings, encoded deterministically with sorted keys and lossless YAML scalar, list, and mapping values.
	Settings map[string]any `yaml:"settings,omitempty"`
}

Plugin holds the importer identifier and typed settings for an asset handled by an editor plugin. A sidecar with a Plugin section requires Version == CurrentVersion (2) and may not also set Image, Audio, Font, or Model.

type Point2D

type Point2D [2]float64

Point2D is an [x, y] coordinate in untrimmed frame pixels from the top-left corner, used for collision polygon vertices and named image points.

func (Point2D) MarshalYAML

func (p Point2D) MarshalYAML() (any, error)

MarshalYAML encodes p as a deterministic YAML flow sequence [x, y].

func (*Point2D) UnmarshalYAML

func (p *Point2D) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML decodes a [x, y] sequence of two finite numbers into p.

type Slice

type Slice struct {
	// Width and Height are each cell's size; both must be positive.
	Width  int `yaml:"width" schema:"required,minimum=1"`
	Height int `yaml:"height" schema:"required,minimum=1"`
	// Margin is the gap between the image's top and left edges and the first row and column of cells.
	Margin int `yaml:"margin,omitempty" schema:"minimum=0"`
	// Spacing is the gap between neighboring cells.
	Spacing int `yaml:"spacing,omitempty" schema:"minimum=0"`
	// Count is how many cells are frames, counted from the first; 0 takes every cell that fits.
	Count int `yaml:"count,omitempty" schema:"minimum=0"`
}

Slice is the grid a sprite sheet is cut into, in pixels. Its cells are taken row by row from the top left, and frame i of the image name.png is packed as name_i.png.

func (Slice) CellRect

func (s Slice) CellRect(bounds image.Rectangle, cols, cell int) (image.Rectangle, bool)

CellRect computes the pixel rectangle for 0-based cell in a grid with cols columns across bounds without allocating a full slice of rectangles.

func (Slice) Cells

func (s Slice) Cells(bounds image.Rectangle) (rects []image.Rectangle, cols, rows int, err error)

Cells returns the pixel rectangles of every cell s cuts from an image with bounds, row by row from the top left, along with the grid's column and row counts. It fails when s is invalid, when no cell fits, when Count exceeds the cells that fit, or when the resulting cell count exceeds MaxSliceCells.

func (Slice) GridCounts

func (s Slice) GridCounts(bounds image.Rectangle) (count, cols, rows int, err error)

GridCounts validates s against bounds and returns the resulting cell count, column count, and row count without allocating cell rectangles. It fails when s is invalid, when no cell fits, when the grid cell count overflows int, or when Count exceeds the cells that fit.

Jump to

Keyboard shortcuts

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