Documentation
¶
Overview ¶
Package project reads, validates, writes and applies game.yaml, the one project file at the root of a game that holds its settings.
The Project File ¶
A game.yaml names the game (name, id, appVersion) and holds its window and virtual resolution (window, display), its input map (input), its audio buses (audio), the scenes and resources it loads at startup (autoload), its export presets per platform (export), the editor plugins the scene editor turns on for it (editor) and the asset pipeline targets game assets builds (assets). Parse decodes a version 1 file into a File and runs Validate, refusing unknown fields, unsupported versions, duplicate names and out-of-range values. Encode validates a File and writes deterministic 2-space YAML in a fixed key order that Parse reads back unchanged, so a load and save never alters a file Encode wrote.
The Runtime ¶
A game embeds its game.yaml and reads it with Parse (or MustParse for a file that is part of the program). File.WindowSize, File.WindowConstraints and File.Appearance feed nsgo.Run's options, File.Viewport is the screen.Viewport of the virtual resolution, File.BindInput binds the input map into an input.Actions, File.ConfigureMixer gives a sound.Mixer each bus's default volume and DSP chain, and File.LoadAutoloads reads the autoloaded scenes (as sceneformat documents) and resources from an fs.FS.
The Tools ¶
game.yaml owns the fields NSGo's own nsgo.yaml repeats: the app's name, id and version, its appearance and its build output and targets. SyncNSGo writes them into an nsgo.yaml, keeping its other keys and comments, and CheckNSGo reports where an nsgo.yaml disagrees. The game project command runs these on a project directory, and the editor opens and saves game.yaml (editor.Editor.OpenProject, EditProject and SaveProject). PathRefs lists every path game.yaml holds to a file or folder of the project with the YAML node that writes it, and File.EachPath visits the same paths in a parsed File, so that package refs can check and rewrite them when a file moves.
Index ¶
- Constants
- Variables
- func AtlasNamed(p, name string) bool
- func Bool(v bool) *bool
- func Encode(f *File) ([]byte, error)
- func EncodeBrief(b *Brief) ([]byte, error)
- func Float32(v float32) *float32
- func Float64(v float64) *float64
- func HasScheme(ref string) bool
- func IsAtlasJSON(data []byte) bool
- func IsPortableTarget(target string) bool
- func IsSHA256(s string) bool
- func NearestAtlases(atlases []string, from, name string) []string
- func ResolveRef(dir, ref string) (string, error)
- func SaveBrief(path string, b *Brief) error
- func SkipDir(name string) bool
- func TargetsOf(platform string) []string
- func Validate(f *File) error
- func ValidateBrief(b *Brief) error
- func ValidateFontChars(chars string) error
- func ValidateFontSize(size int) error
- func ValidateModelScale(scale float64) error
- func ValidatePackName(name string) error
- func ValidatePackVersion(v string) error
- type Action
- type ActionAssist
- type Assets
- type AtlasTarget
- type Audio
- type AudioTarget
- type Autoload
- type Axis
- type Binding
- type Bitcrush
- type Brief
- type BriefArt
- type BriefArtReference
- type BriefFeel
- type BriefPlaytestTarget
- type BriefSection
- type Budgets
- type Bus
- type Delay
- type Display
- type Editor
- type Effect
- type Entry
- type Export
- type File
- func (f *File) Appearance() core.Appearance
- func (f *File) BindInput(a *input.Actions)
- func (f *File) BuildTargets() []string
- func (f *File) CheckNSGo(nsgoYAML []byte) error
- func (f *File) Clone() *File
- func (f *File) ConfigureMixer(m *sound.Mixer)
- func (f *File) ConfigurePhysics3DWorld(w *physics3d.World)
- func (f *File) ConfigurePhysicsWorld(w *physics.World)
- func (f *File) ConfigureRigidWorld(w *physics.RigidWorld)
- func (f *File) EachPath(visit func(field string, path *string))
- func (f *File) FindPack(name string) *Pack
- func (f *File) LDtkOptions(resolveImage func(relPath string) core.ImageSource) tilemap.LDtkOptions
- func (f *File) LoadAutoloads(fsys fs.FS) (*Loaded, error)
- func (f *File) PhysicsLayerTable() *sceneformat.PhysicsLayerTable
- func (f *File) PhysicsSettings() *sceneformat.PhysicsSettings
- func (f *File) PortableBuildTargets() []string
- func (f *File) Preset(platform string) (Preset, bool)
- func (f *File) Region(action string) (core.Bounds, bool)
- func (f *File) SyncNSGo(nsgoYAML []byte) ([]byte, error)
- func (f *File) Title() string
- func (f *File) Viewport() (screen.Viewport, bool)
- func (f *File) WindowConstraints() core.WindowConstraints
- func (f *File) WindowSize() (width, height core.Points)
- type Filter
- type FontTarget
- type Gain
- type GamepadAxis
- type Input
- type LDtkIntGridRule
- type Loaded
- type ManifestTarget
- type ModelTarget
- type MotionAxis
- type NavAgent
- type Navigation
- type Pack
- type PathRef
- type Physics
- func (p *Physics) LDtkOptions(resolveImage func(relPath string) core.ImageSource) tilemap.LDtkOptions
- func (p *Physics) LayerBit(name string) (uint, bool)
- func (p *Physics) LayerMask2D(names ...string) (physics.LayerMask, error)
- func (p *Physics) LayerMask3D(names ...string) (physics3d.LayerMask, error)
- func (p *Physics) LayerTable() *sceneformat.PhysicsLayerTable
- type PhysicsLayer
- type Preset
- type Rect
- type Resolver
- func (r *Resolver) Atlas(name string) (*sprite.Atlas, error)
- func (r *Resolver) AtlasNames() []string
- func (r *Resolver) ForScene(scenePath string) *Resolver
- func (r *Resolver) LDtkOptions() tilemap.LDtkOptions
- func (r *Resolver) Library() *resource.Library
- func (r *Resolver) Material(p string) (*resource.Material, error)
- func (r *Resolver) PhysicsMaterial(p string) (*resource.PhysicsMaterial, error)
- func (r *Resolver) ReadFile(p string) ([]byte, error)
- func (r *Resolver) Refresh()
- func (r *Resolver) Scene(p string) (*sceneformat.SceneDoc, error)
- type Reverb
- type TextureTarget
- type Vec2
- type Vec3
- type Window
Examples ¶
Constants ¶
const ( FieldAutoloadScene = "autoload scene" FieldAutoloadResource = "autoload resource" FieldAssetsCache = "assets cache" FieldAtlasIn = "assets atlas in" FieldAtlasOut = "assets atlas out" FieldTextureIn = "assets texture in" FieldTextureOut = "assets texture out" FieldAudioIn = "assets audio in" FieldAudioOut = "assets audio out" FieldFontIn = "assets font in" FieldFontOut = "assets font out" FieldModelIn = "assets model in" FieldModelOut = "assets model out" FieldManifestIn = "assets manifest in" FieldManifestOut = "assets manifest out" FieldPackDir = "pack dir" )
The fields of a project file that hold a path to a file or folder of the project, in PathRef.Field and in messages.
const ( // KindTouchRegion is a touch inside Region (input.TouchRegion). KindTouchRegion = "touchRegion" // KindMouseButton is Button held anywhere on the view (input.MouseButton). KindMouseButton = "mouseButton" // KindMouseRegion is Button held inside Region (input.MouseRegion). KindMouseRegion = "mouseRegion" // KindKey is Key held on a keyboard, following the active keyboard layout (input.Key). KindKey = "key" // KindKeyCode is Code held at a physical keyboard position, independent of layout (input.KeyCode). KindKeyCode = "keyCode" // KindGamepadButton is Button held on a connected game controller (input.GamepadButton). KindGamepadButton = "gamepadButton" )
Binding kinds name the input.Input constructors.
const ( // PackAsset is a pack of assets, such as images, atlases, sounds and data files. PackAsset = "asset" // PackPlugin is a pack that turns on editor plugins, with any files they read. PackPlugin = "plugin" // PackTemplate is a pack of scenes and prefabs a game starts from or builds on. PackTemplate = "template" )
Pack kinds name what a library pack holds.
const BriefFileName = "brief.yaml"
BriefFileName is the game brief file name at a project's root.
const BriefSchemaComment = "# yaml-language-server: $schema=" + BriefSchemaURL
BriefSchemaComment is the first line EncodeBrief writes: a YAML comment pointing a YAML language server at BriefSchemaURL.
const BriefSchemaURL = "https://game.nsgo.dev/schemas/brief.v1.json"
BriefSchemaURL is where the JSON Schema of version 1 game brief files (brief.yaml) is published.
const BriefVersion = 1
BriefVersion is the brief.yaml schema version this package reads and writes.
const CurrentVersion = 1
CurrentVersion is the project file schema version this package reads and writes.
const DefaultAssetsCache = ".game/assets-cache.yaml"
DefaultAssetsCache is where game assets keeps its build cache, relative to the project root, when Assets.Cache is empty. Its directory starts with a dot, so the manifest's scan of an assets directory never lists it.
const DefaultFontChars = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
DefaultFontChars are the characters a font target bakes when neither it nor its font's import settings list them: printable ASCII, from the space to the tilde.
const DefaultFontSize = 32
DefaultFontSize is the size in pixels a font target bakes its glyphs at when neither it nor its font's import settings set one.
DefaultNavAgent names the agent type game navmesh bakes for when game.yaml declares none.
const FileName = "game.yaml"
FileName is the project file's name at a game's root.
const MaxFontSize = 2048
MaxFontSize is the largest size in pixels a font target or a font's import settings may set: the width and height of a font's page, which each glyph must fit on.
MaxNavVertsPerPoly is the largest Navigation.MaxVertsPerPoly.
const NSGoFileName = "nsgo.yaml"
NSGoFileName is NSGo's own project file, beside game.yaml.
const SchemaURL = "https://game.nsgo.dev/schemas/game.v1.json"
SchemaURL is where the JSON Schema of version 1 project files (game.yaml) is published.
Variables ¶
var AudioFormats = []string{"wav", "aac", "mp3"}
AudioFormats are the formats an audio target may name, as game audio's -format flag spells them.
var BindingKinds = []string{KindTouchRegion, KindMouseButton, KindMouseRegion, KindKey, KindKeyCode, KindGamepadButton}
BindingKinds lists every binding kind a game.yaml action may declare, in display order.
var BriefSections = []BriefSection{ BriefSectionPitch, BriefSectionGenre, BriefSectionPlatforms, BriefSectionArtDirection, BriefSectionFeel, BriefSectionToneAndAudio, }
BriefSections lists every section checked by Brief.MissingSections in canonical display order.
var GamepadAxes = []string{"leftX", "leftY", "rightX", "rightY"}
GamepadAxes lists the W3C Standard Gamepad stick axis names accepted by GamepadAxis.Axis.
var GamepadButtons = []string{
"south", "east", "west", "north",
"leftShoulder", "rightShoulder", "leftTrigger", "rightTrigger",
"back", "start", "leftStick", "rightStick",
"dpadUp", "dpadDown", "dpadLeft", "dpadRight",
"home",
}
GamepadButtons lists the W3C Standard Gamepad button names accepted by KindGamepadButton.
var MotionAxes = []string{"tiltX", "tiltY", "tiltZ", "gyroX", "gyroY", "gyroZ"}
MotionAxes lists the device motion sensor axis names accepted by MotionAxis.Axis.
var MouseButtons = []string{"left", "right", "middle", "back", "forward"}
MouseButtons lists the mouse button names accepted by KindMouseButton and KindMouseRegion.
var PackKinds = []string{PackAsset, PackPlugin, PackTemplate}
PackKinds are the kinds a Pack may have, in the order the tools list them.
var Platforms = []string{"macos", "windows", "linux", "ios", "tvos", "watchos", "android", "harmonyos", "web", "miniprogram"}
Platforms are the export preset platforms, each a name nsgo build -target accepts.
var TextureFormats = []string{"rgba8", "bc1", "bc3", "etc2"}
TextureFormats are the KTX2 formats a texture target may name, as game tex's -format flag spells them.
Functions ¶
func AtlasNamed ¶
AtlasNamed reports whether name names the atlas JSON file at p, a slash-separated path from the project root, as NearestAtlases matches it before choosing the nearest: p without its extension is name, cleaned and taken from the project root, or p's base name without its extension is name.
func Encode ¶
Encode validates f and serializes it as deterministic 2-space YAML that Parse reads back unchanged.
func EncodeBrief ¶
EncodeBrief validates b and writes it as deterministic 2-space YAML prefixed with BriefSchemaComment. A file EncodeBrief wrote loads and saves back unchanged byte for byte.
func Float32 ¶
Float32 returns a pointer to v for optional fields such as Bus.Volume and Audio.Master.
func Float64 ¶
Float64 returns a pointer to v for optional numeric bounds such as BriefPlaytestTarget.Min, Max, and Equal.
func HasScheme ¶
HasScheme reports whether ref starts with a URI scheme of two or more letters, such as asset: or https:, which ResolveRef refuses as a path.
func IsAtlasJSON ¶
IsAtlasJSON reports whether data is a JSON object with top-level frames (an object or an array) and meta (an object), as TexturePacker and Aseprite export an atlas: the test Resolver and `game check` both tell a project's atlas JSON files from its other JSON files by.
func IsPortableTarget ¶
IsPortableTarget reports whether target (or platform name) builds on every host (macOS, Linux, and Windows) with plain Go, without macOS, Xcode, or an Android NDK.
func IsSHA256 ¶
IsSHA256 reports whether s is a SHA-256 digest written as 64 lower-case hexadecimal digits.
func NearestAtlases ¶
NearestAtlases returns which of atlases, the slash-separated paths of a project's atlas JSON files from its root, a scene in the directory from (a path from the root, "." for the root itself) names name, as `game check` and Resolver find them: the files whose path without its extension is name, or whose base name without its extension is name, keeping only those nearest from, counting the directories up from from and down to the file. It returns them sorted; more than one means name is ambiguous there, and none that it names no atlas.
func ResolveRef ¶
ResolveRef joins ref, a slash-separated path written in a file of a project, to dir, the slash-separated directory from the project root it is relative to, and returns the path from the project root, or an error saying why ref cannot name a file there: it refuses a path with backslashes, an absolute path or one starting with a Windows drive letter such as C:, a URI with a scheme of two or more letters (HasScheme), and a path that leads outside the root. `game check` (package assetcheck) reads the paths files write with it, and Resolver reads an atlas's meta.image with it, so the two accept the same images.
func SkipDir ¶
SkipDir reports whether a walk of a project's files skips the directory called name, as the go command skips it: a name starting with "." or "_", or testdata. Resolver and `game check` both skip them.
func ValidateBrief ¶
ValidateBrief checks b against the version 1 brief.yaml schema.
func ValidateFontChars ¶
ValidateFontChars checks the characters of a font target or a font's import settings: valid UTF-8 without control characters, line breaks included. The space is allowed.
func ValidateFontSize ¶
ValidateFontSize checks the size of a font target or a font's import settings: 0, which keeps the default, up to MaxFontSize.
func ValidateModelScale ¶
ValidateModelScale checks the scale of a model target or a model's import settings: a finite number that is not negative, 0 meaning the default.
func ValidatePackName ¶
ValidatePackName reports whether name can name a library pack: 1 to 64 lower-case ASCII letters, digits and '-', starting with a letter or digit, so that it is also a directory name on every platform.
func ValidatePackVersion ¶
ValidatePackVersion reports whether v is a valid semantic version (MAJOR.MINOR.PATCH[-prerelease][+build]) without a leading "v", such as 1.2.0.
Types ¶
type Action ¶
type Action struct {
// Name uniquely identifies the action.
Name string `yaml:"name" schema:"required"`
// Bindings are the inputs that press the action; an action without any is declared for code to bind, such as one an axis reads.
Bindings []Binding `yaml:"bindings,omitempty"`
// Assist declares which player motor assists (hold-to-toggle, mash-to-hold) apply to this action; nil leaves the action ineligible so menu actions are never latched.
Assist *ActionAssist `yaml:"assist,omitempty,flow"`
}
Action is one named action and the physical inputs that trigger it.
type ActionAssist ¶
type ActionAssist struct {
// Toggle reports whether a player may latch this action on press and release it on the next press.
Toggle bool `yaml:"toggle,omitempty"`
// Mash reports whether a player may satisfy rapid-press mashing of this action by holding it.
Mash bool `yaml:"mash,omitempty"`
// MashRate is the synthetic press rate in presses per second used when MashToHold is active; 0 uses input.DefaultMashRate (10). Refused when Mash is false.
MashRate float64 `yaml:"mashRate,omitempty" schema:"minimum=0"`
}
ActionAssist declares which player motor assists an action opts into.
type Assets ¶
type Assets struct {
// Cache is the build cache's path; empty is DefaultAssetsCache.
Cache string `yaml:"cache,omitempty"`
// Atlases are the sprite atlases to pack, each from one folder of PNG images.
Atlases []AtlasTarget `yaml:"atlases,omitempty"`
// Textures are the images to encode into KTX2 containers.
Textures []TextureTarget `yaml:"textures,omitempty"`
// Audio are the WAV files to normalize, resample and convert.
Audio []AudioTarget `yaml:"audio,omitempty"`
// Fonts are the TrueType and OpenType fonts, and the folders of PNG glyph images, to bake into bitmap fonts.
Fonts []FontTarget `yaml:"fonts,omitempty"`
// Models are the glTF models to pack into single GLB files.
Models []ModelTarget `yaml:"models,omitempty"`
// Manifest, when set, is the typed Go asset manifest generated after every other target is built.
Manifest *ManifestTarget `yaml:"manifest,omitempty"`
}
Assets declares the targets game assets builds: the sprite atlases to pack, the textures to encode, the audio to convert, the fonts to bake, the models to pack and the asset manifest to generate. Paths in it are slash-separated and relative to the project root, and may not leave it.
func (*Assets) CachePath ¶
CachePath returns the build cache's slash-separated path relative to the project root: Cache, or DefaultAssetsCache when a is nil or Cache is empty.
func (*Assets) IsOutput ¶
IsOutput reports whether a target of a writes the file at the slash-separated path p, relative to the project root: the cache, a texture, an audio output, a font's .fnt file or one of its pages (name.png or name-N.png beside it), a model, the manifest, or a page of an atlas (name.png, name.json, name-N.png or name-N.json in its out folder). Such a file is built from the targets' inputs rather than authored, so it is not an asset of its own. A nil a writes nothing.
func (*Assets) Validate ¶
Validate checks the assets section as Validate checks the whole file: paths that are relative, slash-separated and stay inside the project, settings in range, known formats, no two targets writing the same file, no file written over game.yaml or over a target's input, no atlas or font page or other PNG written where an atlas reads its images, and no cache where the manifest lists assets.
type AtlasTarget ¶
type AtlasTarget struct {
// Name is the base name of the atlas's page files, such as "ui" for ui.png and ui.json.
Name string `yaml:"name"`
// In is the folder of PNG images, searched recursively.
In string `yaml:"in"`
// Out is the folder the pages are written to.
Out string `yaml:"out"`
// Padding is the transparent gap between frames in pixels; nil is 1.
Padding *int `yaml:"padding,omitempty"`
// Extrude is how many edge pixels are repeated around each frame.
Extrude int `yaml:"extrude,omitempty"`
// MaxWidth bounds a page's width in pixels; 0 is 2048.
MaxWidth int `yaml:"maxWidth,omitempty"`
// MaxHeight bounds a page's height in pixels; 0 is 2048.
MaxHeight int `yaml:"maxHeight,omitempty"`
// Scale is written to the pages' meta.scale; 0 is 1.
Scale int `yaml:"scale,omitempty"`
// Trim removes transparent borders around each image; nil is true.
Trim *bool `yaml:"trim,omitempty"`
}
AtlasTarget is one sprite atlas packed from a folder of PNG images, as game pack packs it.
type Audio ¶
type Audio struct {
// Master is the default master volume in [0, 1]; nil leaves it at 1.
Master *float32 `yaml:"master,omitempty" schema:"minimum=0,maximum=1"`
// Buses are the mixer groups in declaration order.
Buses []Bus `yaml:"buses,omitempty"`
}
Audio is the master volume and the buses (sound.Mixer groups) a game plays through.
type AudioTarget ¶
type AudioTarget struct {
// In is the source WAV file.
In string `yaml:"in"`
// Out is the file written.
Out string `yaml:"out"`
// Format is one of AudioFormats; empty is wav. aac and mp3 need an external encoder, as game audio describes.
Format string `yaml:"format,omitempty"`
// Rate is the sample rate in Hz; 0 keeps the input's.
Rate int `yaml:"rate,omitempty"`
// Channels is 1 for mono or 2 for stereo; 0 keeps the input's.
Channels int `yaml:"channels,omitempty"`
// PeakDB normalizes the peak to this level in dBFS; it may not be set with RMSDB.
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; 0 is 128.
Bitrate int `yaml:"bitrate,omitempty"`
}
AudioTarget is one WAV file normalized, resampled and converted, as game audio converts it.
type Autoload ¶
type Autoload struct {
// MainScene names the scene in Scenes the game starts in; empty leaves the choice to the game.
MainScene string `yaml:"mainScene,omitempty"`
// Scenes are sceneformat YAML documents, loaded and validated at startup.
Scenes []Entry `yaml:"scenes,omitempty"`
// Resources are other files loaded as bytes at startup, such as data tables.
Resources []Entry `yaml:"resources,omitempty"`
}
Autoload lists the scenes and resources a game loads at startup.
type Axis ¶
type Axis struct {
// Name uniquely identifies the axis.
Name string `yaml:"name" schema:"required"`
// Negative names a declared action that drives the axis toward -1; at least one of Negative and Positive is required.
Negative string `yaml:"negative,omitempty"`
// Positive names a declared action that drives the axis toward +1; at least one of Negative and Positive is required.
Positive string `yaml:"positive,omitempty"`
}
Axis is a named axis over two actions, as input.Actions.BindAxis binds it.
type Binding ¶
type Binding struct {
// Kind is KindTouchRegion, KindMouseButton, KindMouseRegion, KindKey, KindKeyCode or KindGamepadButton.
Kind string `yaml:"kind" schema:"required,enum=touchRegion|mouseButton|mouseRegion|key|keyCode|gamepadButton"`
// Button is a mouse button ("left", "right", "middle", "back" or "forward") for KindMouseButton and KindMouseRegion, or a standard gamepad button (one of GamepadButtons) for KindGamepadButton; refused by other kinds.
Button string `yaml:"button,omitempty"`
// Key is the keyboard key name (such as "a", "space", "left", "enter" or "shift") for KindKey, matched case-insensitively as input.Key does; refused by other kinds.
Key string `yaml:"key,omitempty"`
// Code is the physical keyboard position (such as "KeyW", "ArrowLeft", "Space" or "ShiftLeft") for KindKeyCode, as input.KeyCode reads it; refused by other kinds.
Code string `yaml:"code,omitempty"`
// Region is the rectangle in virtual coordinates (or view coordinates without a Display) that KindTouchRegion and KindMouseRegion test; refused by other kinds.
Region *Rect `yaml:"region,omitempty,flow"`
}
Binding is one physical input bound to an action.
type Bitcrush ¶
type Bitcrush struct {
// Bits is the quantized bit depth in [1, 15].
Bits int `yaml:"bits" schema:"required,minimum=1,maximum=15"`
// Downsample holds each sample for this many frames; 0 and 1 keep every frame.
Downsample int `yaml:"downsample,omitempty" schema:"minimum=0"`
}
Bitcrush is a lo-fi quantizer (sound.Bitcrush): Bits in [1, 15] and Downsample 0 or more, where 0 and 1 keep every frame.
type Brief ¶
type Brief struct {
// Version is the schema version; it must equal BriefVersion (1).
Version int `yaml:"version" schema:"required"`
// Pitch describes what the game is meant to be in a sentence or two.
Pitch string `yaml:"pitch,omitempty"`
// Genre lists the game's primary genre labels, such as "2D platformer" and "action".
Genre []string `yaml:"genre,omitempty,flow"`
// Tags lists optional extra keywords or sub-genre tags describing the game.
Tags []string `yaml:"tags,omitempty,flow"`
// Platforms lists the target platforms and control styles, such as "desktop", "phones, touch", and "web".
Platforms []string `yaml:"platforms,omitempty,flow"`
// ArtDirection describes visual style, resolution, palette, and silhouette rules.
ArtDirection string `yaml:"artDirection,omitempty"`
// Art holds structured visual direction notes and pinned reference images read by the agent before every request.
Art *BriefArt `yaml:"art,omitempty"`
// ToneAndAudio describes mood, music, and sound direction.
ToneAndAudio string `yaml:"toneAndAudio,omitempty"`
// Feel describes game feel, difficulty pacing, and structured playtest targets.
Feel *BriefFeel `yaml:"feel,omitempty"`
}
Brief is the root of a versioned brief.yaml file at a game project's root. The agent reads it before every request and checks its work against it, and playtests can read structured targets from Feel.Targets.
func ParseBrief ¶
ParseBrief decodes and validates a versioned brief.yaml document. Unknown fields, trailing YAML documents, duplicate keys, YAML anchors/aliases/merge keys, missing or unsupported versions, and invalid playtest target bounds are refused with *loaderr.Error line info.
func ReadBriefFS ¶
ReadBriefFS reads and parses BriefFileName at the root of fsys.
func (*Brief) MissingSections ¶
func (b *Brief) MissingSections() []BriefSection
MissingSections returns the brief sections that are currently empty, in canonical BriefSections order.
func (*Brief) TargetsForScene ¶
func (b *Brief) TargetsForScene(scene string) []BriefPlaytestTarget
TargetsForScene returns the playtest targets defined in b that apply to scene. Targets with an empty Scene apply to every scene; when both a global target and a scene-specific target exist for the same metric, the scene-specific target takes precedence. When scene is empty, all targets are returned in declaration order.
type BriefArt ¶
type BriefArt struct {
// Direction optionally describes visual direction inline under art.direction.
Direction string `yaml:"direction,omitempty"`
// References lists pinned project-relative reference images included with every agent request.
References []BriefArtReference `yaml:"references,omitempty"`
}
BriefArt holds structured art direction notes and pinned project-relative reference images.
type BriefArtReference ¶
type BriefArtReference struct {
// Path is the project-relative slash path to the reference image (for example "art/reference/spikes_ref.png").
Path string `yaml:"path" schema:"required,minLength=1"`
// Note is an optional short description of what the reference illustrates.
Note string `yaml:"note,omitempty"`
}
BriefArtReference names one pinned reference image listed under art.references in brief.yaml.
type BriefFeel ¶
type BriefFeel struct {
// Summary describes target game feel, controls responsiveness, and difficulty pacing in plain language.
Summary string `yaml:"summary,omitempty"`
// Targets lists structured playtest targets readable by playtest runners and the editor.
Targets []BriefPlaytestTarget `yaml:"targets,omitempty"`
}
BriefFeel describes game feel, difficulty expectations, and machine-readable playtest targets.
type BriefPlaytestTarget ¶
type BriefPlaytestTarget struct {
// Metric is the playtest metric name this target constrains, such as "median_time", "deaths", or "finished".
Metric string `yaml:"metric" schema:"required,minLength=1"`
// Scene optionally restricts this target to a specific scene or level name, such as "floor_01".
Scene string `yaml:"scene,omitempty"`
// Summary is an optional human-readable description of the target, such as "2–4 deaths on floor 3".
Summary string `yaml:"summary,omitempty"`
// Unit is an optional display unit, such as "s", "ms", or "%".
Unit string `yaml:"unit,omitempty"`
// Min is the inclusive lower bound (value >= Min).
Min *float64 `yaml:"min,omitempty"`
// Max is the inclusive upper bound (value <= Max).
Max *float64 `yaml:"max,omitempty"`
// Equal requires value == Equal.
Equal *float64 `yaml:"equal,omitempty"`
}
BriefPlaytestTarget declares one measurable playtest target in brief.yaml's feel and difficulty section.
type BriefSection ¶
type BriefSection string
BriefSection identifies a top-level section of brief.yaml checked for completeness ("gaps").
const ( BriefSectionPitch BriefSection = "pitch" BriefSectionGenre BriefSection = "genre" BriefSectionPlatforms BriefSection = "platforms" BriefSectionArtDirection BriefSection = "artDirection" BriefSectionFeel BriefSection = "feel" BriefSectionToneAndAudio BriefSection = "toneAndAudio" )
type Budgets ¶
type Budgets struct {
// QualityProfile names the quality preset frameTimeP95Ms is measured at (for example "low", "medium", or "high"); empty defaults to "low".
QualityProfile string `yaml:"qualityProfile,omitempty"`
// DownloadSizeMB is the maximum acceptable release download size in megabytes; 0 leaves it unset.
DownloadSizeMB float64 `yaml:"downloadSizeMB,omitempty" schema:"minimum=0"`
// FrameTimeP95Ms is the maximum acceptable 95th-percentile frame time in milliseconds; 0 leaves it unset.
FrameTimeP95Ms float64 `yaml:"frameTimeP95Ms,omitempty" schema:"minimum=0"`
}
Budgets holds release size and performance thresholds checked against each built package.
type Bus ¶
type Bus struct {
// Name is the mixer group, such as "music" or "sfx".
Name string `yaml:"name" schema:"required"`
// Volume is the default volume in [0, 1] until the player sets one; nil leaves it at 1.
Volume *float32 `yaml:"volume,omitempty" schema:"minimum=0,maximum=1"`
// Effects is the bus's DSP chain, applied in order.
Effects []Effect `yaml:"effects,omitempty"`
}
Bus is one sound.Mixer group: its default volume and its DSP effect chain.
func (Bus) Chain ¶
func (b Bus) Chain() sound.EffectChain
Chain returns the bus's effects as a sound.EffectChain, nil without any.
type Delay ¶
type Delay struct {
// Time is the echo spacing, such as 250ms; it must be positive.
Time time.Duration `yaml:"time" schema:"required"`
// Feedback is the feedback gain in [0, 0.99].
Feedback float64 `yaml:"feedback,omitempty" schema:"minimum=0,maximum=0.99"`
// Wet is the wet mix level in [0, 1].
Wet float64 `yaml:"wet,omitempty" schema:"minimum=0,maximum=1"`
}
Delay is a feedback delay line (sound.Delay).
type Display ¶
type Display struct {
// Width is the virtual canvas width in game points; it must be positive.
Width float32 `yaml:"width" schema:"required,exclusiveMinimum=0"`
// Height is the virtual canvas height in game points; it must be positive.
Height float32 `yaml:"height" schema:"required,exclusiveMinimum=0"`
// Mode is how the canvas fits a window of another aspect ratio: "fit" (the default when empty), "fill", "stretch" or "expand", as screen.Mode names them.
Mode string `yaml:"mode,omitempty" schema:"enum=fit|fill|stretch|expand"`
// IntegerScale scales by whole multiples only, as screen.Viewport.IntegerScale does.
IntegerScale bool `yaml:"integerScale,omitempty"`
// PixelSnap aligns the canvas to whole points, as screen.Viewport.PixelSnap does.
PixelSnap bool `yaml:"pixelSnap,omitempty"`
// BarColor is the CSS color of letterbox and pillarbox bars, parsed with core.ParseColor; empty is opaque black.
BarColor string `yaml:"barColor,omitempty"`
}
Display is the virtual resolution a screen.Viewport maps onto the window.
type Editor ¶
type Editor struct {
// Plugins names the editor plugins the scene editor turns on for this project, in the order their panels and tools appear. A plugin is Go code built into the editor binary (editor.Plugin), so this list only turns plugins on; each name is unique and has no spaces or control characters.
Plugins []string `yaml:"plugins,omitempty,flow"`
}
Editor is the scene editor's settings for one project.
type Effect ¶
type Effect struct {
// LowPass is a biquad low-pass filter.
LowPass *Filter `yaml:"lowPass,omitempty,flow"`
// HighPass is a biquad high-pass filter.
HighPass *Filter `yaml:"highPass,omitempty,flow"`
// Delay is a feedback delay line.
Delay *Delay `yaml:"delay,omitempty,flow"`
// Reverb is a Freeverb-style reverb.
Reverb *Reverb `yaml:"reverb,omitempty,flow"`
// Gain scales every sample by a non-negative factor.
Gain *Gain `yaml:"gain,omitempty,flow"`
// Bitcrush quantizes bit depth and sample rate.
Bitcrush *Bitcrush `yaml:"bitcrush,omitempty,flow"`
}
Effect is one DSP effect on a bus; exactly one field must be set.
type Entry ¶
type Entry struct {
// Name uniquely identifies the entry within its list.
Name string `yaml:"name" schema:"required"`
// Path is the file's slash-separated path relative to the project root, as fs.ValidPath accepts it.
Path string `yaml:"path" schema:"required"`
}
Entry is one autoloaded file.
type Export ¶
type Export struct {
// Output is the directory builds are written to; empty is NSGo's default (dist).
Output string `yaml:"output,omitempty"`
// Budgets are optional release thresholds checked before and after each build (download size and frame time p95 at a quality profile).
Budgets *Budgets `yaml:"budgets,omitempty"`
// Presets are the platforms the game exports to, in build order.
Presets []Preset `yaml:"presets,omitempty"`
}
Export holds the build output directory, optional release budgets, and one export preset per platform.
type File ¶
type File struct {
// Version is the schema version; it must equal CurrentVersion (1).
Version int `yaml:"version" schema:"required"`
// Name is the game's display name, which nsgo.yaml's name follows.
Name string `yaml:"name" schema:"required"`
// ID is the game's reverse-DNS application identifier, such as dev.nsgo.game.examples.caverun, which nsgo.yaml's id follows.
ID string `yaml:"id" schema:"required"`
// AppVersion is the game's release version, such as 0.1.0, which nsgo.yaml's version follows.
AppVersion string `yaml:"appVersion" schema:"required"`
// Window is the main window's size, limits, title and appearance.
Window Window `yaml:"window" schema:"required"`
// Display is the virtual resolution the game draws at; nil draws at the window's own size.
Display *Display `yaml:"display,omitempty"`
// Input is the input map bound into an input.Actions; nil binds nothing.
Input *Input `yaml:"input,omitempty"`
// Audio holds the master volume and the audio buses a sound.Mixer is configured with; nil configures nothing.
Audio *Audio `yaml:"audio,omitempty"`
// Physics holds the default 2D and 3D gravity, solver iterations and named collision layers shared by scenes; nil uses each engine's defaults.
Physics *Physics `yaml:"physics,omitempty"`
// Autoload lists the scenes and resources loaded at startup; nil loads nothing.
Autoload *Autoload `yaml:"autoload,omitempty"`
// Export holds the build output directory and the export presets per platform, which nsgo.yaml's build section follows; nil leaves nsgo.yaml without them.
Export *Export `yaml:"export,omitempty"`
// Editor holds the scene editor's settings for this project; nil uses its defaults.
Editor *Editor `yaml:"editor,omitempty"`
// Assets declares the atlases, textures, audio, fonts, models and asset manifest game assets builds; nil declares none.
Assets *Assets `yaml:"assets,omitempty"`
Navigation *Navigation `yaml:"navigation,omitempty"`
// Packs records the library packs installed into the project, in the order they were first installed: the files each wrote and the autoload entries and editor plugins each added, so that a later install of the pack can update it and a removal can undo it (see the tooling/library package). nil records none.
Packs []Pack `yaml:"packs,omitempty"`
}
File is the root of a versioned game.yaml project file.
func Check ¶
Check reads the project at the root of fsys and reports every problem a person should fix before running or building it, joined with errors.Join: a game.yaml that fails Parse, an nsgo.yaml beside it that disagrees with it (CheckNSGo), an autoloaded scene or resource that is missing or, for a scene, invalid (LoadAutoloads), and a file an installed pack wrote (File.Packs) that is missing. It returns the parsed file whenever game.yaml parses, so a caller can go on with it after reporting the rest. A project without an nsgo.yaml has nothing to disagree with.
func MustParse ¶
MustParse is Parse for a project file that is part of the program, such as an embedded game.yaml: it panics on an invalid file.
func Parse ¶
Parse decodes a YAML project file and validates it. Unknown fields and trailing YAML documents are refused.
func (*File) Appearance ¶
func (f *File) Appearance() core.Appearance
Appearance returns the appearance the app starts in, as nsgo.Appearance takes it: core.AppearanceSystem when Window.Appearance is empty.
func (*File) BindInput ¶
BindInput binds every action with bindings, axis, motion axis and gamepad axis of the input map into a, replacing a's bindings of the same names and leaving others, such as ones the game binds in code, as they are. When any action declares an Assist block, BindInput also registers each declared action's input.ActionAssist on a so undeclared actions (such as menu controls) are never latched by player assists.
func (*File) BuildTargets ¶
BuildTargets returns the NSGo build targets of every export preset in order: each preset's Targets, or its platform name when it lists none. It returns nil without export presets.
func (*File) CheckNSGo ¶
CheckNSGo reports the fields of nsgoYAML, an nsgo.yaml's contents, that disagree with f: name, id, version, appearance, build.output and build.targets, which game.yaml owns. For build.targets, both the portable cross-host targets (written by SyncNSGo) and the full BuildTargets list are accepted. It returns nil when they all agree.
func (*File) Clone ¶
Clone returns a deep copy of f, which Validate accepts exactly when it accepts f.
func (*File) ConfigureMixer ¶
ConfigureMixer gives m the default master volume and each bus's default volume and DSP chain. Volumes the player kept in storage win over the defaults. A bus without effects leaves the chain the game set in code, as BindInput leaves the bindings of an action without any.
func (*File) ConfigurePhysics3DWorld ¶
ConfigurePhysics3DWorld applies the project's 3D gravity and solver iterations to w.
func (*File) ConfigurePhysicsWorld ¶
ConfigurePhysicsWorld applies the project's 2D gravity to w when Physics.Gravity2D is set.
func (*File) ConfigureRigidWorld ¶
func (f *File) ConfigureRigidWorld(w *physics.RigidWorld)
ConfigureRigidWorld applies the project's 2D gravity and solver iterations to w.
func (*File) EachPath ¶
EachPath calls visit with every non-empty path f holds to a file or folder of the project, as PathRefs lists them, so that visit can read or change it in place, as a tool that moves a file does.
func (*File) LDtkOptions ¶
func (f *File) LDtkOptions(resolveImage func(relPath string) core.ImageSource) tilemap.LDtkOptions
LDtkOptions builds a tilemap.LDtkOptions using f's physics.ldtkIntGrid rules and resolveImage.
func (*File) LoadAutoloads ¶
LoadAutoloads reads every autoloaded scene and resource from fsys, the project root, parsing and validating the scenes. It fails on the first file that is missing or, for a scene, invalid.
func (*File) PhysicsLayerTable ¶
func (f *File) PhysicsLayerTable() *sceneformat.PhysicsLayerTable
PhysicsLayerTable returns the project's named collision layer table, or nil when File.Physics is nil.
func (*File) PhysicsSettings ¶
func (f *File) PhysicsSettings() *sceneformat.PhysicsSettings
PhysicsSettings converts File.Physics into a *sceneformat.PhysicsSettings for sceneformat.BuildPhysics. It returns nil when f or f.Physics is nil.
func (*File) PortableBuildTargets ¶
PortableBuildTargets returns the subset of BuildTargets that every host can build with plain `nsgo build` (omitting Apple targets and android_x64). It returns nil when BuildTargets has no portable targets.
func (*File) Region ¶
Region returns the first region bound to action, as a game draws its on-screen control there, and false when the action has no region binding.
func (*File) SyncNSGo ¶
SyncNSGo returns nsgoYAML, an nsgo.yaml's contents (empty for a new one), with the fields game.yaml owns set from f: name, id, version, appearance, build.output and build.targets (filtered to cross-host targets when any preset is portable so plain `nsgo build` succeeds on every host). Fields f leaves empty are removed; every other key and comment is kept.
func (*File) Viewport ¶
Viewport returns the screen.Viewport of the virtual resolution, and false without a Display.
func (*File) WindowConstraints ¶
func (f *File) WindowConstraints() core.WindowConstraints
WindowConstraints returns the main window's size limits and whether the user may resize it, as nsgo.WindowConstraints takes them.
func (*File) WindowSize ¶
WindowSize returns the main window's starting content size, as nsgo.WindowSize takes it: nsgo.WindowSize(f.WindowSize()).
type Filter ¶
type Filter struct {
// CutoffHz is the cutoff frequency in hertz; it must be positive.
CutoffHz float64 `yaml:"cutoffHz" schema:"required,exclusiveMinimum=0"`
// Q is the filter's quality factor; 0 is Butterworth.
Q float64 `yaml:"q,omitempty" schema:"minimum=0"`
}
Filter is a biquad low-pass or high-pass filter (sound.LowPass, sound.HighPass).
type FontTarget ¶
type FontTarget struct {
// In is the .ttf or .otf font file, or a folder of PNG glyph images when the path has no .ttf or .otf extension.
In string `yaml:"in"`
// Out is the .fnt file written; the pages are written beside it.
Out string `yaml:"out"`
// Size is the font size in pixels the glyphs are drawn at; 0 is DefaultFontSize. A folder of glyph images keeps its images' pixels instead.
Size int `yaml:"size,omitempty"`
// Chars are the characters baked, each once, in any order; empty is DefaultFontChars. A character the font has no glyph for is left out. A folder of glyph images bakes every image it holds instead.
Chars string `yaml:"chars,omitempty"`
// Padding is the transparent gap around each glyph on the pages in pixels; nil is 1.
Padding *int `yaml:"padding,omitempty"`
// Glyphs maps a glyph image's slash-separated path relative to In to the character it draws, for images whose base name's stem is not one character, such as "plus.png": "+". A folder input only takes it.
Glyphs map[string]string `yaml:"glyphs,omitempty"`
// Spacing is the extra advance in pixels after each glyph of a folder input.
Spacing int `yaml:"spacing,omitempty"`
// Align is where each glyph of a folder input sits in the line: "top", "center" or "bottom"; empty is "bottom".
Align string `yaml:"align,omitempty"`
}
FontTarget is one TrueType or OpenType font, or one folder of PNG glyph images, baked into an AngelCode BMFont, which text.LoadBMFont reads: a text .fnt file and the PNG pages its glyphs are packed on, named after it, such as hud.png beside hud.fnt, or hud-0.png, hud-1.png and so on when the glyphs need several pages.
func (FontTarget) FontPages ¶
func (t FontTarget) FontPages() (dir, name string)
FontPages returns the slash-separated folder a font target writes its pages to and the name they are named after: Out's folder and its base name without the .fnt extension.
func (FontTarget) GlyphFolder ¶
func (t FontTarget) GlyphFolder() bool
GlyphFolder reports whether the font target bakes from a folder of PNG glyph images rather than a TrueType or OpenType font file: In has no .ttf or .otf extension.
type Gain ¶
type Gain struct {
// Factor is the non-negative linear gain multiplier.
Factor float64 `yaml:"factor" schema:"required,minimum=0"`
}
Gain scales every sample by Factor (sound.Gain), which must be finite and non-negative.
type GamepadAxis ¶
type GamepadAxis struct {
// Name uniquely identifies the gamepad axis.
Name string `yaml:"name" schema:"required"`
// Axis is "leftX", "leftY", "rightX" or "rightY".
Axis string `yaml:"axis" schema:"required,enum=leftX|leftY|rightX|rightY"`
// DeadZone is the stick deflection below which the axis reads 0, strictly less than 1; 0 uses input.DefaultGamepadDeadZone and a negative value turns the dead zone off.
DeadZone float64 `yaml:"deadZone,omitempty" schema:"exclusiveMaximum=1"`
// Axial applies DeadZone to this axis alone instead of radially over both axes of the stick.
Axial bool `yaml:"axial,omitempty"`
// Sensitivity multiplies the dead-zoned reading before clamping to [-1, 1]; 0 uses 1.
Sensitivity float64 `yaml:"sensitivity,omitempty" schema:"minimum=0"`
// Invert negates the resulting axis value.
Invert bool `yaml:"invert,omitempty"`
}
GamepadAxis is a named axis read from a connected game controller's analog stick, as input.Actions.BindGamepadAxis binds it.
type Input ¶
type Input struct {
// Actions are the named actions in the order they are declared.
Actions []Action `yaml:"actions,omitempty"`
// Axes are the named axes, each reading -1 for its negative action and +1 for its positive one.
Axes []Axis `yaml:"axes,omitempty"`
// MotionAxes are the named axes read from the device's tilt and gyroscope.
MotionAxes []MotionAxis `yaml:"motionAxes,omitempty"`
// GamepadAxes are the named axes read from a connected game controller's analog sticks.
GamepadAxes []GamepadAxis `yaml:"gamepadAxes,omitempty"`
}
Input is a game's input map: named actions with their physical bindings, axes over pairs of actions, device motion axes and game controller stick axes.
type LDtkIntGridRule ¶
type LDtkIntGridRule struct {
// Name matches an LDtk IntGrid value identifier or IntGrid value group identifier (case-insensitive).
Name string `yaml:"name,omitempty"`
// Value matches a positive numeric LDtk IntGrid value (1, 2, ...).
Value int `yaml:"value,omitempty" schema:"minimum=0"`
// Solid sets tilemap.TileSolid on matching IntGrid cells.
Solid bool `yaml:"solid,omitempty"`
// OneWay sets tilemap.TileOneWay on matching IntGrid cells.
OneWay bool `yaml:"oneWay,omitempty"`
// Flags sets additional game-defined tilemap.TileFlags bits on matching IntGrid cells alongside Solid and OneWay.
Flags uint32 `yaml:"flags,omitempty"`
}
LDtkIntGridRule maps one LDtk IntGrid value (by identifier/group name or positive numeric value) to tile collision flags. Exactly one of Name or Value must be set; leaving Solid, OneWay, and Flags all unset explicitly maps matching cells to 0 (non-colliding).
func (LDtkIntGridRule) TileFlags ¶
func (r LDtkIntGridRule) TileFlags() tilemap.TileFlags
TileFlags returns the combined tilemap.TileFlags produced by r.
type Loaded ¶
type Loaded struct {
// MainScene is the name of the scene the game starts in, empty when the project names none.
MainScene string
// Scenes are the parsed and validated autoloaded scenes by name.
Scenes map[string]*sceneformat.SceneDoc
// Resources are the autoloaded resources' bytes by name.
Resources map[string][]byte
}
Loaded holds the autoloaded scenes and resources of a project.
func (*Loaded) Main ¶
func (l *Loaded) Main() *sceneformat.SceneDoc
Main returns the main scene, nil when the project names none.
type ManifestTarget ¶
type ManifestTarget struct {
// In is the assets folder scanned.
In string `yaml:"in"`
// Out is the .go file written.
Out string `yaml:"out"`
// Package is the generated file's package name; empty is "assets".
Package string `yaml:"package,omitempty"`
// Prefix is prepended to each asset's path to form its URI; empty is "asset:".
Prefix string `yaml:"prefix,omitempty"`
// Embed emits //go:embed directives instead of URI references.
Embed bool `yaml:"embed,omitempty"`
// EmbedDir is prepended to the //go:embed patterns.
EmbedDir string `yaml:"embedDir,omitempty"`
}
ManifestTarget is the typed Go asset manifest generated from a folder of assets, as game manifest generates it.
type ModelTarget ¶
type ModelTarget struct {
// In is the .gltf or .glb file; the buffers and images it references by relative path are read beside it.
In string `yaml:"in"`
// Out is the .glb file written.
Out string `yaml:"out"`
// Scale multiplies the size of every scene of the model, such as 0.01 for a model exported in centimeters; 0 is 1.
Scale float64 `yaml:"scale,omitempty"`
// Animations keeps the model's animations when true and leaves them out when false; nil is true.
Animations *bool `yaml:"animations,omitempty"`
}
ModelTarget is one glTF model packed into a single binary glTF (.glb) file: its buffers merged into the file's binary chunk and the images it references by file embedded, so the game loads one file.
type MotionAxis ¶
type MotionAxis struct {
// Name uniquely identifies the motion axis.
Name string `yaml:"name" schema:"required"`
// Axis is "tiltX", "tiltY", "tiltZ", "gyroX", "gyroY" or "gyroZ".
Axis string `yaml:"axis" schema:"required,enum=tiltX|tiltY|tiltZ|gyroX|gyroY|gyroZ"`
// DeadZone is the sensor dead zone in [0, 1); 0 takes input.MotionAxisOptions' default.
DeadZone float64 `yaml:"deadZone,omitempty" schema:"minimum=0,exclusiveMaximum=1"`
// Sensitivity scales the reading; 0 takes input.MotionAxisOptions' default.
Sensitivity float64 `yaml:"sensitivity,omitempty" schema:"minimum=0"`
// MaxRange is the full-deflection sensor range; 0 takes input.MotionAxisOptions' default.
MaxRange float64 `yaml:"maxRange,omitempty" schema:"minimum=0"`
// Smoothing is the low-pass smoothing factor in [0, 1); 0 disables smoothing.
Smoothing float64 `yaml:"smoothing,omitempty" schema:"minimum=0,exclusiveMaximum=1"`
// Invert negates the resulting axis value.
Invert bool `yaml:"invert,omitempty"`
}
MotionAxis is a named axis read from a device motion sensor, as input.Actions.BindMotionAxis binds it.
type NavAgent ¶
type NavAgent struct {
Name string `yaml:"name"`
Radius float32 `yaml:"radius,omitempty"`
Height float32 `yaml:"height,omitempty"`
MaxSlope float32 `yaml:"maxSlope,omitempty"`
MaxClimb float32 `yaml:"maxClimb,omitempty"`
}
NavAgent is one agent type navigation meshes are baked for, as navbake3d.AgentType defines it; each size 0 or omitted takes navbake3d's default.
type Navigation ¶
type Navigation struct {
CellSize float32 `yaml:"cellSize,omitempty"`
CellHeight float32 `yaml:"cellHeight,omitempty"`
MinRegionArea float32 `yaml:"minRegionArea,omitempty"`
MaxEdgeLength float32 `yaml:"maxEdgeLength,omitempty"`
MaxSimplificationError float32 `yaml:"maxSimplificationError,omitempty"`
MaxVertsPerPoly int `yaml:"maxVertsPerPoly,omitempty"`
DetailSampleDistance float32 `yaml:"detailSampleDistance,omitempty"`
DetailSampleMaxError float32 `yaml:"detailSampleMaxError,omitempty"`
Agents []NavAgent `yaml:"agents,omitempty"`
}
Navigation is the navigation mesh bake settings of a project, as navbake3d.Settings defines them: each field 0 or omitted takes navbake3d's default. The scene's own layers are all baked.
type Pack ¶
type Pack struct {
// Name identifies the pack in its library: lower-case ASCII letters, digits and '-', starting with a letter or digit.
Name string `yaml:"name" schema:"required"`
// Kind is one of PackKinds.
Kind string `yaml:"kind" schema:"required,enum=asset|plugin|template"`
// PackVersion is the version of the pack that was installed, such as 1.2.0.
PackVersion string `yaml:"packVersion" schema:"required"`
// SHA256 is the pack's digest, 64 lower-case hexadecimal digits, which tells one release of the pack from another whatever its version says.
SHA256 string `yaml:"sha256" schema:"required"`
// Dir is the slash-separated directory inside the project the pack's files were written to.
Dir string `yaml:"dir" schema:"required"`
// Files are the slash-separated paths of the pack's files relative to Dir, sorted and unique.
Files []string `yaml:"files,omitempty"`
// Scenes names the autoload scenes the install added.
Scenes []string `yaml:"scenes,omitempty,flow"`
// Resources names the autoload resources the install added.
Resources []string `yaml:"resources,omitempty,flow"`
// Plugins names the editor plugins the install turned on.
Plugins []string `yaml:"plugins,omitempty,flow"`
}
Pack is one library pack installed into the project. Its files are Dir joined with each of Files, and Scenes, Resources and Plugins name the autoload entries and editor plugins the install added, which must still be in the file; an entry or plugin the project held before the install is not the pack's and is not listed.
type PathRef ¶
type PathRef struct {
// Field says what the path is, one of the Field constants, such as FieldAtlasIn.
Field string
// Node is the YAML scalar that writes the path in the document PathRefs parsed: its Value is the path, and its Line and Column say where it is written.
Node *yaml.Node
// Dir reports whether the path names a folder rather than a file.
Dir bool
// Output reports whether the path need not exist before game assets runs: what a tool writes, such as an asset target's out, and the manifest's in, the folder the other targets usually write into.
Output bool
}
PathRef is one path a project file holds to a file or folder of the project, slash-separated and relative to the project root.
type Physics ¶
type Physics struct {
// Gravity2D is the 2D gravity acceleration in points per second squared (for example {y: 980} in +Y-down screen space); nil leaves 2D gravity at (0, 0).
Gravity2D *Vec2 `yaml:"gravity2D,omitempty,flow"`
// Gravity3D is the 3D gravity acceleration in units per second squared (for example {y: -9.81} in Y-up 3D space); nil leaves 3D gravity at physics3d's default (0, -9.81, 0).
Gravity3D *Vec3 `yaml:"gravity3D,omitempty,flow"`
// SolverIterations2D is the number of sequential-impulse iterations per 2D rigid step; 0 uses physics.DefaultSolverIterations.
SolverIterations2D int `yaml:"solverIterations2D,omitempty" schema:"minimum=0"`
// SolverIterations3D is the number of solver iterations per 3D physics step; 0 uses physics3d's default.
SolverIterations3D int `yaml:"solverIterations3D,omitempty" schema:"minimum=0"`
// Layers maps human-readable collision layer names (such as "player", "walls", and "coins") to bit indices in [0, 31], in declaration order.
Layers []PhysicsLayer `yaml:"layers,omitempty"`
// LDtkIntGrid maps LDtk IntGrid value identifiers, group identifiers, or numeric values to tilemap.TileFlags when loading .ldtk projects.
LDtkIntGrid []LDtkIntGridRule `yaml:"ldtkIntGrid,omitempty"`
}
Physics holds the project's default 2D and 3D gravity, solver iterations, named collision layers, and LDtk IntGrid collision flag mappings shared by scenes.
func (*Physics) LDtkOptions ¶
func (p *Physics) LDtkOptions(resolveImage func(relPath string) core.ImageSource) tilemap.LDtkOptions
LDtkOptions builds a tilemap.LDtkOptions using p's LDtkIntGrid rules and resolveImage.
func (*Physics) LayerBit ¶
LayerBit returns the bit index in [0, 31] assigned to name, and false when p is nil or name is not declared.
func (*Physics) LayerMask2D ¶
LayerMask2D resolves layer names into a 2D physics.LayerMask.
func (*Physics) LayerMask3D ¶
LayerMask3D resolves layer names into a 3D physics3d.LayerMask.
func (*Physics) LayerTable ¶
func (p *Physics) LayerTable() *sceneformat.PhysicsLayerTable
LayerTable returns p's declared layers as a *sceneformat.PhysicsLayerTable, or nil when p is nil.
type PhysicsLayer ¶
type PhysicsLayer struct {
// Name uniquely identifies the collision layer, such as "player", "walls", or "coins".
Name string `yaml:"name" schema:"required"`
// Bit is the collision bit index in [0, 31], matching LayerBit(Bit).
Bit int `yaml:"bit" schema:"minimum=0,maximum=31"`
}
PhysicsLayer assigns a human-readable collision layer name to a bit index in [0, 31].
type Preset ¶
type Preset struct {
// Platform is one of Platforms, such as "web" or "macos".
Platform string `yaml:"platform" schema:"required,enum=macos|windows|linux|ios|tvos|watchos|android|harmonyos|web|miniprogram"`
// Targets are the NSGo build targets of the platform to build, such as macos_arm64; empty builds the platform name itself, which NSGo expands to its default targets.
Targets []string `yaml:"targets,omitempty,flow"`
}
Preset is the export preset of one platform.
type Rect ¶
type Rect struct {
// X is the horizontal origin in virtual points.
X float32 `yaml:"x,omitempty"`
// Y is the vertical origin in virtual points.
Y float32 `yaml:"y,omitempty"`
// Width is the rectangle's width in virtual points; it must be positive.
Width float32 `yaml:"width" schema:"required,exclusiveMinimum=0"`
// Height is the rectangle's height in virtual points; it must be positive.
Height float32 `yaml:"height" schema:"required,exclusiveMinimum=0"`
}
Rect is an axis-aligned rectangle with a positive size.
type Resolver ¶
type Resolver struct {
// contains filtered or unexported fields
}
Resolver loads a project's assets from its files, as the scene editor and the game read them: the sprite atlases, scene files, materials, physics materials, YAML tilesets and Tiled and LDtk maps a scene names. It is a sceneformat.AssetResolver that also implements sceneformat.SceneResolver, sceneformat.MaterialResolver, sceneformat.PhysicsMaterialResolver and sceneformat.FileResolver, and it lists the project's atlases (AtlasNames) for the editor's asset browser.
A scene names an atlas the way `game check` (package assetcheck) finds it: the name is the path of an atlas JSON file without its .json extension, either from the project root or as the file's base name, and when several atlases match, the one nearest the scene wins (NearestAtlases). An atlas JSON is a JSON file with top-level frames and meta objects, as TexturePacker and Aseprite export them; its meta.image is read from the project relative to the JSON file, so the atlas draws the project's own image. Scene files, materials, tilesets and tilemap sources are paths from the project root.
The walk for atlases skips the directories the go command skips (names starting with "." or "_", and testdata) and the directories of other projects, those holding a game.yaml, nsgo.yaml or go.mod of their own. A Resolver lists the atlases and parses each one once, then serves them until Refresh; scene files and the files ReadFile reads are read again on every request, so a scene saved since is seen at once. A Resolver is safe for use by multiple goroutines.
Example ¶
A Resolver over a project's files builds its scenes with the project's own atlases, found by name nearest the scene as `game check` finds them.
package main
import (
"fmt"
"testing/fstest"
"github.com/nsgo-dev/game/pkg/project"
"github.com/nsgo-dev/game/pkg/sceneformat"
)
func main() {
fsys := fstest.MapFS{
"sprites/actors.json": {Data: []byte(`{"frames": {"hero": {"frame": {"x": 0, "y": 0, "w": 16, "h": 16}}}, "meta": {"image": "actors.png"}}`)},
"sprites/actors.png": {Data: []byte("the packed image")},
"scenes/room.scene.yaml": {Data: []byte(`version: 2
layers:
- name: actors
objects:
- id: hero
sprite: {atlas: actors, frame: hero}
`)},
}
r := project.NewResolver(fsys).ForScene("scenes/room.scene.yaml")
fmt.Println(r.AtlasNames())
doc, err := r.Scene("scenes/room.scene.yaml")
if err != nil {
fmt.Println(err)
return
}
built, err := sceneformat.Build(doc, r)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s\n", built.Object("hero").Atlas.Image.Data)
}
Output: [actors] the packed image
func NewResolver ¶
NewResolver returns a Resolver over fsys, the project's files with paths from its root, such as os.DirFS of the directory holding game.yaml. It finds atlases nearest the project root; ForScene returns one that finds them nearest a scene.
func (*Resolver) Atlas ¶
Atlas returns the atlas name names, found as Resolver describes. It fails when no atlas matches, when several match at the same distance (name it by its path from the project root instead), and when the matching file or its image does not load.
func (*Resolver) AtlasNames ¶
AtlasNames returns the names a scene can give the project's atlases, sorted: each atlas's base name when that name finds it from r's scene, as Atlas would, and otherwise its path from the project root without .json. It lists an atlas that does not load too; Atlas reports why. It lets a Resolver serve as the editor's editor.AtlasLister, and returns nil when the project's files cannot be listed.
func (*Resolver) ForScene ¶
ForScene returns a Resolver over the same files and caches as r that finds atlases nearest the scene file at scenePath, a slash-separated path from the project root such as "scenes/level.scene.yaml", as `game check` finds a scene's atlases. An empty or invalid scenePath finds them nearest the project root.
func (*Resolver) LDtkOptions ¶
func (r *Resolver) LDtkOptions() tilemap.LDtkOptions
LDtkOptions returns the tilemap.LDtkOptions derived from game.yaml's physics.ldtkIntGrid section, if present, implementing sceneformat.LDtkOptionsResolver so scenes referencing .ldtk sources map IntGrid values from project settings.
func (*Resolver) Library ¶
Library returns the resource.Library that loads the project's materials and physics materials, so callers such as the scene editor can reload edited material files in place (resource.Library.Reload) until Refresh replaces it.
func (*Resolver) Material ¶
Material loads the material file at p, a slash-separated path from the project root, through a resource.Library shared by every Resolver over the project, so every scene that names one file gets the same value until Refresh.
func (*Resolver) PhysicsMaterial ¶
func (r *Resolver) PhysicsMaterial(p string) (*resource.PhysicsMaterial, error)
PhysicsMaterial loads the physics material file at p, a .physics.yaml that a body2d or body3d component names by its path from the project root, through the same resource.Library as Material, so sceneformat.BuildPhysics, which the editor's Play runs, finds the project's physics materials.
func (*Resolver) ReadFile ¶
ReadFile reads the file at p, a slash-separated path from the project root, so that sceneformat.Build reads through it the YAML tilesets layered tilemaps name and the Tiled and LDtk maps tilemap sources name, with the tilesets those refer to, and the editor's tile palette lists their tiles, as sceneformat.FSAssets does. Their images are left as URIs, as FSAssets leaves them.
func (*Resolver) Refresh ¶
func (r *Resolver) Refresh()
Refresh forgets the atlases, materials and physics materials r has listed and loaded, so the next request reads the project's files again: call it after the project's atlases or material files change on disk. It is shared with every Resolver ForScene returned. Until then every scene that names one material file gets the same value.
func (*Resolver) Scene ¶
func (r *Resolver) Scene(p string) (*sceneformat.SceneDoc, error)
Scene reads and parses the scene file at p, a slash-separated path from the project root, as sceneformat.FSScenes does, and names each atlas it names, by its sprites, its overrides' sprites and its inline tilemaps' tilesets, by the atlas's path from the project root without .json when the name finds one atlas nearest p. sceneformat.Build looks up every atlas of a scene and of the scenes it instances or inherits through one resolver, which finds them nearest the open scene, so without this an instanced scene in another directory would draw the atlas nearest the scene instancing it, not the one `game check` finds nearest the instanced file. A name that finds no atlas, or several, is left as it is, for Atlas to report.
type Reverb ¶
type Reverb struct {
// RoomSize controls reverb decay size in [0, 1].
RoomSize float64 `yaml:"roomSize,omitempty" schema:"minimum=0,maximum=1"`
// Damping controls high-frequency attenuation in [0, 1].
Damping float64 `yaml:"damping,omitempty" schema:"minimum=0,maximum=1"`
// Wet is the wet mix level in [0, 1].
Wet float64 `yaml:"wet,omitempty" schema:"minimum=0,maximum=1"`
}
Reverb is a Freeverb-style reverb (sound.Reverb); each field is in [0, 1].
type TextureTarget ¶
type TextureTarget struct {
// In is the source image.
In string `yaml:"in"`
// Out is the .ktx2 file written.
Out string `yaml:"out"`
// Format is one of TextureFormats; empty is rgba8.
Format string `yaml:"format,omitempty"`
// Mipmaps writes the whole mipmap chain down to 1x1.
Mipmaps bool `yaml:"mipmaps,omitempty"`
// SRGB marks the texture sRGB and filters its mipmaps in linear light.
SRGB bool `yaml:"srgb,omitempty"`
}
TextureTarget is one PNG or JPEG image encoded into a KTX2 container, as game tex encodes it.
type Vec2 ¶
type Vec2 struct {
// X is the horizontal component.
X float32 `yaml:"x,omitempty"`
// Y is the vertical component.
Y float32 `yaml:"y,omitempty"`
}
Vec2 is a two-dimensional vector in game.yaml, such as 2D gravity.
type Vec3 ¶
type Vec3 struct {
// X is the X-axis component.
X float32 `yaml:"x,omitempty"`
// Y is the Y-axis component.
Y float32 `yaml:"y,omitempty"`
// Z is the Z-axis component.
Z float32 `yaml:"z,omitempty"`
}
Vec3 is a three-dimensional vector in game.yaml, such as 3D gravity.
type Window ¶
type Window struct {
// Title is the window's title; empty uses File.Name.
Title string `yaml:"title,omitempty"`
// Width is the window's starting content width in points; it must be positive.
Width float32 `yaml:"width" schema:"required,exclusiveMinimum=0"`
// Height is the window's starting content height in points; it must be positive.
Height float32 `yaml:"height" schema:"required,exclusiveMinimum=0"`
// MinWidth is the smallest content width the user may resize the window to; 0 is no limit.
MinWidth float32 `yaml:"minWidth,omitempty" schema:"minimum=0"`
// MinHeight is the smallest content height the user may resize the window to; 0 is no limit.
MinHeight float32 `yaml:"minHeight,omitempty" schema:"minimum=0"`
// MaxWidth is the largest content width the user may resize the window to; 0 is no limit.
MaxWidth float32 `yaml:"maxWidth,omitempty" schema:"minimum=0"`
// MaxHeight is the largest content height the user may resize the window to; 0 is no limit.
MaxHeight float32 `yaml:"maxHeight,omitempty" schema:"minimum=0"`
// Resizable says whether the user may resize the window; nil defaults to true.
Resizable *bool `yaml:"resizable,omitempty"`
// Appearance starts the app "light" or "dark" whatever the system's; empty follows the system. nsgo.yaml's appearance follows it.
Appearance string `yaml:"appearance,omitempty" schema:"enum=light|dark"`
}
Window is the main window's content size in points, its size limits, its title and its appearance.