Справочник API собран из Go doc-комментариев в исходном коде и написан на английском языке.
package resource
import "github.com/nsgo-dev/game/pkg/resource"Обзор
Package resource reads, validates and writes shared resource files: reusable data that scenes and code reference by path instead of repeating it, as Godot's .tres files are.
Files
A resource file is one YAML document that starts with a common header, the resource's type, the schema version and an optional uid, followed by the fields of that type:
type: material version: 1 baseColor: "#8a8f99" opacity: 0.75 blend: multiply
The uid (Header.UID) is the file's stable ID, made once by NewUID, which stays the same when the file is renamed or moved so that package refs can find it again.
The types are material (Material), curve (Curve), gradient (Gradient), animation (Animation), theme (Theme), busLayout (BusLayout) and physicsMaterial (PhysicsMaterial). Parse reads any of them and returns the matching type; it refuses an unknown type, a version other than CurrentVersion, unknown fields, trailing documents and values out of range. Encode writes deterministic 2-space YAML with fields in a fixed order, so a file that Encode wrote reads back with Parse and encodes to the same bytes.
Sharing
A Library loads resource files from an fs.FS by slash-separated path and keeps one value per path, so every scene and every piece of code that loads the same path holds the same pointer. Library.Reload replaces a loaded resource's contents in place, so an edit to one file reaches everything that uses it; hotreload.Watcher.WatchResources calls it when a file changes on disk.
sceneformat objects reference a material by path (ObjectDoc.Material) and resolve it through a resolver such as a Library, so two scenes that use one material file both change when it is edited.
Указатель
- Константы
- func BlendModes() []string
- func Encode(r Resource) ([]byte, error)
- func LoadAs[T Resource](l *Library, path string) (T, error)
- func NewUID(r io.Reader) (string, error)
- func ParseAs[T Resource](data []byte) (T, error)
- func ValidUID(s string) bool
- type Animation
- type BitcrushEffect
- type Bus
- type BusEffect
- type BusLayout
- type Curve
- type DelayEffect
- type Event
- type FilterEffect
- type FrameKey
- type GainEffect
- type Gradient
- type GradientStop
- type Header
- type Interp
- type Key
- type Kind
- type Library
- func NewLibrary(fsys fs.FS) *Library
- func (l *Library) Animation(path string) (*Animation, error)
- func (l *Library) Load(path string) (Resource, error)
- func (l *Library) Loaded(path string) bool
- func (l *Library) Material(path string) (*Material, error)
- func (l *Library) Paths() []string
- func (l *Library) PhysicsMaterial(path string) (*PhysicsMaterial, error)
- func (l *Library) Reload(path string, data []byte) (bool, error)
- func (l *Library) ReloadFile(path string) (int64, bool, error)
- func (l *Library) Revision() uint64
- type Material
- type PhysicsMaterial
- type Resource
- type ReverbEffect
- type Theme
- type ThemeColors
- type ThemeFont
- type Track
Константы
const CurrentVersion = 1CurrentVersion is the resource schema version this package reads and writes.
Функции
func BlendModes() []stringBlendModes returns the names Material.Blend accepts, sorted: the canvas composite operations in camel case, such as "sourceOver", "multiply" and "lighter".
func Encode(r Resource) ([]byte, error)Encode validates r and writes it as deterministic 2-space YAML: the header first, then the type's fields in declaration order, omitting fields left at their defaults.
func LoadAs[T Resource](l *Library, path string) (T, error)LoadAs loads the resource at path from l and returns it as T, failing when the file holds another type.
func NewUID(r io.Reader) (string, error)NewUID returns a new UID, UIDLength characters of uidAlphabet that carry 65 random bits read from r, or from crypto/rand when r is nil. A UID is the stable ID a scene or resource file keeps in its header (SceneDoc.UID in sceneformat, Header.UID here), which stays the same when the file is renamed or moved, so the tools can find a moved file again (see package refs).
func ParseAs[T Resource](data []byte) (T, error)ParseAs parses data and returns it as T, failing when the file holds another type.
func ValidUID(s string) boolValidUID reports whether s has the form NewUID returns: UIDLength characters, each a digit or a lower-case letter other than i, l, o and u.
Типы
type Animation struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Length is the clip's length in seconds; it must be positive.
Length float32 `yaml:"length"`
// Loop plays the clip again from the start when it ends.
Loop bool `yaml:"loop,omitempty"`
// Tracks are the clip's keyed properties; each target and property pair appears once.
Tracks []Track `yaml:"tracks,omitempty"`
// Events are named cues on the clip's timeline in time order, such as a footstep sound, which a player reports as playback crosses them.
Events []Event `yaml:"events,omitempty"`
}Animation is a clip of property tracks keyed over its length, played on a scene object or node.
func (a *Animation) ClipTime(t float32) float32ClipTime maps a play time t in seconds to a time within the clip: wrapped into [0, Length) when Loop is set, clamped to [0, Length] otherwise.
func (a *Animation) Sample(t float32, set func(target, property string, value float32))Sample evaluates every numeric track at play time t (mapped through ClipTime) and calls set with each track's target, property and value, in track order. Discrete frame tracks are skipped; use SampleFrames for them.
func (a *Animation) SampleFrames(t float32, set func(target, property, frame string))SampleFrames evaluates every discrete frame track at play time t (mapped through ClipTime) and calls set with each track's target, property and frame name, in track order.
func (a *Animation) Validate() errorValidate checks the header, the length, every track and every event.
type BitcrushEffect struct {
// Bits is the bit depth from 1 to 15.
Bits int `yaml:"bits"`
// Downsample holds every Downsample-th frame; 0 or 1 does not downsample.
Downsample int `yaml:"downsample,omitempty"`
}BitcrushEffect quantizes samples and holds frames for a lo-fi sound.
type Bus struct {
// Name is the mixer group's name, such as "music" or "effects".
Name string `yaml:"name"`
// Effects is the bus's effect chain, applied in order.
Effects []BusEffect `yaml:"effects,omitempty"`
}Bus is one sound bus: a sound.Mixer group and its effects, applied in order.
func (bus *Bus) Chain() sound.EffectChainChain returns the bus's effects as a sound.EffectChain, in order.
type BusEffect struct {
// LowPass attenuates frequencies above its cutoff (sound.LowPass).
LowPass *FilterEffect `yaml:"lowPass,omitempty"`
// HighPass attenuates frequencies below its cutoff (sound.HighPass).
HighPass *FilterEffect `yaml:"highPass,omitempty"`
// Delay is a feedback echo (sound.Delay).
Delay *DelayEffect `yaml:"delay,omitempty"`
// Reverb is a room reverb (sound.Reverb).
Reverb *ReverbEffect `yaml:"reverb,omitempty"`
// Gain scales every sample (sound.Gain).
Gain *GainEffect `yaml:"gain,omitempty"`
// Bitcrush lowers bit depth and sample rate (sound.Bitcrush).
Bitcrush *BitcrushEffect `yaml:"bitcrush,omitempty"`
}BusEffect is one effect on a bus. Exactly one field must be set.
func (e *BusEffect) Effect() sound.BusEffectEffect returns the sound.BusEffect the entry describes, or nil when no field is set.
type BusLayout struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Buses are the layout's buses, each name once.
Buses []Bus `yaml:"buses,omitempty"`
}BusLayout lays out a game's sound buses: the groups a sound.Mixer plays through and the DSP effect chain on each.
func (b *BusLayout) Apply(m *sound.Mixer)Apply sets each bus's effect chain on m with sound.Mixer.SetGroupEffects; a bus with no effects clears its group's chain. Groups the layout does not name keep their chains, and volumes are left to the player's settings.
func (b *BusLayout) Validate() errorValidate checks the header, bus names and every effect's parameters.
type Curve struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Keys are the curve's keys in strictly increasing Time order; there must be at least one.
Keys []Key `yaml:"keys"`
}Curve is a value keyed over time, such as an easing, a particle's size over its life or damage over distance.
func (c *Curve) Eval(t float32) float32Eval returns the curve's value at t, holding the first and last keys' values before and after them. Its method value fits tween.EaseFunc.
func (c *Curve) Validate() errorValidate checks the header and that the keys are finite, ordered and use a known interp.
type DelayEffect struct {
// Seconds is the echo spacing; it must be positive.
Seconds float64 `yaml:"seconds"`
// Feedback is how much of each echo feeds the next, from 0 to 0.99.
Feedback float64 `yaml:"feedback,omitempty"`
// Wet is the dry/wet mix from 0 to 1.
Wet float64 `yaml:"wet"`
}DelayEffect is a feedback delay line.
type Event struct {
// Time is where the event sits, from 0 to the clip's Length; events must be in non-decreasing Time order.
Time float32 `yaml:"time"`
// Name says what happens, such as "footstep"; it must not be empty.
Name string `yaml:"name"`
}Event is one named cue on an Animation's timeline.
type FilterEffect struct {
// CutoffHz is the cutoff frequency in hertz; it must be positive.
CutoffHz float64 `yaml:"cutoffHz"`
// Q is the filter's resonance; 0 is Butterworth (1/sqrt(2)).
Q float64 `yaml:"q,omitempty"`
}FilterEffect is a low-pass or high-pass biquad filter.
type FrameKey struct {
// Time is where the frame starts, from 0 to the clip's Length; frame keys must be in strictly increasing Time order.
Time float32 `yaml:"time"`
// Frame is the atlas frame name shown from Time until the next key; it must not be empty.
Frame string `yaml:"frame"`
}FrameKey is one discrete sprite frame key on an animation Track, holding an atlas frame name from Time until the next key without interpolation.
type GainEffect struct {
// Factor is the scale; it must be finite and non-negative.
Factor float64 `yaml:"factor"`
}GainEffect scales every sample by Factor.
type Gradient struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Stops are the gradient's colors in non-decreasing Offset order; two stops at one offset make a hard edge. There must be at least one.
Stops []GradientStop `yaml:"stops"`
}Gradient is a run of colors keyed over offsets from 0 to 1, such as a particle's color over its life or a sky's color over the day.
func (g *Gradient) At(t float32) core.ColorAt returns the gradient's color at t, mixing each channel linearly between the stops around it and holding the end colors beyond them.
func (g *Gradient) CoreStops() []core.GradientStopCoreStops returns the stops as core.GradientStop values for a canvas gradient. A stop whose color does not parse is transparent.
func (g *Gradient) Validate() errorValidate checks the header and that the stops are in order with valid colors.
type GradientStop struct {
// Offset is where the color sits, from 0 to 1.
Offset float32 `yaml:"offset"`
// Color is a CSS color parsed with core.ParseColor.
Color string `yaml:"color"`
}GradientStop is one color of a Gradient.
type Header struct {
// Type names the resource's type; it must match the Go type holding it.
Type Kind `yaml:"type"`
// Version is the schema version; it must equal CurrentVersion (1).
Version int `yaml:"version"`
// UID is the file's stable ID, which stays the same when the file is renamed or moved so the tools can find it again (see package refs); empty until a tool such as game index gives it one. When set it must be a UID as NewUID returns it.
UID string `yaml:"uid,omitempty"`
}Header is the common start of every resource file: its type, schema version and stable ID. Every resource type embeds it, so Type, Version and UID are the first fields of each file.
func NewHeader(kind Kind) HeaderNewHeader returns the header for a resource of kind at CurrentVersion.
type Interp stringInterp is how a key's value moves to the next key's.
const (
// InterpLinear moves in a straight line; it is the default when a key leaves interp empty.
InterpLinear Interp = "linear"
// InterpStep holds the key's value until the next key.
InterpStep Interp = "step"
// InterpSmooth eases in and out with a smoothstep.
InterpSmooth Interp = "smooth"
)type Key struct {
// Time is where the key sits; keys must be in strictly increasing Time order.
Time float32 `yaml:"time"`
// Value is the value at Time.
Value float32 `yaml:"value"`
// Interp is how the value moves from this key to the next; empty is InterpLinear.
Interp Interp `yaml:"interp,omitempty"`
}Key is one keyed value on a Curve or a numeric animation Track.
type Kind stringKind is a resource file's type, written in its header's type field.
const (
// KindMaterial is a Material: surface color, texture, opacity and blending.
KindMaterial Kind = "material"
// KindCurve is a Curve: a value keyed over time.
KindCurve Kind = "curve"
// KindGradient is a Gradient: colors keyed over offsets from 0 to 1.
KindGradient Kind = "gradient"
// KindAnimation is an Animation: property tracks keyed over a clip's length.
KindAnimation Kind = "animation"
// KindTheme is a Theme: colors, spacing and font for gameui.
KindTheme Kind = "theme"
// KindBusLayout is a BusLayout: sound buses and their effect chains.
KindBusLayout Kind = "busLayout"
// KindPhysicsMaterial is a PhysicsMaterial: friction, bounce and damping for rigid bodies.
KindPhysicsMaterial Kind = "physicsMaterial"
)func Kinds() []KindKinds returns every resource type this package reads, in a fixed order.
type Library struct {
// contains filtered or unexported fields
}Library loads resource files from a file system and shares them: every Load of one path returns the same pointer, so the scenes and code that use a resource all see one value, and Reload changes that value in place.
Paths are slash-separated and relative to the file system's root, as fs.ValidPath requires, such as "materials/stone.material.yaml".
Load and Reload are safe to call from any goroutine, but Reload writes the shared value that readers hold, so call it on the goroutine that reads resources, usually the engine's; hotreload.Watcher.WatchResources does.
func NewLibrary(fsys fs.FS) *LibraryNewLibrary returns a Library that reads files from fsys, such as os.DirFS(projectRoot) or an embed.FS.
func (l *Library) Animation(path string) (*Animation, error)Animation loads the animation clip at path. It lets a Library serve as an animclip.ClipResolver.
func (l *Library) Load(path string) (Resource, error)Load returns the resource at path, parsing it on first use and returning the shared value after that.
func (l *Library) Loaded(path string) boolLoaded reports whether path has been loaded.
func (l *Library) Material(path string) (*Material, error)Material loads the material at path. It lets a Library serve as a sceneformat.MaterialResolver.
func (l *Library) Paths() []stringPaths returns the loaded paths, sorted.
func (l *Library) PhysicsMaterial(path string) (*PhysicsMaterial, error)PhysicsMaterial loads the physics material at path. It lets a Library serve as a sceneformat.PhysicsMaterialResolver.
func (l *Library) Reload(path string, data []byte) (bool, error)Reload parses data as the new contents of path and, when path is loaded, copies them into the shared value so every holder sees them. It reports whether path was loaded; an unloaded path is ignored. On an error, including a file that changed its type, the loaded value is left as it was.
func (l *Library) ReloadFile(path string) (int64, bool, error)ReloadFile re-reads path from the library's file system and reloads it in place via Reload. It reports the file's byte size, whether path was loaded in the library, and any read or parse error. An unloaded path returns (0, false, nil). On error, the previously loaded resource stays unchanged.
func (l *Library) Revision() uint64Revision counts the successful reloads, so code that derives values from resources, such as a gameui.Theme built with Theme.Apply, can tell when to derive them again.
type Material struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// BaseColor is a CSS color parsed with core.ParseColor; empty is opaque white.
BaseColor string `yaml:"baseColor,omitempty"`
// Texture is an optional slash-separated path to the surface's image, relative to the project root.
Texture string `yaml:"texture,omitempty"`
// Opacity multiplies the alpha of everything drawn with the material, from 0 to 1; nil is 1.
Opacity *float32 `yaml:"opacity,omitempty"`
// Blend is how the surface mixes with what is beneath (see BlendModes); empty is "sourceOver".
Blend string `yaml:"blend,omitempty"`
// Metallic is the PBR metalness from 0 to 1.
Metallic float32 `yaml:"metallic,omitempty"`
// Roughness is the PBR roughness from 0 to 1; nil is 1.
Roughness *float32 `yaml:"roughness,omitempty"`
// Emissive is an optional CSS color the surface gives off; empty is none.
Emissive string `yaml:"emissive,omitempty"`
// DoubleSided draws a 3D surface's back faces too.
DoubleSided bool `yaml:"doubleSided,omitempty"`
// Unlit draws a 3D surface in its base color without lighting.
Unlit bool `yaml:"unlit,omitempty"`
}Material describes how a surface draws: its color and texture, how opaque it is and how it blends with what is beneath. 2D sprites use Opacity and Blend; 3D renderers also read the PBR fields.
func (m *Material) BlendOp() core.CompositeOpBlendOp returns the composite operation Blend names, core.CompositeSourceOver when it is empty or unknown.
func (m *Material) Color() core.ColorColor returns the parsed base color, opaque white when BaseColor is empty or invalid.
func (m *Material) EffectiveOpacity() float32EffectiveOpacity returns Opacity, 1 when it is nil.
func (m *Material) EffectiveRoughness() float32EffectiveRoughness returns Roughness, 1 when it is nil.
func (m *Material) EmissiveColor() (core.Color, bool)EmissiveColor returns the parsed emissive color and whether the material has one.
func (m *Material) Validate() errorValidate checks the header, colors, ranges and blend mode.
type PhysicsMaterial struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Friction is the Coulomb friction coefficient; it must be finite and non-negative.
Friction *float32 `yaml:"friction,omitempty"`
// Restitution is the bounce from 0, which stops dead, to 1, which bounces back fully.
Restitution *float32 `yaml:"restitution,omitempty"`
// LinearDamping and AngularDamping slow movement and spin each second; they must be finite and non-negative.
LinearDamping *float32 `yaml:"linearDamping,omitempty"`
AngularDamping *float32 `yaml:"angularDamping,omitempty"`
}PhysicsMaterial holds the surface properties of rigid bodies: friction, bounce and damping. A field left out keeps the body's own value when applied.
func (p *PhysicsMaterial) ApplyTo(body *physics.RigidBody)ApplyTo sets the fields the material holds on body, leaving the others as they are.
func (p *PhysicsMaterial) ApplyTo3D(body *physics3d.Body)ApplyTo3D sets the fields the material holds on a 3D physics body, leaving the others as they are.
func (p *PhysicsMaterial) Kind() KindKind returns KindPhysicsMaterial.
func (p *PhysicsMaterial) Validate() errorValidate checks the header and the ranges.
type Resource interface {
// Kind returns the resource's type.
Kind() Kind
// Validate checks the header and every field against the schema.
Validate() error
// contains filtered or unexported methods
}Resource is one parsed resource file: a *Material, *Curve, *Gradient, *Animation, *Theme, *BusLayout or *PhysicsMaterial.
func New(kind Kind) (Resource, error)New returns an empty resource of kind with its header set, or an error for a kind this package does not know.
func Parse(data []byte) (Resource, error)Parse decodes one YAML resource file and validates it. It reads the header first, refuses an unknown type or unsupported version, then decodes the whole document into the matching type, refusing unknown fields and trailing documents.
type ReverbEffect struct {
// RoomSize, Damping and Wet are each from 0 to 1.
RoomSize float64 `yaml:"roomSize"`
Damping float64 `yaml:"damping,omitempty"`
Wet float64 `yaml:"wet"`
}ReverbEffect is a comb and allpass room reverb.
type Theme struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Colors holds the theme's CSS colors, each parsed with core.ParseColor.
Colors ThemeColors `yaml:"colors,omitempty"`
// Padding is the default inner padding in points.
Padding *float32 `yaml:"padding,omitempty"`
// CornerRadius is the default corner radius in points.
CornerRadius *float32 `yaml:"cornerRadius,omitempty"`
// BorderWidth is the widget border stroke width in points.
BorderWidth *float32 `yaml:"borderWidth,omitempty"`
// FocusWidth is the focus outline stroke width in points.
FocusWidth *float32 `yaml:"focusWidth,omitempty"`
// Font is the default font of text-bearing widgets.
Font *ThemeFont `yaml:"font,omitempty"`
}Theme is a UI theme for gameui: colors, spacing and font. Every field is optional; Apply overrides only the fields a file sets, so a theme file can restyle a few colors of gameui.DefaultTheme.
func (t *Theme) Apply(base gameui.Theme) gameui.ThemeApply returns base with every field the theme sets replaced. Fields the file leaves out keep base's values, as do gameui.Theme fields a file cannot hold, such as frame drawers.
func (t *Theme) Validate() errorValidate checks the header, every color, the sizes and the font.
type ThemeColors struct {
PanelBackground string `yaml:"panelBackground,omitempty"`
PanelBorder string `yaml:"panelBorder,omitempty"`
Background string `yaml:"background,omitempty"`
Hover string `yaml:"hover,omitempty"`
Active string `yaml:"active,omitempty"`
FocusedBorder string `yaml:"focusedBorder,omitempty"`
Disabled string `yaml:"disabled,omitempty"`
Border string `yaml:"border,omitempty"`
Text string `yaml:"text,omitempty"`
DisabledText string `yaml:"disabledText,omitempty"`
MutedText string `yaml:"mutedText,omitempty"`
Accent string `yaml:"accent,omitempty"`
AccentHover string `yaml:"accentHover,omitempty"`
AccentActive string `yaml:"accentActive,omitempty"`
Track string `yaml:"track,omitempty"`
}ThemeColors holds a Theme's colors, one per gameui.Theme color field; an empty one keeps the base theme's.
type ThemeFont struct {
// Family is a font family name.
Family string `yaml:"family,omitempty"`
// Size is the font size in points; 0 keeps the base theme's.
Size float32 `yaml:"size,omitempty"`
// Weight is "light", "normal", "medium", "semibold" or "bold".
Weight string `yaml:"weight,omitempty"`
// Italic sets the italic style when true; nil keeps the base theme's.
Italic *bool `yaml:"italic,omitempty"`
}ThemeFont is a Theme's default font; an empty or zero field keeps the base theme's.
type Track struct {
// Target names the object the track drives, such as the ID of an object in a scene (animclip binds it that way); empty is the object the clip plays on.
Target string `yaml:"target,omitempty"`
// Property names the property, such as "x", "rotation", "alpha" or "sprite.frame".
Property string `yaml:"property"`
// Keys are the track's numeric keys, with times from 0 to the clip's Length. A track sets either Keys or Frames, not both.
Keys []Key `yaml:"keys,omitempty"`
// Frames are the track's discrete sprite frame keys, with times from 0 to the clip's Length, stepping without interpolation. A track sets either Keys or Frames, not both.
Frames []FrameKey `yaml:"frames,omitempty"`
}Track keys one property of one target over an Animation's length: numeric values in Keys or discrete sprite frames in Frames.
func (tr *Track) Eval(t float32) float32Eval returns the numeric track's value at clip time t, holding the first and last keys' values before and after them.
func (tr *Track) EvalFrame(t float32) stringEvalFrame returns the discrete frame track's frame name at clip time t, holding the first frame before it and stepping at each key's time without interpolation.
func (tr *Track) IsFrameTrack() boolIsFrameTrack reports whether tr holds discrete sprite frame keys rather than numeric keys.