GitHub快速開始

API 參考取自原始碼中的 Go 文件註解,以英文撰寫。

package importsettings

import "github.com/nsgo-dev/game/pkg/tooling/importsettings"

概覽

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, as Godot's .import files do.

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.

索引

常數

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

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

const AssetSourceSchemaURL = "https://game.nsgo.dev/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 so editors and AI tools validate and complete source files as they are written.

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.

const AssetSourceVersion = 1

AssetSourceVersion is the YAML schema version of generated asset source sidecars (*.source.yaml).

const CurrentVersion = 1

CurrentVersion is the sidecar schema version this package reads and writes.

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.

const MaxSliceCells = 65536

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

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

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

const SchemaURL = "https://game.nsgo.dev/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 sidecar's first line, so editors that run the YAML language server validate and complete the file as it is written.

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.

變數

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.

函式

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(f *File) ([]byte, error)

Encode validates f and writes it as deterministic 2-space YAML, SchemaComment on its first line, that Parse reads back unchanged.

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

EncodeAssetSource validates s and writes deterministic 2-space YAML prefixed with AssetSourceSchemaComment.

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(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(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(asset string) string

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

func ValidateAssetSource(s *AssetSource) error

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

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.

型別

type AssetSource struct {
	// Version is the schema version; it must equal AssetSourceVersion (1).
	Version int `yaml:"version" schema:"required"`
	// 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"`
}

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 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 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 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 (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 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.

type File struct {
	// Version is the schema version; it must equal CurrentVersion (1).
	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"`
	// 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 and Model, for how game assets imports the asset, and Credit for who made it and under what license.

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

Parse decodes a sidecar and validates it.

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

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

func (f *File) Validate() error

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

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"`
	// 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.

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: "rgba8", "bc1", "bc3" or "etc2".
	Format string `yaml:"format,omitempty" schema:"enum=rgba8|bc1|bc3|etc2"`
	// 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"`
	// 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"`
	// 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"`
}

Image holds how an image is imported. A texture target reads Filter, Format, Mipmaps and SRGB; an atlas target reads Slice and Pivot. Each field left out keeps the target's setting in game.yaml.

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 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"`
	// 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"`
}

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 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 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 (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 (p *Pivot) ForImage() (PivotPoint, bool)

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

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 (p PivotPoint) MarshalYAML() (any, error)

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

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

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

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 (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 (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 (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.