La referencia de API proviene de los comentarios de documentación de Go en el código fuente y está redactada en inglés.
package sceneformat
import "github.com/nsgo-dev/game/pkg/sceneformat"Resumen
Package sceneformat reads, validates, encodes and builds versioned YAML scene documents for NSGo games.
Editor Scope Decision
NSGo's game layer keeps Tiled and Go code first-class while growing into a lightweight scene editor built with NSGo's own UI views (option b growing into c, tracked in #159). Rather than building a monolithic IDE or locking scenes inside an opaque binary format, both hand-authored scenes and the future NSGo-native editor (object placement, tile painting, typed property editing, undo/redo, play-in-editor and asset browsing) share the human-editable YAML format defined here (#160).
Scene Documents and Runtime Building
Parse decodes a version 1 or 2 YAML scene into a SceneDoc and runs Validate to reject unknown fields, unsupported versions, duplicate layer names or object IDs, invalid coordinate spaces, malformed colors and bad transforms. Encode validates a SceneDoc and writes deterministic 2-space YAML that round-trips through Parse. A scene's optional uid (SceneDoc.UID) is its stable ID, which stays the same when the file is renamed or moved so that package refs can find it again.
Build resolves a SceneDoc's atlas and tilemap references through an AssetResolver and produces a BuiltScene holding sprite.Batch values ready to draw into a core.Drawing. BuiltScene.Draw paints the background color over the virtual viewport, applies the camera transform to world-space layers, leaves screen-space layers untransformed, and preserves exact layer order and per-layer Z order. An object may name a shared material file (ObjectDoc.Material); Build resolves it through a MaterialResolver such as resource.Library, and the object's sprite draws with the material's current opacity and blend mode, so every scene using the file follows its edits.
Node Tree
An ObjectDoc holds child objects in Children, each with a transform local to its parent (#484). Build composes the tree into BuiltObject.World and WorldAlpha and draws child sprites at their world transforms, SpawnEntities builds it into an entities.World's Hierarchy2D, and BuildNodes3D builds it into a scene3d node tree. WalkObjects visits a layer's objects depth first, each parent before its children.
Instancing and Inheritance
A version 2 scene can reuse other scene files, as Godot's scenes do (#483). An object that names a scene file in ObjectDoc.Scene instances it: the instanced scene's objects become the object's children, under IDs prefixed with the object's ID and a slash, and ObjectDoc.Overrides changes them by their IDs in that scene. A scene that names a base scene in SceneDoc.Inherits starts as a copy of the base and changes only what it declares: its own scene fields, SceneDoc.Overrides for inherited objects, SceneDoc.LayerOverrides for inherited layers, and its layers, which add objects to the base's layers of the same name or add new layers. Parse and Encode keep the references and overrides as written, so a scene of instances round-trips unchanged. Resolve loads the referenced files through a SceneResolver, such as FSScenes, refuses cycles, and returns a self-contained copy; Build resolves a scene itself when its AssetResolver also implements SceneResolver, while SpawnEntities and BuildNodes3D take a resolved scene.
Índice
- Constantes
- func Bool(v bool) *bool
- func BuildLights2D(scene *BuiltScene) (*lights2d.Scene, error)
- func BuildNavMesh2D(scene *BuiltScene) (*navbake.Mesh, *ai.NavMesh, error)
- func CheckObjectCamera3D(o *ObjectDoc) error
- func CheckObjectLight(o *ObjectDoc) error
- func CheckObjectLightProbeGrid(o *ObjectDoc) error
- func CheckObjectModel(o *ObjectDoc) error
- func CheckObjectReflectionProbe(o *ObjectDoc) error
- func CheckObjectTree(o *ObjectDoc) error
- func Encode(doc *SceneDoc) ([]byte, error)
- func EncodeConflict(doc *ConflictDoc) ([]byte, error)
- func ExtractBuiltCoverPoints(scene *BuiltScene) ([]ai.CoverPoint, error)
- func ExtractBuiltNavLinks2D(scene *BuiltScene) ([]ai.NavOffMeshLink, error)
- func ExtractBuiltNavLinks3D(scene *BuiltScene) ([]world3d.NavOffMeshLink, error)
- func ExtractCoverPoints(doc *SceneDoc) ([]ai.CoverPoint, error)
- func ExtractNavLinks2D(doc *SceneDoc) ([]ai.NavOffMeshLink, error)
- func ExtractNavLinks3D(doc *SceneDoc) ([]world3d.NavOffMeshLink, error)
- func Float32(v float32) *float32
- func Float64(v float64) *float64
- func FormatTileRow(cells []uint32) string
- func Int(v int) *int
- func IsGridMapPath(p string) bool
- func IsHDRPath(p string) bool
- func IsLightProbeGridPath(p string) bool
- func IsLights2DComponent(name string) bool
- func IsModelPath(p string) bool
- func IsNavRegion2DComponent(name string) bool
- func IsPhysicsComponent(name string) bool
- func IsSkeletalComponent(name string) bool
- func Lights2DComponentNames() []string
- func MeshPrimitives() []string
- func ObjectLocalTransform3D(o *ObjectDoc) math3d.Transform
- func ParseTileRow(row string) ([]uint32, error)
- func PhysicsComponentNames() []string
- func RegisterAnimatorComponent(reg *ComponentRegistry) error
- func RegisterCoverPoint(reg *ComponentRegistry) error
- func RegisterLights2DComponents(reg *ComponentRegistry) error
- func RegisterNavLink(reg *ComponentRegistry) error
- func RegisterNavRegion2DComponent(reg *ComponentRegistry) error
- func RegisterPhysicsComponents(reg *ComponentRegistry) error
- func RegisterSkeletalComponent(reg *ComponentRegistry) error
- func SchemaCommentFor(version int) string
- func SpawnEntities(doc *SceneDoc, w *entities.World) (map[string]entities.Entity, error)
- func String(v string) *string
- func Validate(doc *SceneDoc) error
- func ValidateComponents(doc *SceneDoc, reg *ComponentRegistry) error
- func ValidateConflict(doc *ConflictDoc) error
- func ValidateConnections(doc *SceneDoc, reg *ComponentRegistry) error
- func ValidatePhysicsLayers(doc *SceneDoc, layers *PhysicsLayerTable) error
- func WalkObjects(objs []ObjectDoc, fn func(o, parent *ObjectDoc) bool) bool
- type AnimatorConfig
- type AssetResolver
- type AtlasMap
- type BoundsDoc
- type BuiltLayer
- type BuiltObject
- type BuiltScene
- func Build(doc *SceneDoc, resolver AssetResolver) (*BuiltScene, error)
- func (s *BuiltScene) Draw(d *core.Drawing)
- func (s *BuiltScene) Layer(name string) *BuiltLayer
- func (s *BuiltScene) Object(id string) *BuiltObject
- func (s *BuiltScene) SyncLights2D() error
- func (s *BuiltScene) SyncMaterials()
- func (s *BuiltScene) SyncNavMesh2D() error
- func (s *BuiltScene) Update(dt time.Duration)
- type Call
- type Camera3DDoc
- type CameraDoc
- type Circle
- type ComponentError
- type ComponentRegistry
- func AnimatorComponentRegistry() *ComponentRegistry
- func Lights2DComponentRegistry() *ComponentRegistry
- func NavRegion2DComponentRegistry() *ComponentRegistry
- func NewComponentRegistry() *ComponentRegistry
- func PhysicsComponentRegistry() *ComponentRegistry
- func SkeletalComponentRegistry() *ComponentRegistry
- func (r *ComponentRegistry) CheckComponent(component string, value any) error
- func (r *ComponentRegistry) CheckField(component, field string, value any) (any, error)
- func (r *ComponentRegistry) Lookup(name string) (ComponentType, bool)
- func (r *ComponentRegistry) MustRegister(t ComponentType)
- func (r *ComponentRegistry) Names() []string
- func (r *ComponentRegistry) Register(t ComponentType) error
- func (r *ComponentRegistry) Resolve(component string, data map[string]any) (map[string]any, error)
- func (r *ComponentRegistry) Types() []ComponentType
- type ComponentType
- func AnimatorComponent() ComponentType
- func Body2DComponent() ComponentType
- func Body3DComponent() ComponentType
- func Collider2DComponent() ComponentType
- func Collider3DComponent() ComponentType
- func CoverPointComponent() ComponentType
- func Light2DComponent() ComponentType
- func NavLinkComponent() ComponentType
- func NavRegion2DComponent() ComponentType
- func Occluder2DComponent() ComponentType
- func SkeletalComponent() ComponentType
- func Trigger2DComponent() ComponentType
- func Trigger3DComponent() ComponentType
- func (t *ComponentType) Event(name string) (Event, bool)
- func (t *ComponentType) Field(name string) (Field, bool)
- func (t *ComponentType) FieldNames() []string
- func (t *ComponentType) Handler(name string) (Handler, bool)
- type ConflictDoc
- type ConflictKind
- type ConnectionDoc
- type ConnectionError
- type EnvironmentDoc
- func (e *EnvironmentDoc) Clone() *EnvironmentDoc
- func (e *EnvironmentDoc) EffectiveAmbientColor() string
- func (e *EnvironmentDoc) EffectiveAmbientIntensity() float32
- func (e *EnvironmentDoc) EffectiveExposure() float32
- func (e *EnvironmentDoc) EffectiveIBLIntensity() float32
- func (e *EnvironmentDoc) EffectiveTonemapping() TonemapMode
- type Event
- type FSAssets
- type FSScenes
- type Field
- type FieldError
- type FieldKind
- type FileResolver
- type FogDoc
- type FogMode
- type Handler
- type HandlerFunc
- type ImageResolver
- type LDtkOptionsResolver
- type LayerDoc
- type LayerOverride
- type Light2DDebug
- type LightDoc
- type LightKind
- type LightProbeGridDoc
- func (g *LightProbeGridDoc) Clone() *LightProbeGridDoc
- func (g *LightProbeGridDoc) EffectiveCenter() [3]float32
- func (g *LightProbeGridDoc) EffectiveCounts() [3]int
- func (g *LightProbeGridDoc) EffectiveIntensity() float32
- func (g *LightProbeGridDoc) EffectiveSize() [3]float32
- func (g *LightProbeGridDoc) LocalBounds() (lo, hi [3]float32)
- type MaterialResolver
- type MergeConflict
- type MergeResult
- type MergedItem
- type ModelResolver
- type NavRegion2DDebug
- type Nodes3D
- type ObjectDoc
- type ObjectOverride
- type ObjectRef
- type Occluder2DDebug
- type OccluderDoc
- type OccluderMode
- type ParseOptions
- type ParticlesRef
- type ParticlesResolver
- type PhysicsDebugShape2D
- type PhysicsDebugShape3D
- type PhysicsLayerDef
- type PhysicsLayerTable
- func MustPhysicsLayerTable(defs []PhysicsLayerDef) *PhysicsLayerTable
- func NewPhysicsLayerTable(defs []PhysicsLayerDef) (*PhysicsLayerTable, error)
- func (t *PhysicsLayerTable) Bit(name string) (uint, bool)
- func (t *PhysicsLayerTable) Mask2D(names ...string) (physics.LayerMask, error)
- func (t *PhysicsLayerTable) Mask3D(names ...string) (physics3d.LayerMask, error)
- func (t *PhysicsLayerTable) Names() []string
- type PhysicsMaterialResolver
- type PhysicsScene
- type PhysicsSettings
- type PhysicsTriggerEvent
- type PhysicsTriggerEventKind
- type Point
- type ProjectionKind
- type Rect
- type ReflectionProbeDoc
- func (p *ReflectionProbeDoc) Clone() *ReflectionProbeDoc
- func (p *ReflectionProbeDoc) EffectiveBoxProjection() bool
- func (p *ReflectionProbeDoc) EffectiveCenter() [3]float32
- func (p *ReflectionProbeDoc) EffectiveIntensity() float32
- func (p *ReflectionProbeDoc) EffectiveResolution() int
- func (p *ReflectionProbeDoc) EffectiveSize() [3]float32
- func (p *ReflectionProbeDoc) LocalBounds() (lo, hi [3]float32)
- type SceneDoc
- type SceneResolver
- type Signals
- func Connect(doc *SceneDoc, reg *ComponentRegistry, ctx any) (*Signals, error)
- func SpawnConnected(doc *SceneDoc, w *entities.World, reg *ComponentRegistry, ctx any) (map[string]entities.Entity, *Signals, error)
- func (s *Signals) Emit(from, event string, payload any) error
- func (s *Signals) EmitEntity(e entities.Entity, event string, payload any) error
- func (s *Signals) Enqueue(from, event string, payload any) error
- func (s *Signals) EnqueueEntity(e entities.Entity, event string, payload any) error
- func (s *Signals) Entity(id string) (entities.Entity, bool)
- func (s *Signals) Flush() error
- func (s *Signals) Pending() int
- type SkeletonResolver
- type SkyDoc
- type SkyKind
- type Space
- type SpriteRef
- type TerrainResolver
- type TileLayerDoc
- type TilemapDoc
- type TilemapResolver
- type TonemapMode
Constantes
const (
// MeshBox is a 1 by 1 by 1 cube centered on the object's origin.
MeshBox = "box"
// MeshSphere is a sphere 1 across centered on the object's origin.
MeshSphere = "sphere"
// MeshPlane is a 1 by 1 square in the object's XZ plane, centered on its origin and facing +Y.
MeshPlane = "plane"
// MeshCapsule is a capsule 1 across and 2 tall along the object's Y axis, centered on its origin.
MeshCapsule = "capsule"
// MeshCylinder is a cylinder 1 across and 1 tall along the object's Y axis, centered on its origin.
MeshCylinder = "cylinder"
)The built-in primitives ObjectDoc.Mesh names.
const (
// Light2DComponentName is the built-in 2D point or spotlight component.
Light2DComponentName = "light2d"
// Occluder2DComponentName is the built-in 2D shadow-casting occluder component (rect, polygon, or tilemap collision).
Occluder2DComponentName = "occluder2d"
)Built-in 2D lighting component type names in scene YAML files.
const (
// Body2DComponentName is the built-in 2D physics body component (static, kinematic or dynamic).
Body2DComponentName = "body2d"
// Collider2DComponentName is the built-in 2D collision shape component (box or circle).
Collider2DComponentName = "collider2d"
// Trigger2DComponentName is the built-in 2D non-solid trigger sensor component (box or circle).
Trigger2DComponentName = "trigger2d"
// Body3DComponentName is the built-in 3D physics body component (static, kinematic, dynamic, or trigger).
Body3DComponentName = "body3d"
// Collider3DComponentName is the built-in 3D collision shape component (box, sphere, capsule, cylinder, convex, trimesh, or heightfield).
Collider3DComponentName = "collider3d"
// Trigger3DComponentName is the built-in 3D non-solid trigger sensor component (box, sphere, capsule, cylinder, or convex).
Trigger3DComponentName = "trigger3d"
)Built-in physics component type names in scene YAML files.
const (
// DefaultReflectionProbeResolution is the cubemap face resolution used when ReflectionProbeDoc.Resolution is 0.
DefaultReflectionProbeResolution = 64
// MaxReflectionProbeResolution is the largest cubemap face resolution accepted in a scene file.
MaxReflectionProbeResolution = 1024
// MaxLightProbesPerGrid caps the total number of probes (nx * ny * nz) in a LightProbeGridDoc.
MaxLightProbesPerGrid = 4096
)const AnimatorComponentName = "animator"AnimatorComponentName is the built-in sprite animation state machine component type name in scene and prefab YAML files.
const ConflictVersion = 1ConflictVersion is the schema version of the YAML conflict file written by the scene merge driver when a three-way merge encounters conflicts.
const CoverPointComponentName = "cover_point"CoverPointComponentName is the canonical scene YAML component key for authored cover points.
const CurrentVersion = 4CurrentVersion is the newest scene format schema version, the one new documents are written in. Version 2 adds scene instancing (ObjectDoc.Scene and ObjectDoc.Overrides), inheritance (SceneDoc.Inherits, SceneDoc.Overrides and SceneDoc.LayerOverrides) and glTF models (ObjectDoc.Model, ObjectDoc.ModelNode and ObjectDoc.ModelMesh). Version 3 adds parallax and repeating layers (LayerDoc.ParallaxX, LayerDoc.ParallaxY, LayerDoc.RepeatX, LayerDoc.RepeatY, LayerDoc.RepeatWidth and LayerDoc.RepeatHeight, and the matching fields on LayerOverride) and tilemap offsets (TilemapDoc.OffsetX and TilemapDoc.OffsetY). Version 4 adds 3D lights (ObjectDoc.Light), 3D cameras (ObjectDoc.Camera), 3D reflection probes (ObjectDoc.ReflectionProbe), 3D light probe grids (ObjectDoc.LightProbeGrid) and scene environment settings (SceneDoc.Environment).
const Lights2DComponentVersion = 1Lights2DComponentVersion is the schema version of the built-in 2D lighting components (light2d and occluder2d).
const MaxEmitDepth = 64MaxEmitDepth is how deeply Signals.Emit nests: a handler that emits an event is one level, and a handler that event runs and emits another is two. Emit refuses to go deeper, which stops connections that trigger each other from looping forever.
const MaxObjectDepth = 64MaxObjectDepth is how many levels of objects a layer may nest: a top-level object is at depth 1, its children at depth 2, and so on. Validate refuses a deeper tree.
const MaxResolvedObjects = 1 << 17MaxResolvedObjects is the most objects Resolve creates for one scene, counting each copy of an instanced or inherited object. It stops scenes that instance each other many times over from growing without bound.
const MaxSceneNesting = 64MaxSceneNesting is how many scene files deep Resolve follows instancing and inheritance: a scene that instances or inherits another is one level, and a scene that one instances in turn is two. Resolve refuses a deeper chain.
const MaxTileLayers = 64MaxTileLayers is the most tile layers one layered grid may hold (TilemapDoc.TileLayers).
const MinVersion = 1MinVersion is the oldest scene format schema version this package still reads. A version 1, 2 or 3 document is read and written unchanged, and may not use any field added by a newer version.
NavLinkComponentName is the canonical scene YAML component key for authored off-mesh navigation links (jumps, ledge drops, ladders, doors, and teleporters).
NavRegion2DComponentName is the built-in 2D navigation region polygon component key in scene YAML files.
NavRegion2DComponentVersion is the schema version of the built-in 2D navigation region component (navregion2d).
const PhysicsComponentVersion = 1PhysicsComponentVersion is the schema version of the built-in 2D and 3D physics components.
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURLSchemaComment is the first line Encode writes for a version 1 document: a YAML comment that points a YAML language server at SchemaURL. Parse ignores it like any other comment.
const SchemaCommentV2 = "# yaml-language-server: $schema=" + SchemaURLV2SchemaCommentV2 is the first line Encode writes for a version 2 document, pointing a YAML language server at SchemaURLV2.
const SchemaCommentV3 = "# yaml-language-server: $schema=" + SchemaURLV3SchemaCommentV3 is the first line Encode writes for a version 3 document, pointing a YAML language server at SchemaURLV3.
const SchemaCommentV4 = "# yaml-language-server: $schema=" + SchemaURLV4SchemaCommentV4 is the first line Encode writes for a version 4 document, pointing a YAML language server at SchemaURLV4.
const SchemaURL = "https://game.nsgo.dev/schemas/scene.v1.json"SchemaURL is where the JSON Schema of version 1 scene documents is published. Encode names it in a yaml-language-server comment on the first line of a version 1 document, so editors that run the YAML language server (such as VS Code's YAML extension) and AI tools validate and complete a scene file as it is written.
const SchemaURLV2 = "https://game.nsgo.dev/schemas/scene.v2.json"SchemaURLV2 is where the JSON Schema of version 2 scene documents is published, named by SchemaCommentV2 as SchemaURL is by SchemaComment.
const SchemaURLV3 = "https://game.nsgo.dev/schemas/scene.v3.json"SchemaURLV3 is where the JSON Schema of version 3 scene documents is published, named by SchemaCommentV3 as SchemaURL is by SchemaComment.
const SchemaURLV4 = "https://game.nsgo.dev/schemas/scene.v4.json"SchemaURLV4 is where the JSON Schema of version 4 scene documents is published, named by SchemaCommentV4 as SchemaURL is by SchemaComment.
const SkeletalComponentName = "skeletal"SkeletalComponentName is the built-in 2D skeletal rig component name in scene YAML files.
const SkeletalComponentVersion = 1SkeletalComponentVersion is the schema version of the built-in "skeletal" component.
Funciones
func Bool(v bool) *boolBool returns a pointer to v for optional YAML boolean fields such as LayerDoc.Visible.
func BuildLights2D(scene *BuiltScene) (*lights2d.Scene, error)BuildLights2D constructs a *lights2d.Scene from a BuiltScene's AmbientColor, built-in light2d and occluder2d components on visible world-space layers, and any tilemap collision occluders referenced by occluder2d (shape: "tilemap"). It returns (nil, nil) when the scene declares no ambientColor, no light2d components, and no occluder2d components.
func BuildNavMesh2D(scene *BuiltScene) (*navbake.Mesh, *ai.NavMesh, error)BuildNavMesh2D constructs a baked *navbake.Mesh and runtime *ai.NavMesh from all built-in navregion2d components on visible world-space layers of scene, optionally subtracting solid tilemap collision geometry and attaching any authored 2D nav_link components.
It returns (nil, nil, nil) when the scene declares no navregion2d components. When navregion2d components exist but no enabled walkable polygon has at least 3 vertices, it returns an empty *navbake.Mesh and empty *ai.NavMesh without error.
func CheckObjectCamera3D(o *ObjectDoc) errorCheckObjectCamera3D checks o.Camera as Validate checks it in a version 4 scene.
func CheckObjectLight(o *ObjectDoc) errorCheckObjectLight checks o.Light as Validate checks it in a version 4 scene.
func CheckObjectLightProbeGrid(o *ObjectDoc) errorCheckObjectLightProbeGrid checks o.LightProbeGrid as Validate checks it in a version 4 scene.
func CheckObjectModel(o *ObjectDoc) errorCheckObjectModel checks the fields of o that say what it draws in 3D and how it occludes, as Validate checks them in a version 2 scene: Mesh is "" or one of MeshPrimitives, Model is "" or a slash-separated path to a .gltf or .glb file, Mesh and Model are not both set, nor ModelNode and ModelMesh, ModelNode and ModelMesh require Model, and Occluder (when set) is valid with mode "model" requiring Mesh or Model. It does not check o's descendants, and lets a caller such as an editor refuse an object before it reaches a document.
func CheckObjectReflectionProbe(o *ObjectDoc) errorCheckObjectReflectionProbe checks o.ReflectionProbe as Validate checks it in a version 4 scene.
func CheckObjectTree(o *ObjectDoc) errorCheckObjectTree checks the shape of the tree rooted at o, taking o as a top-level object: nesting no deeper than MaxObjectDepth levels, and no sprite whose composed world transform is sheared. Validate makes the same checks for every layer of a scene; CheckObjectTree lets a caller such as an editor refuse a tree or a transform change before it reaches a document. It does not check IDs or field values.
func Encode(doc *SceneDoc) ([]byte, error)Encode validates doc and serializes it as deterministic 2-space YAML, starting with the line SchemaCommentFor returns for its version. A whole-number float in a custom property (ObjectDoc.Properties) is written with a decimal point, such as 2.0, so that it reads back as a float and not an int.
func EncodeConflict(doc *ConflictDoc) ([]byte, error)EncodeConflict validates doc and serializes it as deterministic 2-space YAML.
func ExtractBuiltCoverPoints(scene *BuiltScene) ([]ai.CoverPoint, error)ExtractBuiltCoverPoints extracts all authored "cover_point" components from a resolved BuiltScene.
func ExtractBuiltNavLinks2D(scene *BuiltScene) ([]ai.NavOffMeshLink, error)ExtractBuiltNavLinks2D extracts all authored "nav_link" components from a resolved BuiltScene as 2D links.
func ExtractBuiltNavLinks3D(scene *BuiltScene) ([]world3d.NavOffMeshLink, error)ExtractBuiltNavLinks3D extracts all authored "nav_link" components from a resolved BuiltScene as 3D links.
func ExtractCoverPoints(doc *SceneDoc) ([]ai.CoverPoint, error)ExtractCoverPoints extracts all authored "cover_point" components from doc in deterministic document order (including nested child objects, composing parent 2D transforms).
Each extracted CoverPoint receives a sequential 1-based ID, normalized world-space Facing (rotated by composed object rotation), validated CoverHeight ("half" or "full"), and parsed Tags.
func ExtractNavLinks2D(doc *SceneDoc) ([]ai.NavOffMeshLink, error)ExtractNavLinks2D extracts all authored "nav_link" components from doc in deterministic document order (including nested child objects, composing parent 2D transforms) as 2D ai.NavOffMeshLink values ready for ai.NavMesh.AddOffMeshLink.
func ExtractNavLinks3D(doc *SceneDoc) ([]world3d.NavOffMeshLink, error)ExtractNavLinks3D extracts all authored "nav_link" components from doc in deterministic document order (including nested child objects, composing full 3D object transforms) as 3D world3d.NavOffMeshLink values ready for world3d.NavMesh.AddOffMeshLink or navbake3d.
func Float32(v float32) *float32Float32 returns a pointer to v for optional YAML float fields such as ScaleX, ScaleY, Alpha and Zoom.
func Float64(v float64) *float64Float64 returns a pointer to v for a Field's optional Min and Max.
func FormatTileRow(cells []uint32) stringFormatTileRow writes cells, tile values as TileLayerDoc.Cell returns them, as one row of a tile layer in the form Encode writes: single spaces between cells, "." for an empty one and flip letters in the order h, v, d.
func Int(v int) *intInt returns a pointer to v for optional YAML integer fields such as ObjectOverride.Z and LayerOverride.Order.
func IsGridMapPath(p string) boolIsGridMapPath reports whether p names a 3D grid map file by its extension, .gridmap.yaml or .gridmap.yml in any case, as ObjectDoc.GridMap requires.
func IsHDRPath(p string) boolIsHDRPath reports whether p names a Radiance HDR image by its extension, .hdr or .pic in any case, as SkyDoc.HDR requires.
func IsLightProbeGridPath(p string) boolIsLightProbeGridPath reports whether p names a YAML light probe grid file by its extension (.yaml or .yml in any case).
func IsLights2DComponent(name string) boolIsLights2DComponent reports whether name is one of the built-in 2D lighting component types.
func IsModelPath(p string) boolIsModelPath reports whether p names a glTF 2.0 file by its extension, .gltf or .glb in any case, as ObjectDoc.Model requires.
func IsNavRegion2DComponent(name string) boolIsNavRegion2DComponent reports whether name is the built-in 2D navigation region component type.
func IsPhysicsComponent(name string) boolIsPhysicsComponent reports whether name is one of the built-in 2D or 3D physics component types.
func IsSkeletalComponent(name string) boolIsSkeletalComponent reports whether name is the built-in "skeletal" component type.
func Lights2DComponentNames() []stringLights2DComponentNames returns the names of all built-in 2D lighting component types in canonical order.
func MeshPrimitives() []stringMeshPrimitives returns the built-in primitive names ObjectDoc.Mesh accepts, sorted.
func ObjectLocalTransform3D(o *ObjectDoc) math3d.TransformObjectLocalTransform3D returns o's 3D transform relative to its parent (or to its layer for a top-level object): position (X, Y, PosZ), rotation RotX then RotY then RotZ about fixed axes (the quaternion Rz * Ry * Rx, matching the editor's 3D viewport), and scale (ScaleX, ScaleY, ScaleZ).
func ParseTileRow(row string) ([]uint32, error)ParseTileRow parses one row of a tile layer (TileLayerDoc.Rows) into its cells, as TileLayerDoc.Cell returns each. Cells are separated by spaces or tabs, and a cell's flip letters may come in any order, each at most once.
func PhysicsComponentNames() []stringPhysicsComponentNames returns the names of all built-in physics component types in canonical order.
func RegisterAnimatorComponent(reg *ComponentRegistry) errorRegisterAnimatorComponent registers the built-in "animator" component type on reg.
func RegisterCoverPoint(reg *ComponentRegistry) errorRegisterCoverPoint registers the built-in "cover_point" component type on reg.
func RegisterLights2DComponents(reg *ComponentRegistry) errorRegisterLights2DComponents registers the built-in light2d and occluder2d component types on reg.
func RegisterNavLink(reg *ComponentRegistry) errorRegisterNavLink registers the built-in "nav_link" component type on reg.
func RegisterNavRegion2DComponent(reg *ComponentRegistry) errorRegisterNavRegion2DComponent registers the built-in "navregion2d" component type on reg.
func RegisterPhysicsComponents(reg *ComponentRegistry) errorRegisterPhysicsComponents registers all six built-in 2D and 3D physics component types on reg.
func RegisterSkeletalComponent(reg *ComponentRegistry) errorRegisterSkeletalComponent registers the built-in "skeletal" component type on reg.
func SchemaCommentFor(version int) stringSchemaCommentFor returns the first line Encode writes for a document of the given version: SchemaComment for version 1, SchemaCommentV2 for version 2, SchemaCommentV3 for version 3, and SchemaCommentV4 for version 4.
func SpawnEntities(doc *SceneDoc, w *entities.World) (map[string]entities.Entity, error)SpawnEntities validates doc and spawns one entity per object into w, children included, linked into w's 2D transform hierarchy (entities.Hierarchy2D) the way the objects nest in the document. Each entity's local entities.Transform2D holds the object's X, Y, Rotation, ScaleX and ScaleY, and each carries an ObjectRef component. The top-level objects of a hidden layer are spawned hidden, so their subtrees are not world-visible. Entities are spawned in depth-first document order, each parent before its children, and the result maps every object ID to its entity.
SpawnEntities returns an error and spawns nothing when doc is invalid, still instances or inherits other scene files (pass it through Resolve first), or w is nil or disposed.
func String(v string) *stringString returns a pointer to v for optional YAML string fields such as ObjectOverride.Name.
func Validate(doc *SceneDoc) errorValidate checks that doc conforms to the schema rules of its version. It checks a scene's references to other scene files only for their form; Resolve loads them and validates the result. Every error it returns is a *FieldError naming the field at fault. When several fields are wrong it reports the first in document order, taking the entries of Tilemaps in key order.
func ValidateComponents(doc *SceneDoc, reg *ComponentRegistry) errorValidateComponents checks the components of every object in doc, children included, against reg: unregistered component types, unknown fields, wrong kinds and out-of-range values are refused. Objects are checked in document order and components and fields in ascending name order. The returned error is a *ComponentError naming the object; it carries no line because doc holds none, so prefer ParseWith with ParseOptions.Components when loading files.
func ValidateConflict(doc *ConflictDoc) errorValidateConflict checks that doc conforms to ConflictVersion's schema.
func ValidateConnections(doc *SceneDoc, reg *ComponentRegistry) errorValidateConnections checks every connection of doc against reg: each event must be declared by exactly one registered component type of its From object (or by the component it names, as in "button.pressed"), each handler likewise on its To object, and each argument must match a param of the handler in kind and range. doc must not instance or inherit other scene files; pass it through Resolve first. The error is a *ConnectionError without a position; ParseWith with ParseOptions.Components reports the same errors with the file and line.
func ValidatePhysicsLayers(doc *SceneDoc, layers *PhysicsLayerTable) errorValidatePhysicsLayers checks every named collision layer and mask in built-in physics components of doc against layers. Unknown or misspelled layer names return a *loaderr.Error naming the field path. Prefer ParseWith with ParseOptions.PhysicsLayers when loading files so errors also carry exact 1-based line and column numbers.
func WalkObjects(objs []ObjectDoc, fn func(o, parent *ObjectDoc) bool) boolWalkObjects calls fn for every object in objs and its descendants, depth first with each parent before its children and siblings in document order. parent is nil for an object in objs. The walk stops when fn returns false, and WalkObjects reports whether it visited every object.
Tipos
type AnimatorConfig struct {
// States is the project-relative path to the *.states.yaml file.
States string
// StartClip is the optional starting state or clip override.
StartClip string
// AutoPlay reports whether playback starts automatically.
AutoPlay bool
// Speed is the playback speed multiplier (>= 0).
Speed float64
}AnimatorConfig holds the resolved fields of an object's built-in "animator" component.
func ResolveAnimatorComponent(obj *ObjectDoc) (AnimatorConfig, bool, error)ResolveAnimatorComponent resolves the built-in "animator" component on obj, returning (cfg, true, nil) when present, (zero, false, nil) when absent, or an error when its fields are invalid.
type AssetResolver interface {
Atlas(name string) (*sprite.Atlas, error)
}AssetResolver resolves sprite atlases named in a SceneDoc when building a BuiltScene.
type AtlasMap map[string]*sprite.AtlasAtlasMap is an AssetResolver backed by a map of atlas names to atlases.
func (m AtlasMap) Atlas(name string) (*sprite.Atlas, error)Atlas returns the atlas named name or an error when it is absent or nil.
type BoundsDoc struct {
// X and Y are the rectangle's top-left corner.
X float32 `yaml:"x,omitempty"`
Y float32 `yaml:"y,omitempty"`
// Width and Height are the rectangle's size; both must be positive.
Width float32 `yaml:"width" schema:"required,exclusiveMinimum=0"`
Height float32 `yaml:"height" schema:"required,exclusiveMinimum=0"`
}BoundsDoc is an axis-aligned rectangle in world coordinates.
type BuiltLayer struct {
// Doc is the source layer definition.
Doc *LayerDoc
// Name is the layer's unique name.
Name string
// Space is SpaceWorld or SpaceScreen.
Space Space
// Order is the layer's draw order.
Order int
// Visible controls whether Draw renders this layer.
Visible bool
// ParallaxX and ParallaxY are the layer's horizontal and vertical parallax scroll factors, defaulting to 1.
ParallaxX float32
ParallaxY float32
// RepeatX and RepeatY report whether a world-space layer tiles horizontally or vertically across the camera's visible region.
RepeatX bool
RepeatY bool
// RepeatWidth and RepeatHeight are the horizontal and vertical repeat periods in layer points; when RepeatX or RepeatY is true and the document leaves a period 0, Build fills it from the layer's tilemap pixel size or the scene's virtual size.
RepeatWidth float32
RepeatHeight float32
// Tilemap is the sprite batch for the layer's tilemap when it is a single grid of atlas frames (TilemapDoc.Tileset and Data), or nil.
Tilemap *sprite.Batch
// Map is the tilemap built from the layer's tilemap when it is a layered grid (TilemapDoc.TileLayers) or a Tiled or LDtk source, or nil. It holds the tileset's flags, properties, shapes, animations and terrains, so in the layer's coordinates it answers FlagsAt, TileProperties, TilesInRect and Raycast and serves tileshape.New; Draw draws only its tiles inside the view, and BuiltScene.Update animates them.
Map *tilemap.Tilemap
// Batches are the sprite batches for the layer's sprite objects, grouped in exact Z order.
Batches []*sprite.Batch
// Emitters are the layer's built objects that carry a live 2D particle emitter (ObjectDoc.Particles), in document order.
Emitters []*BuiltObject
// Skeletons are the layer's built objects that carry a live 2D skeletal rig (BuiltObject.Skeleton), in Z order.
Skeletons []*BuiltObject
// Objects are the layer's top-level built objects in document order; each one's descendants hang from BuiltObject.Children.
Objects []*BuiltObject
// contains filtered or unexported fields
}BuiltLayer is one resolved layer of a BuiltScene.
func (l *BuiltLayer) Draw(d *core.Drawing, view *tilemap.Camera)Draw draws the layer's tilemap, layered map, and Z-order interleaved sprite batches, particle emitters, and skeletal rigs into d. When view is nil, every tile of Map draws without culling.
func (l *BuiltLayer) DrawObjects(d *core.Drawing)DrawObjects draws the layer's sprite batches, particle emitters, and skeletal rigs into d in exact Z order.
func (l *BuiltLayer) RepeatTileRanges(camX, camY, vw, vh, zoom, rot float32) (minCol, maxCol, minRow, maxRow int, rx, ry bool)RepeatTileRanges computes the tile column and row ranges covering the visible bounds of a camera at (camX, camY) with viewport (vw, vh), zoom and rotation, matching scene.Layer's repeat tiling while guarding non-finite inputs, integer overflow, and extreme repeat counts.
type BuiltObject struct {
// Doc is the source object definition.
Doc *ObjectDoc
// ID is the object's unique scene ID.
ID string
// Layer is the name of the layer containing this object.
Layer string
// Atlas is the resolved atlas for Sprite or Skeleton, or nil when the object has neither.
Atlas *sprite.Atlas
// Sprite is the live sprite drawn by its layer's batch, or nil when the object has no sprite. Its X, Y, Rotation, ScaleX, ScaleY and Alpha are the object's world values, composed through its ancestors.
Sprite *sprite.Sprite
// Skeleton is the live 2D skeletal rig built from the object's "skeletal" component, or nil when none is configured. Its root transform, flips, alpha and Z track the object's world values and BuiltScene.Update advances its playback.
Skeleton *skeletal.Skeleton
// Material is the shared material resolved from Doc.Material, or nil when the object names none. It is the resolver's value, not a copy, so an edit reloaded into it reaches every scene that uses it.
Material *resource.Material
// Emitter is the live 2D particle emitter built from Doc.Particles, or nil when the object has none. BuiltScene.Update steps it and BuiltScene.Draw draws it at the object's world transform.
Emitter *particles.Emitter
// Parent is the object this one is a child of, or nil for a top-level object.
Parent *BuiltObject
// Children are the object's built children in document order.
Children []*BuiltObject
// World is the object's transform composed with its ancestors', mapping its local space to its layer's space (World = Parent.World * local).
World math2d.Affine
// WorldAlpha is the object's alpha multiplied by every ancestor's.
WorldAlpha float32
// contains filtered or unexported fields
}BuiltObject is one object instantiated from an ObjectDoc.
func (bo *BuiltObject) Sync() boolSync recomputes the object's World and WorldAlpha from its document and its parent's, copies its transform, sprite frame (when found in Atlas), origin, flip and alpha onto its sprite (times its material's opacity, as Build does), and does the same for its descendants, so an edit to the document fields of a built object, such as one an animation makes, shows on the next Draw. It reports false, and leaves the sprite's transform as it was, for a sprite whose composed transform is sheared, which a sprite cannot draw.
type BuiltScene struct {
// Doc is the validated SceneDoc this scene was built from: the one passed to Build, or for a scene that instances or inherits other scene files, the self-contained copy Resolve made of it, whose objects the BuiltObjects point into.
Doc *SceneDoc
// BackgroundColor is the parsed background color; HasBackground reports whether Draw paints it.
BackgroundColor core.Color
HasBackground bool
// AmbientColor is the parsed 2D lighting ambient color; HasAmbient reports whether the scene sets one.
AmbientColor core.Color
HasAmbient bool
// Lights2D is the 2D lighting scene built from SceneDoc.AmbientColor, built-in light2d and occluder2d components, and tilemap collision shapes, or nil when the scene defines none.
Lights2D *lights2d.Scene
// SkipLights2D disables drawing Lights2D inside Draw when true (for example when an editor toggles lighting preview off).
SkipLights2D bool
// Lights2DBounds optionally overrides the world-space bounds passed to Lights2D.Draw inside Draw. Nil uses the scene's virtual viewport through Camera (or the union of light/occluder extents when the virtual size is 0).
Lights2DBounds *core.Bounds
// NavBake2D is the baked 2D navigation mesh produced from built-in navregion2d components (and optional tilemap collision subtraction), or nil when the scene defines none.
// NavMesh2D is the runtime 2D ai.NavMesh constructed from NavBake2D (including any authored 2D nav_link components), or nil when the scene defines no navregion2d components.
// Camera is the active camera transform for world-space layers; nil leaves world space untransformed.
Camera *CameraDoc
// Layers are the scene's layers in draw order (lowest Order first, ties in document order).
Layers []*BuiltLayer
// Objects indexes every built object in the scene, children included, by its unique ID.
Objects map[string]*BuiltObject
// DrawAllTiles makes Draw draw every tile of the layers' maps (BuiltLayer.Map). By default Draw culls them to the scene's view, its virtual viewport through the camera, which a view that shows more of the world, such as an editor's panned past the camera, sets it to avoid.
DrawAllTiles bool
// contains filtered or unexported fields
}BuiltScene is a SceneDoc resolved against atlases and ready to draw into a core.Drawing.
func Build(doc *SceneDoc, resolver AssetResolver) (*BuiltScene, error)Build validates doc, resolves its referenced atlases and tilemaps through resolver, and returns a BuiltScene ready to draw. A single grid of atlas frames becomes a sprite batch (BuiltLayer.Tilemap); a layered grid, with the YAML tileset it names read through a FileResolver, and a Tiled or LDtk source, read through a TilemapResolver when the resolver implements one and otherwise through a FileResolver, become a tilemap.Tilemap (BuiltLayer.Map). A scene that instances or inherits other scene files (SceneDoc.RefersToScenes) is first resolved with Resolve, which loads them through resolver when it implements SceneResolver.
func (s *BuiltScene) Draw(d *core.Drawing)Draw draws the scene into d: it syncs materials (SyncMaterials), then draws the background fill over the virtual viewport (when configured), then each visible layer in order, its tilemap beneath its objects. World-space layers draw under the camera transform; screen-space layers draw in canvas coordinates. A layer's map (BuiltLayer.Map) draws only the tiles inside the virtual viewport, seen through the camera for a world-space layer, unless the scene has no virtual size or DrawAllTiles is set. Draw leaves d's transform and paint state as it found it.
func (s *BuiltScene) Layer(name string) *BuiltLayerLayer returns the built layer named name, or nil if none exists.
func (s *BuiltScene) Object(id string) *BuiltObjectObject returns the built object with ID id, or nil if none exists.
func (s *BuiltScene) SyncLights2D() errorSyncLights2D rebuilds s.Lights2D from the scene's current object transforms, component values, ambient color, and tilemaps, preserving LightComposite and DisableShadows when a Lights2D scene already existed.
func (s *BuiltScene) SyncMaterials()SyncMaterials copies the current state of every object's material onto its sprite, so a material reloaded in place (resource.Library.Reload) shows on the next draw. Draw calls it first; call it directly to read the sprites without drawing.
func (s *BuiltScene) SyncNavMesh2D() errorSyncNavMesh2D rebuilds s.NavBake2D and s.NavMesh2D from the scene's current object transforms, navregion2d components, and tilemaps.
func (s *BuiltScene) Update(dt time.Duration)Update advances the animated tiles of every layer's map (BuiltLayer.Map), every placed particle emitter (BuiltLayer.Emitters), and every placed 2D skeletal rig (BuiltLayer.Skeletons) by dt, so the next Draw shows their current frames and poses.
type Call struct {
// Signals is the dispatcher that called the handler, so a handler can emit further events.
Signals *Signals
// Context is the value passed to Connect, such as the game's own state or a *BuiltScene.
Context any
// Source is the object that emitted the event, in the document passed to Connect.
Source *ObjectDoc
// SourceComponent is the component of Source whose type declares the event.
SourceComponent string
// Event is the event's name as its component type declares it, without the component.
Event string
// Target is the object whose handler runs, in the document passed to Connect.
Target *ObjectDoc
// Component is the component of Target whose type declares the handler.
Component string
// Handler is the handler's name as its component type declares it, without the component.
Handler string
// Args holds every param of the handler: the connection's value normalized to the param's Go type (bool, int, float64 or string), or the param's default. The map is the handler's own to change.
Args map[string]any
// Payload is the value passed to Signals.Emit or Signals.Enqueue.
Payload any
// SourceEntity and TargetEntity are the entities Source and Target were spawned as when SpawnConnected made the Signals, or entities.Zero when Connect made it.
SourceEntity, TargetEntity entities.Entity
}Call is what a HandlerFunc receives: the connection that fired, the objects at both ends and the values passed along.
type Camera3DDoc struct {
// Projection selects ProjectionPerspective ("perspective") or ProjectionOrthographic ("orthographic"); empty defaults to perspective.
Projection ProjectionKind `yaml:"projection,omitempty" schema:"enum=perspective|orthographic"`
// FOV is a perspective camera's vertical field of view in degrees, in (0, 180); nil defaults to 60. Refused on orthographic cameras.
FOV *float32 `yaml:"fov,omitempty" schema:"exclusiveMinimum=0,exclusiveMaximum=180"`
// OrthoHeight is an orthographic camera's full vertical world height; nil defaults to 10. Must be finite and positive; refused on perspective cameras.
OrthoHeight *float32 `yaml:"orthoHeight,omitempty" schema:"exclusiveMinimum=0"`
// Near is the near clip plane distance; nil defaults to 0.1. Must be finite and positive for perspective cameras, and finite for orthographic cameras.
Near *float32 `yaml:"near,omitempty"`
// Far is the far clip plane distance; nil defaults to 1000. Must be finite and greater than near.
Far *float32 `yaml:"far,omitempty"`
// Current marks this camera as the scene's active 3D camera. At most one camera in a scene may be current; when none is marked, the first 3D camera in document order is used.
Current bool `yaml:"current,omitempty"`
}Camera3DDoc configures a 3D camera attached to an object (ObjectDoc.Camera). Its world position and orientation (looking down local -Z with +Y up) come from the object's 3D transform. Version 4.
func (c *Camera3DDoc) Clone() *Camera3DDocClone returns a deep copy of c, or nil when c is nil.
func (c *Camera3DDoc) EffectiveFOV() float32EffectiveFOV returns a perspective camera's vertical field of view in degrees, defaulting to 60 when nil.
func (c *Camera3DDoc) EffectiveFar() float32EffectiveFar returns the far clip plane distance, defaulting to 1000 when nil.
func (c *Camera3DDoc) EffectiveNear() float32EffectiveNear returns the near clip plane distance, defaulting to 0.1 when nil.
func (c *Camera3DDoc) EffectiveOrthoHeight() float32EffectiveOrthoHeight returns an orthographic camera's full vertical world height, defaulting to 10 when nil.
func (c *Camera3DDoc) EffectiveProjection() ProjectionKindEffectiveProjection returns c.Projection, defaulting to ProjectionPerspective when empty.
type CameraDoc struct {
// X and Y are the world coordinates centered in the virtual viewport (or mapped to the origin when virtual dimensions are 0).
X float32 `yaml:"x,omitempty"`
Y float32 `yaml:"y,omitempty"`
// Zoom is the camera zoom factor; nil defaults to 1. Must be positive when set.
Zoom *float32 `yaml:"zoom,omitempty" schema:"exclusiveMinimum=0"`
// Rotation turns the camera clockwise in radians; world geometry rotates by -Rotation around (X, Y).
Rotation float32 `yaml:"rotation,omitempty"`
// Bounds optionally clamps the camera view inside a world rectangle.
Bounds *BoundsDoc `yaml:"bounds,omitempty"`
}CameraDoc describes a 2D camera transform for world-space layers.
func (c *CameraDoc) EffectiveZoom() float32EffectiveZoom returns the camera's zoom factor, defaulting to 1 when Zoom is nil.
type Circle struct {
// X is the horizontal center coordinate in object-local space.
X float64 `yaml:"x"`
// Y is the vertical center coordinate in object-local space.
Y float64 `yaml:"y"`
// Radius is the circle's radius in object-local space (non-negative).
Radius float64 `yaml:"radius" schema:"minimum=0"`
}Circle is a 2D circle in an object's local coordinate space, used by FieldCircle component fields.
func ParseCircle(v any) (Circle, error)ParseCircle converts a component field value (Circle or decoded YAML map) to a validated Circle.
func (c Circle) MarshalYAML() (any, error)MarshalYAML encodes Circle with deterministic alphabetical key order matching YAML map decoding ("radius", "x", "y").
type ComponentError struct {
// File is ParseOptions.File, or empty.
File string
// Line and Column are the 1-based position of the offending key or value, or 0 when unknown.
Line, Column int
// Object is the ID of the object holding the component, or empty when the check was not about a scene object.
Object string
// Component is the component type name as written.
Component string
// Field is the field name as written, or empty when the error is about the whole component.
Field string
// Msg says what is wrong.
Msg string
}ComponentError reports a component value that does not match its registered type. File, Line and Column locate it in a scene file when it came from ParseWith; they are empty or zero otherwise.
func (e *ComponentError) Error() stringError formats the error as "file:line:col: sceneformat: object "id" component "name" field "f": msg", leaving out the parts that are unknown.
type ComponentRegistry struct {
// contains filtered or unexported fields
}ComponentRegistry holds the component types scene files may use. Types are declared explicitly in Go, so loading needs no reflection over game structs. Register every type before the registry is shared; lookups are safe from many goroutines once registration is done, but Register is not safe to call concurrently with them.
func AnimatorComponentRegistry() *ComponentRegistryAnimatorComponentRegistry returns a new ComponentRegistry containing the built-in "animator" component.
func Lights2DComponentRegistry() *ComponentRegistryLights2DComponentRegistry returns a new ComponentRegistry pre-populated with the built-in 2D lighting components.
func NavRegion2DComponentRegistry() *ComponentRegistryNavRegion2DComponentRegistry returns a new ComponentRegistry pre-populated with the built-in "navregion2d" component.
func NewComponentRegistry() *ComponentRegistryNewComponentRegistry returns an empty registry.
func PhysicsComponentRegistry() *ComponentRegistryPhysicsComponentRegistry returns a new ComponentRegistry pre-populated with all built-in 2D and 3D physics components.
func SkeletalComponentRegistry() *ComponentRegistrySkeletalComponentRegistry returns a new ComponentRegistry pre-populated with the built-in "skeletal" component.
func (r *ComponentRegistry) CheckComponent(component string, value any) errorCheckComponent checks that value is a mapping whose keys are all registered fields of component with values of the right kind and range. Fields are checked in ascending name order so the first error is deterministic.
func (r *ComponentRegistry) CheckField(component, field string, value any) (any, error)CheckField checks value against the registered field component.field and returns it normalized to the field's Go type (bool, int, float64 or string). The error names the component and field; it is a *ComponentError without a position.
func (r *ComponentRegistry) Lookup(name string) (ComponentType, bool)Lookup returns a copy of the component type named name and whether it is registered.
func (r *ComponentRegistry) MustRegister(t ComponentType)MustRegister is Register for package-level setup; it panics when Register returns an error.
func (r *ComponentRegistry) Names() []stringNames returns the registered type names in ascending order.
func (r *ComponentRegistry) Register(t ComponentType) errorRegister adds t to the registry. It refuses an empty or duplicate type name, an empty or duplicate field name, an unknown kind, a range or step on a non-numeric field, a range whose Min is above its Max, a fractional range or step on an int field, a negative or non-finite step, and a default of the wrong kind or outside the range. It refuses an event or handler whose name is empty, holds a dot or repeats another event's or handler's of the type, and a handler's params on the same terms as fields; an event and a handler may share a name. The registry keeps its own copy of t.
func (r *ComponentRegistry) Resolve(component string, data map[string]any) (map[string]any, error)Resolve checks data against component and returns a new map holding every registered field: the value from data where it is set and the registered default otherwise. Use it at runtime to read a component without repeating its defaults; the scene document itself keeps only the fields its author wrote.
func (r *ComponentRegistry) Types() []ComponentTypeTypes returns copies of the registered types ordered by name.
type ComponentType struct {
// Name is the key under an object's components mapping, such as "body" or "collider". It must be non-empty and unique within a registry.
Name string
// Doc is a one-line description shown by tools such as the editor's inspector.
Doc string
// Fields are the component's fields in the order tools list them.
Fields []Field
// Events are the events an object with this component emits, such as a button's "pressed", in the order tools list them. A scene's connections (SceneDoc.Connections) name them, and Signals.Emit fires them.
Events []Event
// Handlers are what an object with this component can do when an event connected to it fires, such as a door's "open", in the order tools list them.
Handlers []Handler
}ComponentType is a registered component: the name it is keyed by under an object's components and its fields in declaration order.
func AnimatorComponent() ComponentTypeAnimatorComponent returns the ComponentType schema for the built-in "animator" component. An object with an animator component names a *.states.yaml file and an optional starting state or clip.
func Body2DComponent() ComponentTypeBody2DComponent returns the ComponentType schema for the built-in "body2d" component.
func Body3DComponent() ComponentTypeBody3DComponent returns the ComponentType schema for the built-in "body3d" component.
func Collider2DComponent() ComponentTypeCollider2DComponent returns the ComponentType schema for the built-in "collider2d" component.
func Collider3DComponent() ComponentTypeCollider3DComponent returns the ComponentType schema for the built-in "collider3d" component.
func CoverPointComponent() ComponentTypeCoverPointComponent returns the ComponentType schema for authoring ai.CoverPoint objects in scene YAML.
Register it on a ComponentRegistry via RegisterCoverPoint so ParseWith validates cover_point fields and rejects unknown keys, wrong types, or out-of-range facing components.
func Light2DComponent() ComponentTypeLight2DComponent returns the ComponentType schema for the built-in "light2d" component.
func NavLinkComponent() ComponentTypeNavLinkComponent returns the ComponentType schema for authoring off-mesh navigation links in scene YAML files (for both 2D ai.NavMesh and 3D world3d.NavMesh / navbake3d).
The link's Start and End are expressed in the object's local space (start defaults to the object origin (0, 0, 0), end to (endX, endY, endZ)) and transformed by the object's composed world transform when extracted, so moving, rotating, or instancing a scene or prefab carries both endpoints together.
Register it on a ComponentRegistry via RegisterNavLink so ParseWith validates nav_link fields and rejects unknown keys, wrong types, or out-of-range values.
func NavRegion2DComponent() ComponentTypeNavRegion2DComponent returns the ComponentType schema for the built-in "navregion2d" component.
func Occluder2DComponent() ComponentTypeOccluder2DComponent returns the ComponentType schema for the built-in "occluder2d" component.
func SkeletalComponent() ComponentTypeSkeletalComponent returns the ComponentType schema for the built-in "skeletal" component, which places a 2D skeletal rig (.skel.yaml) on a scene object with an atlas, skin, and animation.
func Trigger2DComponent() ComponentTypeTrigger2DComponent returns the ComponentType schema for the built-in "trigger2d" component.
func Trigger3DComponent() ComponentTypeTrigger3DComponent returns the ComponentType schema for the built-in "trigger3d" component.
func (t *ComponentType) Event(name string) (Event, bool)Event returns the event named name and whether the type declares it.
func (t *ComponentType) Field(name string) (Field, bool)Field returns the field named name and whether the type has it.
func (t *ComponentType) FieldNames() []stringFieldNames returns the type's field names in declaration order.
func (t *ComponentType) Handler(name string) (Handler, bool)Handler returns the handler named name and whether the type declares it.
type ConflictDoc struct {
// Version is ConflictVersion (1).
Version int `yaml:"version"`
// Path is the scene's slash-separated path in the repository (git's %P), when known.
Path string `yaml:"path,omitempty"`
// Merged lists items the merge driver joined cleanly by identity from one or both sides.
Merged []MergedItem `yaml:"merged,omitempty"`
// Conflicts lists every unresolved conflict in deterministic order.
Conflicts []MergeConflict `yaml:"conflicts"`
}ConflictDoc is the versioned, deterministic YAML document left behind when a three-way scene merge cannot finish cleanly.
func ParseConflict(data []byte) (*ConflictDoc, error)ParseConflict decodes and validates a YAML scene merge conflict document. Unknown fields, unsupported versions and trailing YAML documents are refused.
type ConflictKind stringConflictKind classifies why a three-way scene merge entry conflicted.
const (
// ConflictField means both branches changed the same field to different values.
ConflictField ConflictKind = "field"
// ConflictDeleteModify means one branch deleted an item while the other modified it.
ConflictDeleteModify ConflictKind = "delete-modify"
// ConflictAddAdd means both branches added an item with the same identity and different contents.
ConflictAddAdd ConflictKind = "add-add"
// ConflictMove means both branches moved the same object to different parents or layers, or combined moves formed a cycle.
ConflictMove ConflictKind = "move"
// ConflictValidation means the merged scene failed SceneDoc validation.
ConflictValidation ConflictKind = "validation"
)type ConnectionDoc struct {
// From is the ID of the object that emits the event. In a scene that instances or inherits other scene files it may name their objects, such as "door_1/button".
From string `yaml:"from" schema:"required,minLength=1"`
// Event names an event a registered component type of From's object declares (ComponentType.Events), such as "pressed", or "button.pressed" to say which component when several of the object's components declare it.
Event string `yaml:"event" schema:"required,minLength=1"`
// To is the ID of the object whose handler runs.
To string `yaml:"to" schema:"required,minLength=1"`
// Handler names a handler a registered component type of To's object declares (ComponentType.Handlers), such as "open", or "door.open" to say which component.
Handler string `yaml:"handler" schema:"required,minLength=1"`
// Args are values for the handler's params by name; a param left out takes its default. Each is a bool, a number or a string.
Args map[string]any `yaml:"args,omitempty"`
// Once disconnects the connection after the first time the event fires, as Godot's one-shot connections do.
Once bool `yaml:"once,omitempty"`
}ConnectionDoc connects an event that one object emits to a handler of another object, or of the same one (SceneDoc.Connections). Signals.Emit calls the handler each time the object emits the event.
type ConnectionError struct {
// File is ParseOptions.File, or empty.
File string
// Line and Column are the 1-based position of the offending value, or 0 when unknown.
Line, Column int
// Index is the connection's index in SceneDoc.Connections.
Index int
// From, Event, To and Handler are the connection's fields as written.
From, Event, To, Handler string
// Field is the connection's key at fault: "from", "event", "to", "handler" or "args".
Field string
// Arg is the argument at fault when Field is "args", or empty.
Arg string
// Msg says what is wrong.
Msg string
}ConnectionError reports a connection (SceneDoc.Connections) that names an event, handler or argument its objects' registered component types do not declare. File, Line and Column locate it in a scene file when it came from ParseWith; they are empty or zero otherwise.
func (e *ConnectionError) Error() stringError formats the error as `file:line:col: sceneformat: connection 0 ("button" pressed -> "door" open) argument "speed": msg`, leaving out the parts that are unknown.
type EnvironmentDoc struct {
// Sky configures the background sky and IBL environment map; nil leaves the scene without a skybox.
Sky *SkyDoc `yaml:"sky,omitempty"`
// AmbientColor is the CSS color of the uniform ambient fill light (sRGB, converted to linear light); empty defaults to "#ffffff".
AmbientColor string `yaml:"ambientColor,omitempty"`
// AmbientIntensity scales the uniform ambient fill light; nil defaults to 0.25. Must be finite and non-negative.
AmbientIntensity *float32 `yaml:"ambientIntensity,omitempty" schema:"minimum=0"`
// IBLIntensity scales diffuse spherical-harmonic and specular prefiltered image-based lighting derived from Sky; nil defaults to 1 for SkyHDR and 0 otherwise. Must be finite and non-negative.
IBLIntensity *float32 `yaml:"iblIntensity,omitempty" schema:"minimum=0"`
// Fog configures 3D distance and analytical height fog; nil leaves fog disabled.
Fog *FogDoc `yaml:"fog,omitempty"`
// Tonemapping selects TonemapNone ("none"), TonemapReinhard ("reinhard"), TonemapACES ("aces"), TonemapNeutral ("neutral") or TonemapAgX ("agx"); empty defaults to none.
Tonemapping TonemapMode `yaml:"tonemapping,omitempty" schema:"enum=none|reinhard|aces|neutral|agx"`
// Exposure is the linear exposure multiplier applied before tone mapping; nil defaults to 1. Must be finite and non-negative.
Exposure *float32 `yaml:"exposure,omitempty" schema:"minimum=0"`
}EnvironmentDoc configures a 3D scene's sky, ambient fill, image-based lighting, fog, tone mapping and exposure (SceneDoc.Environment). Version 4.
func (e *EnvironmentDoc) Clone() *EnvironmentDocClone returns a deep copy of e, or nil when e is nil.
func (e *EnvironmentDoc) EffectiveAmbientColor() stringEffectiveAmbientColor returns e.AmbientColor, defaulting to "#ffffff" when empty.
func (e *EnvironmentDoc) EffectiveAmbientIntensity() float32EffectiveAmbientIntensity returns e.AmbientIntensity, defaulting to 0.25 when nil.
func (e *EnvironmentDoc) EffectiveExposure() float32EffectiveExposure returns e.Exposure, defaulting to 1 when nil.
func (e *EnvironmentDoc) EffectiveIBLIntensity() float32EffectiveIBLIntensity returns e.IBLIntensity when set, 1 when Sky is SkyHDR, and 0 otherwise.
func (e *EnvironmentDoc) EffectiveTonemapping() TonemapModeEffectiveTonemapping returns e.Tonemapping, defaulting to TonemapNone when empty.
type Event struct {
// Name is the event's name as connections write it. It must be non-empty, hold no dot and be unique among its component type's events.
Name string
// Doc is a one-line description shown by tools such as the editor.
Doc string
}Event declares an event that objects with a component emit (ComponentType.Events), such as a button's "pressed".
type FSAssets struct {
// FS holds the project's files, with paths relative to the project root, such as os.DirFS of the directory that holds game.yaml.
FS fs.FS
// Atlases are the sprite atlases the scene's sprites and atlas tilesets name.
Atlases AtlasMap
}FSAssets is an AssetResolver that reads a project's files from a file system: its scene files (SceneResolver), and through FileResolver the YAML tilesets and Tiled and LDtk maps its tilemaps name, so Build builds a scene whose layers use them with no resolver of the game's own. Atlases come from Atlases, and images are named by their paths (core.ImageSource{URI: path}).
func (a FSAssets) Atlas(name string) (*sprite.Atlas, error)Atlas returns the atlas named name from a.Atlases.
func (a FSAssets) ReadFile(path string) ([]byte, error)ReadFile reads the file at path from a.FS.
func (a FSAssets) Scene(path string) (*SceneDoc, error)Scene reads the scene file at path from a.FS and parses it, as FSScenes does.
type FSScenes struct {
// FS holds the project's files, with paths relative to the project root.
FS fs.FS
}FSScenes is a SceneResolver that reads scene files from FS and parses them with Parse.
func (s FSScenes) Scene(path string) (*SceneDoc, error)Scene reads the file at path from s.FS and parses it.
type Field struct {
// Name is the field's YAML key inside the component mapping. It must be non-empty and unique within its component type.
Name string
// Kind is the field's value type.
Kind FieldKind
// Default is the value an unset field takes. Nil means the kind's zero value (false, 0, 0.0 or ""). Register normalizes it to bool, int, float64 or string and refuses a default of the wrong kind or outside the range.
Default any
// Min and Max are the optional inclusive bounds of a FieldInt or FieldFloat value; nil leaves that side open. They are refused on other kinds, and on a FieldInt they must be whole numbers.
Min, Max *float64
// Step is the increment tools such as the editor's inspector use for a FieldInt or FieldFloat value, and the precision a typed value is rounded to from Min; 0 means 1 for a FieldInt and 0.1 for a FieldFloat. It is refused when negative or not finite, on other kinds, and on a FieldInt when it is not a whole number.
Step float64
// Enum optionally restricts a FieldString value to one of the listed strings. Refused on other kinds.
Enum []string
// Doc is a one-line description shown by tools such as the editor's inspector.
Doc string
}Field describes one field of a component type: its YAML key, value kind, default, optional inclusive range and documentation.
type FieldError struct {
// Path leads from the document's root to the field, one mapping key or decimal sequence index per step, such as ["layers", "2", "objects", "0", "alpha"]. It is empty when the error is about the whole document. A step may name a field the document leaves out, such as a required tileWidth, in which case the nearest written field is the one to point at.
Path []string
// Err is the error itself; FieldError's message is Err's.
Err error
}FieldError is the error Validate returns: what is wrong with a scene document and which field it is about, so a tool such as `game check` can point at the line that holds it.
func (e *FieldError) Error() stringError returns Err's message.
type FieldKind uint8FieldKind is the value type of one registered component field.
const (
// FieldBool holds true or false and decodes to a Go bool.
FieldBool FieldKind = iota + 1
// FieldInt holds a whole number and decodes to a Go int. A YAML float such as 3.0 is refused.
FieldInt
// FieldFloat holds a finite number and decodes to a Go float64. A YAML integer is accepted and widened.
FieldFloat
// FieldString holds text and decodes to a Go string.
FieldString
// FieldStringList holds a list of strings (such as named collision masks) and decodes to a Go []string.
FieldStringList
// FieldPointList holds a list of 2D [x, y] points (such as an occluder polygon's vertices) and decodes to a Go [][2]float64.
FieldPointList
// FieldPoint holds a 2D point {x, y} in object-local space and decodes to a Go Point.
FieldPoint
// FieldRect holds a 2D rectangle {x, y, width, height} in object-local space and decodes to a Go Rect.
FieldRect
// FieldCircle holds a 2D circle {x, y, radius} in object-local space and decodes to a Go Circle.
FieldCircle
// FieldPolygon holds a list of 2D points [{x, y}, ...] in object-local space and decodes to a Go []Point.
FieldPolygon
)func (k FieldKind) IsNumeric() boolIsNumeric reports whether the kind is FieldInt or FieldFloat, the kinds a Field's Min and Max apply to.
func (k FieldKind) IsShape() boolIsShape reports whether the kind is one of the 2D geometry shape kinds: FieldPoint, FieldRect, FieldCircle or FieldPolygon.
func (k FieldKind) String() stringString returns the kind's name as written in error messages: "bool", "int", "float", "string", "[]string", "[][2]float64", "point", "rect", "circle" or "polygon".
type FileResolver interface {
ReadFile(path string) ([]byte, error)
}FileResolver may optionally be implemented by an AssetResolver to read the project's files by their slash-separated paths from the project root. Build reads through it the YAML tilesets that layered grids name (TilemapDoc.TilesetFile) and, with no TilemapResolver, the Tiled (.tmj, .tmx) and LDtk (.ldtk) maps that tilemap sources name, with the tilesets and images those refer to, so a scene uses them with no code of the game's own. FSAssets implements it.
type FogDoc struct {
// Mode selects FogOff ("off"), FogLinear ("linear"), FogExp ("exp") or FogExp2 ("exp2"); empty defaults to off.
Mode FogMode `yaml:"mode,omitempty" schema:"enum=off|linear|exp|exp2"`
// Color is the CSS color of the fog (sRGB, converted to linear light when shaded); empty defaults to "#8090a8".
Color string `yaml:"color,omitempty"`
// Start is the world distance where FogLinear fog begins; must be finite and non-negative.
Start float32 `yaml:"start,omitempty" schema:"minimum=0"`
// End is the world distance where FogLinear fog reaches full density; must be finite and greater than Start when Mode is FogLinear.
End float32 `yaml:"end,omitempty" schema:"minimum=0"`
// Density is the extinction density for FogExp and FogExp2; must be finite and non-negative.
Density float32 `yaml:"density,omitempty" schema:"minimum=0"`
// MaxOpacity caps the combined fog factor in (0, 1]; nil defaults to 1.
MaxOpacity *float32 `yaml:"maxOpacity,omitempty" schema:"exclusiveMinimum=0,maximum=1"`
// HeightEnabled enables analytical exponential height fog along the view ray.
HeightEnabled bool `yaml:"heightEnabled,omitempty"`
// HeightBase is the world Y reference height where height fog has full HeightDensity.
HeightBase float32 `yaml:"heightBase,omitempty"`
// HeightFalloff is the vertical exponential decay rate above HeightBase; must be finite and non-negative.
HeightFalloff float32 `yaml:"heightFalloff,omitempty" schema:"minimum=0"`
// HeightDensity is the base extinction density of height fog at HeightBase; must be finite and non-negative.
HeightDensity float32 `yaml:"heightDensity,omitempty" schema:"minimum=0"`
}FogDoc configures 3D distance and analytical exponential height fog (EnvironmentDoc.Fog). Version 4.
func (f *FogDoc) Clone() *FogDocClone returns a deep copy of f, or nil when f is nil.
func (f *FogDoc) EffectiveColor() stringEffectiveColor returns f.Color, defaulting to "#8090a8" when empty.
func (f *FogDoc) EffectiveMaxOpacity() float32EffectiveMaxOpacity returns f.MaxOpacity, defaulting to 1 when nil.
func (f *FogDoc) EffectiveMode() FogModeEffectiveMode returns f.Mode, defaulting to FogOff when empty.
type FogMode stringFogMode selects how 3D distance fog attenuates visibility (FogDoc.Mode).
const (
// FogOff disables distance fog (analytical height fog may still apply when HeightEnabled is true).
FogOff FogMode = "off"
// FogLinear ramps distance fog linearly from Start to End.
FogLinear FogMode = "linear"
// FogExp applies exponential distance fog using Density.
FogExp FogMode = "exp"
// FogExp2 applies exponential-squared distance fog using Density.
FogExp2 FogMode = "exp2"
)type Handler struct {
// Name is the handler's name as connections write it. It must be non-empty, hold no dot and be unique among its component type's handlers.
Name string
// Doc is a one-line description shown by tools such as the editor.
Doc string
// Params are the arguments a connection may pass the handler (ConnectionDoc.Args), checked as component fields are: by kind and range, with a default for one a connection leaves out.
Params []Field
// Func runs the handler. A registry used only to check files, such as an editor's, may leave it nil; Connect refuses a connection to a handler without one.
Func HandlerFunc
}Handler declares something objects with a component can do when an event connected to it fires (ComponentType.Handlers), such as a door's "open".
func (h *Handler) Param(name string) (Field, bool)Param returns the param named name and whether the handler has it.
type HandlerFunc func(Call)HandlerFunc runs a handler for one emitted event.
type ImageResolver interface {
Image(path string) (core.ImageSource, error)
}ImageResolver may optionally be implemented by an AssetResolver to load the images that YAML tilesets and Tiled and LDtk maps draw their tiles from, given each one's slash-separated path from the project root. Without it an image is core.ImageSource{URI: path}.
type LDtkOptionsResolver interface {
LDtkOptions() tilemap.LDtkOptions
}LDtkOptionsResolver may optionally be implemented by an AssetResolver to provide tilemap.LDtkOptions (such as IntGrid-to-TileFlags mappings from project settings) when Build loads an LDtk (.ldtk) map.
type LayerDoc struct {
// Name uniquely identifies the layer within the scene.
Name string `yaml:"name" schema:"required,minLength=1"`
// Space is SpaceWorld or SpaceScreen; empty defaults to SpaceWorld.
Space Space `yaml:"space,omitempty" schema:"enum=world|screen"`
// Order sets draw order across layers: lower values draw first, ties keep document order.
Order int `yaml:"order,omitempty"`
// Visible controls whether the layer draws; nil defaults to true.
Visible *bool `yaml:"visible,omitempty"`
// ParallaxX scales how fast a world-space layer scrolls horizontally relative to the camera; nil defaults to 1. Zero pins the layer horizontally against camera translation, 0.5 scrolls at half speed, and values above 1 scroll faster for foreground layers. Version 3.
ParallaxX *float32 `yaml:"parallaxX,omitempty"`
// ParallaxY scales how fast a world-space layer scrolls vertically relative to the camera; nil defaults to 1. Zero pins the layer vertically against camera translation, 0.5 scrolls at half speed, and values above 1 scroll faster for foreground layers. Version 3.
ParallaxY *float32 `yaml:"parallaxY,omitempty"`
// RepeatX tiles a world-space layer horizontally across the camera's visible region using RepeatWidth (or, when RepeatWidth is 0, the layer's tilemap pixel width or the scene's virtualWidth). Version 3.
RepeatX bool `yaml:"repeatX,omitempty"`
// RepeatY tiles a world-space layer vertically across the camera's visible region using RepeatHeight (or, when RepeatHeight is 0, the layer's tilemap pixel height or the scene's virtualHeight). Version 3.
RepeatY bool `yaml:"repeatY,omitempty"`
// RepeatWidth is the horizontal repeat period in layer points when RepeatX is true; 0 uses the layer's tilemap pixel width or the scene's virtualWidth. Must be non-negative. Version 3.
RepeatWidth float32 `yaml:"repeatWidth,omitempty" schema:"minimum=0"`
// RepeatHeight is the vertical repeat period in layer points when RepeatY is true; 0 uses the layer's tilemap pixel height or the scene's virtualHeight. Must be non-negative. Version 3.
RepeatHeight float32 `yaml:"repeatHeight,omitempty" schema:"minimum=0"`
// Tilemap optionally attaches a tilemap (by Ref, external Source, or inline grid) drawn beneath Objects.
Tilemap *TilemapDoc `yaml:"tilemap,omitempty"`
// Objects are the placed objects in this layer.
Objects []ObjectDoc `yaml:"objects,omitempty"`
}LayerDoc is one ordered layer in a scene.
func (l *LayerDoc) EffectiveParallaxX() float32EffectiveParallaxX returns ParallaxX, defaulting to 1 when nil.
func (l *LayerDoc) EffectiveParallaxY() float32EffectiveParallaxY returns ParallaxY, defaulting to 1 when nil.
func (l *LayerDoc) EffectiveSpace() SpaceEffectiveSpace returns SpaceWorld when Space is empty, and l.Space otherwise.
func (l *LayerDoc) IsVisible() boolIsVisible reports whether the layer is visible, defaulting to true when Visible is nil.
type LayerOverride struct {
// Space replaces the layer's space when set.
Space Space `yaml:"space,omitempty" schema:"enum=world|screen"`
// Order replaces the layer's draw order when set.
Order *int `yaml:"order,omitempty"`
// Visible replaces the layer's visibility when set.
Visible *bool `yaml:"visible,omitempty"`
// ParallaxX replaces the layer's horizontal parallax scroll factor when set. Version 3.
ParallaxX *float32 `yaml:"parallaxX,omitempty"`
// ParallaxY replaces the layer's vertical parallax scroll factor when set. Version 3.
ParallaxY *float32 `yaml:"parallaxY,omitempty"`
// RepeatX replaces whether a world-space layer tiles horizontally across the camera's visible region when set. Version 3.
RepeatX *bool `yaml:"repeatX,omitempty"`
// RepeatY replaces whether a world-space layer tiles vertically across the camera's visible region when set. Version 3.
RepeatY *bool `yaml:"repeatY,omitempty"`
// RepeatWidth replaces the horizontal repeat period in layer points when set. Version 3.
RepeatWidth *float32 `yaml:"repeatWidth,omitempty" schema:"minimum=0"`
// RepeatHeight replaces the vertical repeat period in layer points when set. Version 3.
RepeatHeight *float32 `yaml:"repeatHeight,omitempty" schema:"minimum=0"`
// Tilemap replaces the layer's tilemap when set.
Tilemap *TilemapDoc `yaml:"tilemap,omitempty"`
}LayerOverride changes an inherited layer in a scene that inherits another (SceneDoc.LayerOverrides). A field left unset keeps the base layer's value.
type Light2DDebug struct {
Kind string
Color core.Color
Radius float32
WorldRadius float32
Intensity float32
Falloff float32
Direction float32
Angle float32
CastShadows bool
Enabled bool
OffsetX float32
OffsetY float32
WorldX float32
WorldY float32
WorldAngle float32
}Light2DDebug describes a resolved light2d component in local and world space for editor overlays and handles.
func ExtractLight2D(o *ObjectDoc, world *math2d.Affine) (*lights2d.Light, Light2DDebug, error)ExtractLight2D resolves a light2d component from o at world (or o's local transform when world is nil), returning the built *lights2d.Light and debug metadata.
type LightDoc struct {
// Kind selects LightDirectional ("directional"), LightPoint ("point") or LightSpot ("spot").
Kind LightKind `yaml:"kind" schema:"required,enum=directional|point|spot"`
// Color is an optional CSS color string parsed with core.ParseColor (sRGB, converted to linear light when shaded); empty defaults to white.
Color string `yaml:"color,omitempty"`
// Intensity scales the light's color; nil defaults to 1. Must be finite and non-negative.
Intensity *float32 `yaml:"intensity,omitempty" schema:"minimum=0"`
// Range is the smooth distance falloff cutoff in world units for point and spot lights; 0 gives unbounded inverse-square falloff. Must be finite and non-negative; refused on directional lights when non-zero.
Range float32 `yaml:"range,omitempty" schema:"minimum=0"`
// InnerCone is a spot light's inner cone half-angle in degrees, in [0, outerCone); defaults to 0. Refused on non-spot lights when non-zero.
InnerCone float32 `yaml:"innerCone,omitempty" schema:"minimum=0,maximum=90"`
// OuterCone is a spot light's outer cone half-angle in degrees, in (0, 90]; nil defaults to 45 for spot lights. Refused on non-spot lights.
OuterCone *float32 `yaml:"outerCone,omitempty" schema:"exclusiveMinimum=0,maximum=90"`
// Shadows enables shadow casting for this light.
Shadows bool `yaml:"shadows,omitempty"`
}LightDoc configures a 3D light attached to an object (ObjectDoc.Light). Its world position and forward direction (local -Z) come from the object's 3D transform. Version 4.
func (l *LightDoc) Clone() *LightDocClone returns a deep copy of l, or nil when l is nil.
func (l *LightDoc) EffectiveColor() stringEffectiveColor returns l.Color, defaulting to "#ffffff" when empty.
func (l *LightDoc) EffectiveIntensity() float32EffectiveIntensity returns l.Intensity, defaulting to 1 when nil.
func (l *LightDoc) EffectiveOuterCone() float32EffectiveOuterCone returns a spot light's outer cone half-angle in degrees, defaulting to 45 when nil.
type LightKind stringLightKind selects the kind of 3D light an object emits (LightDoc.Kind).
const (
// LightDirectional is an infinitely distant light whose parallel rays travel along the object's local -Z axis.
LightDirectional LightKind = "directional"
// LightPoint is an omnidirectional punctual light shining from the object's position.
LightPoint LightKind = "point"
// LightSpot is a cone-shaped punctual light at the object's position shining along its local -Z axis.
LightSpot LightKind = "spot"
)type LightProbeGridDoc struct {
// Center is the optional local-space center [x, y, z] of the grid volume relative to the object's origin; nil centers it at [0, 0, 0].
Center *[3]float32 `yaml:"center,omitempty,flow"`
// Size is the local-space [width, height, depth] extents of the grid volume; nil defaults to [10, 6, 10]. When set, every axis must be finite and positive.
Size *[3]float32 `yaml:"size,omitempty,flow"`
// Counts is the number of probes [nx, ny, nz] along X, Y and Z; nil defaults to [3, 2, 3]. Each axis must be positive and nx*ny*nz at most MaxLightProbesPerGrid (4096).
Counts *[3]int `yaml:"counts,omitempty,flow"`
// Intensity scales the grid's diffuse irradiance contribution; nil defaults to 1. Must be finite and non-negative.
Intensity *float32 `yaml:"intensity,omitempty" schema:"minimum=0"`
// Data optionally names the baked light probe YAML file by its slash-separated path from the project root, such as "probes/room.probes.yaml".
Data string `yaml:"data,omitempty"`
}LightProbeGridDoc configures a 3D light probe grid attached to an object (ObjectDoc.LightProbeGrid). The grid places Counts[0] x Counts[1] x Counts[2] diffuse L2 spherical harmonic irradiance probes uniformly across the axis-aligned volume defined by Center and Size in local space. Version 4.
func (g *LightProbeGridDoc) Clone() *LightProbeGridDocClone returns a deep copy of g, or nil when g is nil.
func (g *LightProbeGridDoc) EffectiveCenter() [3]float32EffectiveCenter returns g.Center, defaulting to [0, 0, 0] when nil.
func (g *LightProbeGridDoc) EffectiveCounts() [3]intEffectiveCounts returns g.Counts, defaulting to [3, 2, 3] when nil or all zero.
func (g *LightProbeGridDoc) EffectiveIntensity() float32EffectiveIntensity returns g.Intensity, defaulting to 1 when nil.
func (g *LightProbeGridDoc) EffectiveSize() [3]float32EffectiveSize returns g.Size, defaulting to [10, 6, 10] when nil or all zero.
func (g *LightProbeGridDoc) LocalBounds() (lo, hi [3]float32)LocalBounds returns the local-space min and max corners of the grid's volume.
type MaterialResolver interface {
Material(path string) (*resource.Material, error)
}MaterialResolver may optionally be implemented by an AssetResolver to load the shared material files objects name in ObjectDoc.Material. A resolver that returns the same pointer for the same path, as resource.Library does, lets every scene using one file see its edits.
type MergeConflict struct {
// Kind is ConflictField, ConflictDeleteModify, ConflictAddAdd, ConflictMove or ConflictValidation.
Kind ConflictKind `yaml:"kind"`
// Scope is "scene", "layer", "object", "connection", "tilemap", "override" or "layerOverride".
Scope string `yaml:"scope"`
// Layer names the layer when the conflict is on a layer or an object inside a layer.
Layer string `yaml:"layer,omitempty"`
// Object is the object's ID when Scope is "object".
Object string `yaml:"object,omitempty"`
// Target identifies non-object items (such as a connection signature, tilemap name or override key).
Target string `yaml:"target,omitempty"`
// Field names the conflicting field path (such as "x", "components.patrol.speed", or "parent").
Field string `yaml:"field,omitempty"`
// Message describes the conflict in plain text when needed (such as delete/modify or validation errors).
Message string `yaml:"message,omitempty"`
// Base is the ancestor value, or nil when absent.
Base any `yaml:"base"`
// Ours is the current branch's value, or nil when absent or deleted.
Ours any `yaml:"ours"`
// Theirs is the other branch's value, or nil when absent or deleted.
Theirs any `yaml:"theirs"`
}MergeConflict describes one unresolved conflict in a three-way scene merge.
func (c MergeConflict) Summary() stringformatConflictSummary returns a single-line human-readable description of c for CLI diagnostics.
type MergeResult struct {
// Doc is the merged scene document. When len(Conflicts) == 0, Doc passes
// Validate and can be written directly with Encode. When len(Conflicts) > 0,
// Doc holds the best-effort merged scene (preferring ours on conflicted
// fields) for tools such as an editor conflict resolver.
Doc *SceneDoc
// Merged lists items joined cleanly by identity from one or both sides,
// sorted deterministically.
Merged []MergedItem
// Conflicts lists every conflict encountered, sorted deterministically.
// Empty on a clean merge.
Conflicts []MergeConflict
}MergeResult is the outcome of a three-way scene merge.
func Merge(base, ours, theirs *SceneDoc) (*MergeResult, error)Merge performs an identity-based three-way merge of base, ours and theirs.
Layers are matched by name, objects by id anywhere in the scene tree (including across reparenting and layer moves), tilemaps and overrides by key, and connections by (from, event, to, handler). Fields are merged one by one so edits to different objects or different fields on the same object combine cleanly.
base may be nil for an add/add merge where both branches created the scene independently. ours and theirs must be non-nil valid SceneDoc values (and base, if non-nil, must be valid). The combined result is validated with Validate; a merged document that fails validation is reported as a ConflictValidation conflict.
func (r *MergeResult) ConflictDoc(scenePath string) *ConflictDocConflictDoc returns a versioned ConflictDoc for scenePath when r has conflicts, or nil when the merge is clean.
func (r *MergeResult) HasConflicts() boolHasConflicts reports whether the merge encountered any conflicts.
type MergedItem struct {
// Scope is "scene", "layer", "object", "connection", "tilemap", "override" or "layerOverride".
Scope string `yaml:"scope"`
// Target identifies the item: object ID, layer name, connection signature, or map key.
Target string `yaml:"target,omitempty"`
// Side is "ours", "theirs" or "both".
Side string `yaml:"side"`
// Action is "added", "changed", "deleted" or "moved".
Action string `yaml:"action"`
}MergedItem records one scene item that the merge driver combined cleanly by identity without a conflict.
type ModelResolver interface {
Model(path string) (*gltf.Document, error)
}ModelResolver may optionally be implemented by an AssetResolver (such as *scenemodel.Assets) to load glTF models referenced by convex or trimesh 3D colliders. If the resolver instead implements FileResolver (such as *project.Resolver or FSAssets), BuildPhysics loads models from it automatically via gltf.LoadFS.
type NavRegion2DDebug struct {
// WorldVertices are the transformed closed polygon vertices in world space.
}NavRegion2DDebug describes a resolved navregion2d component in local and world space for editor overlays and polygon handles.
func ExtractNavRegion2D(o *ObjectDoc, world *math2d.Affine) (NavRegion2DDebug, bool, error)ExtractNavRegion2D resolves a navregion2d component from o at world (or o's local transform when world is nil).
type Nodes3D struct {
// Layers maps each layer name to its group node, a child of the parent given to BuildNodes3D with an identity transform and the layer's visibility.
Layers map[string]*scene3d.Node
// Objects maps each object ID, children included, to its node.
Objects map[string]*scene3d.Node
}Nodes3D is the 3D node tree BuildNodes3D builds from a scene.
func BuildNodes3D(doc *SceneDoc, parent *scene3d.Node) (*Nodes3D, error)BuildNodes3D validates doc and builds its layers and objects into a 3D node tree under parent, such as a scene3d.Scene's Root. Each layer becomes a group node named after the layer, in document order, and each object a node named by its ID under its layer's node or its parent object's node, children in document order. An object's local transform is its ObjectLocalTransform3D, and its node's UserData is the *ObjectDoc it came from (a pointer into doc).
BuildNodes3D returns an error and leaves parent unchanged when doc is invalid, still instances or inherits other scene files (pass it through Resolve first), or parent is nil.
type ObjectDoc struct {
// ID uniquely identifies the object across the entire scene.
ID string `yaml:"id" schema:"required,minLength=1"`
// Name is an optional human-readable display name.
Name string `yaml:"name,omitempty"`
// Prefab optionally names a prefab or archetype template.
Prefab string `yaml:"prefab,omitempty"`
// X and Y are where the object's origin sits in its parent's space, which for a top-level object is its layer's coordinate space.
X float32 `yaml:"x,omitempty"`
Y float32 `yaml:"y,omitempty"`
// PosZ is the optional 3D Z coordinate (depth in 3D scenes) in its parent's space, distinct from 2D draw order Z.
PosZ float32 `yaml:"posZ,omitempty"`
// OriginX and OriginY are the pivot point inside the sprite's untrimmed frame.
OriginX float32 `yaml:"originX,omitempty"`
OriginY float32 `yaml:"originY,omitempty"`
// Rotation turns the object clockwise in radians about its origin in 2D space.
Rotation float32 `yaml:"rotation,omitempty"`
// RotX, RotY, and RotZ are optional 3D Euler rotations in radians about the X, Y, and Z axes, applied in that order about fixed axes (the rotation Rz * Ry * Rx).
RotX float32 `yaml:"rotX,omitempty"`
RotY float32 `yaml:"rotY,omitempty"`
RotZ float32 `yaml:"rotZ,omitempty"`
// ScaleX, ScaleY, and ScaleZ scale the object about its origin; nil defaults to 1. Negative mirrors.
ScaleX *float32 `yaml:"scaleX,omitempty"`
ScaleY *float32 `yaml:"scaleY,omitempty"`
ScaleZ *float32 `yaml:"scaleZ,omitempty"`
// Depth is the optional 3D extent along the Z axis in world units; 0 uses a default extent.
Depth float32 `yaml:"depth,omitempty" schema:"minimum=0"`
// Mesh optionally names the built-in primitive the object draws in 3D: "box", "sphere", "plane", "capsule" or "cylinder" (MeshPrimitives lists them, and package scenemodel builds them). It cannot be combined with Model; scale the object to size the primitive.
Mesh string `yaml:"mesh,omitempty" schema:"enum=box|sphere|plane|capsule|cylinder"`
// Model optionally names the glTF 2.0 model the object draws in 3D, a .gltf or .glb file named by its slash-separated path from the project root, such as "models/crate.glb". Without ModelNode or ModelMesh the object draws every node of the model's default scene; package scenemodel loads it through a ModelResolver. Version 2.
Model string `yaml:"model,omitempty"`
// ModelNode optionally names one node of Model, the first with that name in the file, which the object draws with its descendants in place of the whole model; the object's own transform replaces the node's. It requires Model and cannot be combined with ModelMesh. Version 2.
ModelNode string `yaml:"modelNode,omitempty"`
// ModelMesh optionally names one mesh of Model, the first with that name in the file, which the object draws at its origin in place of the whole model. It requires Model and cannot be combined with ModelNode. Version 2.
ModelMesh string `yaml:"modelMesh,omitempty"`
// GridMap optionally names a 3D grid map file (*.gridmap.yaml or *.gridmap.yml) by its slash-separated path from the project root, such as "levels/dungeon.gridmap.yaml". Package scenemodel loads it and instances its tiles with world3d.GridMap.BuildInstances. It cannot be combined with Mesh or Model. Version 2.
GridMap string `yaml:"gridMap,omitempty"`
// Occluder optionally marks this 3D object as an occluder for render3d.OcclusionBuffer, using either its own 3D geometry (mode "model") or an explicit local-space box (mode "box"). Version 2.
Occluder *OccluderDoc `yaml:"occluder,omitempty"`
// FlipX and FlipY mirror the sprite inside its untrimmed frame box.
FlipX bool `yaml:"flipX,omitempty"`
FlipY bool `yaml:"flipY,omitempty"`
// Alpha is the object's opacity in [0, 1]; nil defaults to 1.
Alpha *float32 `yaml:"alpha,omitempty" schema:"minimum=0,maximum=1"`
// Z orders objects within the layer, children included; lower Z draws first, and ties keep document order with each parent before its children.
Z int `yaml:"z,omitempty"`
// Sprite optionally binds the object to a frame in a sprite.Atlas.
Sprite *SpriteRef `yaml:"sprite,omitempty"`
// Material optionally names a shared material resource file by its slash-separated path from the project root, such as "materials/stone.material.yaml". Build resolves it through a MaterialResolver; the sprite draws with the material's opacity and blend mode, so every scene that uses the file changes when it is edited. In 3D it replaces every material of the object's Model, or gives its Mesh primitive its surface (package scenemodel).
Material string `yaml:"material,omitempty"`
// Particles optionally binds the object to a 2D particle emitter YAML file (particles.Config) and optional sprite atlas, so Build constructs a live particles.Emitter that BuiltScene.Update steps and BuiltScene.Draw renders at the object's world transform. Version 2.
Particles *ParticlesRef `yaml:"particles,omitempty"`
// Light optionally attaches a directional, point or spot 3D light to this object, placed and aimed by its 3D transform (local -Z). Version 4.
Light *LightDoc `yaml:"light,omitempty"`
// Camera optionally attaches a perspective or orthographic 3D camera to this object, placed and oriented by its 3D transform (looking down local -Z). Version 4.
Camera *Camera3DDoc `yaml:"camera,omitempty"`
// ReflectionProbe optionally attaches a local 3D reflection probe volume to this object, capturing reflections from its world position over its influence box. Version 4.
ReflectionProbe *ReflectionProbeDoc `yaml:"reflectionProbe,omitempty"`
// LightProbeGrid optionally attaches a regular 3D lattice of diffuse L2 spherical harmonic irradiance probes to this object. Version 4.
LightProbeGrid *LightProbeGridDoc `yaml:"lightProbeGrid,omitempty"`
// Components holds structured component data keyed by component type name.
Components map[string]any `yaml:"components,omitempty"`
// Properties holds arbitrary custom metadata for gameplay scripts or editors. Encode writes a whole-number float with a decimal point (2.0), so that every value reads back with the kind it was written with.
Properties map[string]any `yaml:"properties,omitempty"`
// Scene optionally instances another scene file, named by its slash-separated path from the project root such as "scenes/enemy.scene.yaml". Resolve makes the top-level objects of every layer of that scene, in document order, this object's first children, ahead of the ones in Children, with each instanced object's ID prefixed by this object's ID and a slash ("enemy_1/body"). The instanced scene's layer settings, camera, background and virtual size do not carry over, and a scene whose layers hold a tilemap cannot be instanced. Version 2.
Scene string `yaml:"scene,omitempty"`
// Overrides changes objects of the instanced Scene, keyed by their IDs inside that scene ("body", or "gun/barrel" for an object of a scene it instances in turn); it requires Scene. Version 2.
Overrides map[string]ObjectOverride `yaml:"overrides,omitempty"`
// Children are objects attached to this one, in document order. A child's transform (X, Y, Rotation, ScaleX, ScaleY, and in 3D PosZ, RotX, RotY, RotZ, ScaleZ) is local to this object, and its alpha multiplies this object's. Children belong to their parent's layer; their IDs share the scene-wide namespace, and nesting is limited to MaxObjectDepth levels.
Children []ObjectDoc `yaml:"children,omitempty"`
}ObjectDoc is one entity or visual object placed on a layer.
func (o *ObjectDoc) Clone() ObjectDocClone returns a deep copy of o: its children, overrides, sprite, optional values and maps are all new, so changing the copy never changes o.
func (o *ObjectDoc) EffectiveAlpha() float32EffectiveAlpha returns Alpha, defaulting to 1 when nil.
func (o *ObjectDoc) EffectiveScaleX() float32EffectiveScaleX returns ScaleX, defaulting to 1 when nil.
func (o *ObjectDoc) EffectiveScaleY() float32EffectiveScaleY returns ScaleY, defaulting to 1 when nil.
func (o *ObjectDoc) EffectiveScaleZ() float32EffectiveScaleZ returns ScaleZ, defaulting to 1 when nil.
func (o *ObjectDoc) LocalTransform() math2d.AffineLocalTransform returns the object's 2D transform relative to its parent (or to its layer for a top-level object): translate by (X, Y), rotate by Rotation, then scale by (ScaleX, ScaleY). OriginX, OriginY and the flips place a sprite inside this space and are not part of it.
type ObjectOverride struct {
// Name replaces the object's name.
Name *string `yaml:"name,omitempty"`
// Prefab replaces the prefab the object names.
Prefab *string `yaml:"prefab,omitempty"`
// X replaces where the object's origin sits along x in its parent's space.
X *float32 `yaml:"x,omitempty"`
// Y replaces where the object's origin sits along y in its parent's space.
Y *float32 `yaml:"y,omitempty"`
// PosZ replaces the object's 3D Z coordinate in its parent's space.
PosZ *float32 `yaml:"posZ,omitempty"`
// OriginX replaces the x of the object's pivot point.
OriginX *float32 `yaml:"originX,omitempty"`
// OriginY replaces the y of the object's pivot point.
OriginY *float32 `yaml:"originY,omitempty"`
// Rotation replaces the object's clockwise 2D rotation in radians.
Rotation *float32 `yaml:"rotation,omitempty"`
// RotX replaces the object's rotation about the x axis in 3D.
RotX *float32 `yaml:"rotX,omitempty"`
// RotY replaces the object's rotation about the y axis in 3D.
RotY *float32 `yaml:"rotY,omitempty"`
// RotZ replaces the object's rotation about the z axis in 3D.
RotZ *float32 `yaml:"rotZ,omitempty"`
// ScaleX replaces the object's x scale.
ScaleX *float32 `yaml:"scaleX,omitempty"`
// ScaleY replaces the object's y scale.
ScaleY *float32 `yaml:"scaleY,omitempty"`
// ScaleZ replaces the object's z scale in 3D.
ScaleZ *float32 `yaml:"scaleZ,omitempty"`
// Depth replaces the object's 3D extent along the Z axis.
Depth *float32 `yaml:"depth,omitempty" schema:"minimum=0"`
// Mesh replaces the built-in 3D primitive the object draws; "" removes it, as an override that gives the object a Model in place of a primitive must.
Mesh *string `yaml:"mesh,omitempty" schema:"enum=|box|sphere|plane|capsule|cylinder"`
// Model replaces the glTF model the object draws, a slash-separated path from the project root.
Model *string `yaml:"model,omitempty"`
// ModelNode replaces the node of the model the object draws.
ModelNode *string `yaml:"modelNode,omitempty"`
// ModelMesh replaces the mesh of the model the object draws.
ModelMesh *string `yaml:"modelMesh,omitempty"`
// GridMap replaces the 3D grid map file the object draws, a slash-separated path from the project root; "" removes it.
GridMap *string `yaml:"gridMap,omitempty"`
// Occluder replaces the object's 3D occluder definition.
Occluder *OccluderDoc `yaml:"occluder,omitempty"`
// FlipX replaces whether the sprite is mirrored horizontally.
FlipX *bool `yaml:"flipX,omitempty"`
// FlipY replaces whether the sprite is mirrored vertically.
FlipY *bool `yaml:"flipY,omitempty"`
// Alpha replaces the object's opacity, in [0, 1].
Alpha *float32 `yaml:"alpha,omitempty" schema:"minimum=0,maximum=1"`
// Z replaces the object's draw order within its layer.
Z *int `yaml:"z,omitempty"`
// Sprite replaces the atlas frame the object draws.
Sprite *SpriteRef `yaml:"sprite,omitempty"`
// Material replaces the material resource file the object names, a slash-separated path from the project root.
Material *string `yaml:"material,omitempty"`
// Particles replaces the particle emitter file and optional atlas the object runs.
Particles *ParticlesRef `yaml:"particles,omitempty"`
// Light replaces the 3D light attached to the object. Version 4.
Light *LightDoc `yaml:"light,omitempty"`
// Camera replaces the 3D camera attached to the object. Version 4.
Camera *Camera3DDoc `yaml:"camera,omitempty"`
// ReflectionProbe replaces the 3D reflection probe attached to the object. Version 4.
ReflectionProbe *ReflectionProbeDoc `yaml:"reflectionProbe,omitempty"`
// LightProbeGrid replaces the 3D light probe grid attached to the object. Version 4.
LightProbeGrid *LightProbeGridDoc `yaml:"lightProbeGrid,omitempty"`
// Components replaces the object's components key by key, keeping the others.
Components map[string]any `yaml:"components,omitempty"`
// Properties replaces the object's custom properties key by key, keeping the others.
Properties map[string]any `yaml:"properties,omitempty"`
}ObjectOverride changes one object of an instanced or inherited scene (ObjectDoc.Overrides, SceneDoc.Overrides). Each field set replaces the ObjectDoc field of the same name; a field left unset keeps it. Components and Properties replace the object's entries key by key and keep its other keys. An override cannot change an object's ID or children, or what it instances.
type ObjectRef struct {
// ID is the object's unique scene ID.
ID string
// Layer is the name of the layer the object belongs to.
Layer string
}ObjectRef is the component SpawnEntities attaches to every entity it spawns, naming the scene object the entity came from.
type Occluder2DDebug struct {
Shape string
Width float32
Height float32
OffsetX float32
OffsetY float32
Points [][2]float64
Layer string
TileLayers []string
Enabled bool
// WorldVertices are the transformed closed polygon corners/vertices in world space (for rect and polygon shapes).
WorldVertices []core.Point
}Occluder2DDebug describes a resolved occluder2d component in local and world space for editor overlays and shape handles.
func ExtractOccluder2D(o *ObjectDoc, world *math2d.Affine) (Occluder2DDebug, bool, error)ExtractOccluder2D resolves an occluder2d component from o at world (or o's local transform when world is nil).
type OccluderDoc struct {
// Mode selects the occluder geometry: "model" (the object's own Mesh or Model) or "box" (an explicit local-space solid box).
Mode OccluderMode `yaml:"mode" schema:"required,enum=model|box"`
// Center is the optional local-space center [x, y, z] of a "box" occluder; nil centers it at the object's origin. Only valid when Mode is "box".
Center *[3]float32 `yaml:"center,omitempty,flow"`
// Size is the optional local-space dimensions [width, height, depth] of a "box" occluder; nil defaults to [1, 1, 1], scaled by the object's transform. When set, every axis must be positive. Only valid when Mode is "box".
Size *[3]float32 `yaml:"size,omitempty,flow"`
// DoubleSided rasterizes both front and back faces of a "model" occluder when true.
DoubleSided bool `yaml:"doubleSided,omitempty"`
}OccluderDoc marks a 3D object as an occluder that hides objects behind it in render3d.OcclusionBuffer (ObjectDoc.Occluder). Version 2.
func (o *OccluderDoc) EffectiveCenter() [3]float32EffectiveCenter returns Center, defaulting to [0, 0, 0] when nil.
func (o *OccluderDoc) EffectiveSize() [3]float32EffectiveSize returns Size, defaulting to [1, 1, 1] when nil or all zero.
func (o *OccluderDoc) LocalBounds() (lo, hi [3]float32)LocalBounds returns the local-space min and max corners of a "box" occluder.
type OccluderMode stringOccluderMode selects the geometry a 3D object contributes to a render3d.OcclusionBuffer (OccluderDoc.Mode).
const (
// OccluderModel uses the object's own 3D geometry (Mesh primitive or glTF Model) as an occluder.
OccluderModel OccluderMode = "model"
// OccluderBox uses an explicit local-space solid box (Center, Size) transformed by the object's world matrix as an occluder.
OccluderBox OccluderMode = "box"
)type ParseOptions struct {
// File names the source in errors, such as "scenes/level1.scene.yaml": the File of a *ComponentError or of a *loaderr.Error. Empty leaves it unnamed.
File string
// Components, when non-nil, checks every object's components against the registered types: an unregistered type, a misspelled or unknown field, a value of the wrong kind or out of range fails the load with a *ComponentError carrying File, Line and Column. It also checks the scene's connections, unless the scene instances or inherits other scene files whose objects they may name: an event or handler no component of its object declares, and an argument the handler has no param for or of the wrong kind or out of range, fail the load with a *ConnectionError carrying File, Line and Column.
Components *ComponentRegistry
// PhysicsLayers, when non-nil, validates every named collision layer and mask in built-in physics components (collider2d, trigger2d, collider3d, trigger3d) against the table. An unknown or misspelled layer name fails the load with a *loaderr.Error carrying File and 1-based Line and Column.
PhysicsLayers *PhysicsLayerTable
}ParseOptions configures ParseWith.
type ParticlesRef struct {
// File is the slash-separated path from the project root to a particle emitter YAML file, such as "fx/fire.particles.yaml".
File string `yaml:"file" schema:"required,minLength=1"`
// Atlas optionally names the sprite.Atlas an AssetResolver looks up to resolve the emitter's frameNames.
Atlas string `yaml:"atlas,omitempty"`
}ParticlesRef binds an object to a versioned 2D particle emitter YAML file (particles.Config) and an optional sprite atlas for its frameNames.
type ParticlesResolver interface {
Particles(path string) (particles.Config, error)
}ParticlesResolver may optionally be implemented by an AssetResolver to load particle emitter definitions named by ObjectDoc.Particles. When not implemented, Build reads the file through FileResolver (such as FSAssets) and decodes it with particles.UnmarshalConfigYAML.
type PhysicsDebugShape2D struct {
Shape physics.Shape
Angle float32
IsTrigger bool
BodyKind string // "static", "kinematic", "dynamic", or "" for trigger-only
}PhysicsDebugShape2D describes a 2D collider or trigger outline extracted from an ObjectDoc for editor debug drawing.
func ExtractPhysicsDebug2D(o *ObjectDoc, world *math2d.Affine) []PhysicsDebugShape2DExtractPhysicsDebug2D extracts any 2D collider and trigger shapes from o at its current transform for debug drawing.
type PhysicsDebugShape3D struct {
Shape physics3d.Shape
TriMesh *physics3d.TriMeshCollider
Heightfield *physics3d.HeightfieldCollider
IsTrigger bool
BodyKind string
}PhysicsDebugShape3D describes a 3D collider or trigger wireframe extracted from an ObjectDoc for editor debug drawing.
func ExtractPhysicsDebug3D(o *ObjectDoc) []PhysicsDebugShape3DExtractPhysicsDebug3D extracts any 3D collider and trigger shapes from o using its local transform.
func ExtractPhysicsDebug3DAt(o *ObjectDoc, world math3d.Transform) []PhysicsDebugShape3DExtractPhysicsDebug3DAt extracts any 3D collider and trigger shapes from o at the given composed world transform.
func ExtractPhysicsDebug3DAtWithResolver(o *ObjectDoc, world math3d.Transform, resolver AssetResolver) []PhysicsDebugShape3DExtractPhysicsDebug3DAtWithResolver extracts any 3D collider and trigger shapes from o at the given composed world transform, using resolver (when non-nil) to load glTF models for convex/trimesh colliders and terrains for heightfield colliders.
type PhysicsLayerDef struct {
Name string
Bit int
}PhysicsLayerDef maps one human-readable collision layer name to a bit index in [0, 31].
type PhysicsLayerTable struct {
// contains filtered or unexported fields
}PhysicsLayerTable resolves human-readable collision layer names (such as "player", "walls", "coins") to 32-bit layer bitmasks used by physics and physics3d.
func MustPhysicsLayerTable(defs []PhysicsLayerDef) *PhysicsLayerTableMustPhysicsLayerTable is NewPhysicsLayerTable for tests and setup code; it panics on error.
func NewPhysicsLayerTable(defs []PhysicsLayerDef) (*PhysicsLayerTable, error)NewPhysicsLayerTable builds a validated collision layer table from defs. It refuses empty names, duplicate names, bits outside [0, 31], and duplicate bit indices.
func (t *PhysicsLayerTable) Bit(name string) (uint, bool)Bit returns the bit index in [0, 31] assigned to name and whether name is declared.
func (t *PhysicsLayerTable) Mask2D(names ...string) (physics.LayerMask, error)Mask2D resolves names into a 2D physics.LayerMask. Empty names returns 0 (which defaults to LayerAll).
func (t *PhysicsLayerTable) Mask3D(names ...string) (physics3d.LayerMask, error)Mask3D resolves names into a 3D physics3d.LayerMask. Empty names returns 0 (which defaults to LayerAll).
func (t *PhysicsLayerTable) Names() []stringNames returns all declared layer names in ascending order.
type PhysicsMaterialResolver interface {
PhysicsMaterial(path string) (*resource.PhysicsMaterial, error)
}PhysicsMaterialResolver may optionally be implemented by an AssetResolver (such as *resource.Library) to load shared .physics.yaml materials named by body2d.material and body3d.material / body3d.physicsMaterial.
type PhysicsScene struct {
// Scene is the BuiltScene this PhysicsScene drives.
Scene *BuiltScene
// World2D holds all 2D bodies (dynamic mirrors, kinematic, static) and 2D triggers for queries and trigger callbacks.
World2D *physics.World
// Rigid2D simulates 2D dynamic and static rigid bodies with impulses, friction, and restitution.
Rigid2D *physics.RigidWorld
// World3D simulates 3D static, kinematic, dynamic bodies, and 3D triggers.
World3D *physics3d.World
// Bodies2D maps object IDs to their 2D query/kinematic Body.
Bodies2D map[string]*physics.Body
// RigidBodies2D maps object IDs to their 2D RigidBody.
RigidBodies2D map[string]*physics.RigidBody
// Triggers2D maps object IDs to their 2D Trigger.
Triggers2D map[string]*physics.Trigger
// Bodies3D maps object IDs to their 3D Body (including 3D triggers with IsTrigger == true).
Bodies3D map[string]*physics3d.Body
// TriMeshes3D maps object IDs to their static 3D triangle-mesh colliders.
TriMeshes3D map[string]*physics3d.TriMeshCollider
// Heightfields3D maps object IDs to their static 3D terrain heightfield colliders.
Heightfields3D map[string]*physics3d.HeightfieldCollider
// OnTrigger is called deterministically for every 2D and 3D trigger enter/stay/exit transition during Step.
OnTrigger func(PhysicsTriggerEvent)
// Signals, when non-nil, receives enter/stay/exit events emitted from trigger objects during Step.
Signals *Signals
// contains filtered or unexported fields
}PhysicsScene holds the 2D and 3D physics worlds constructed from a BuiltScene's built-in physics components. Calling Step advances 2D rigid bodies, 2D kinematic bodies, 2D triggers, and 3D bodies/triggers deterministically, synchronizing simulated transforms back into the BuiltScene's objects so sprites and 3D wireframes move live.
func BuildPhysics(scene *BuiltScene, settings *PhysicsSettings, resolver AssetResolver) (*PhysicsScene, error)BuildPhysics constructs 2D and 3D physics worlds from scene's built-in physics components (body2d, collider2d, trigger2d, body3d, collider3d, trigger3d). settings may be nil (using default gravity, default solver iterations, and no named layers). resolver may be nil unless a body component specifies a shared .physics.yaml material path.
func (ps *PhysicsScene) HasPhysics() boolHasPhysics reports whether ps contains at least one 2D or 3D body, collider, or trigger.
func (ps *PhysicsScene) Step(dt time.Duration)Step advances the 2D and 3D physics simulations by dt, resolves collisions and triggers, and writes updated positions and rotations back onto the BuiltScene's objects.
func (ps *PhysicsScene) TriggerEvents() []PhysicsTriggerEventTriggerEvents returns the trigger events produced by the most recent Step call.
type PhysicsSettings struct {
// HasGravity2D reports whether Gravity2D overrides the default (0, 0) 2D gravity.
HasGravity2D bool
// Gravity2D is the 2D gravity vector in points per second squared.
Gravity2D math2d.Vec2
// HasGravity3D reports whether Gravity3D overrides physics3d's default (0, -9.81, 0) gravity.
HasGravity3D bool
// Gravity3D is the 3D gravity vector in units per second squared.
Gravity3D physics3d.Vec3
// SolverIterations2D overrides RigidWorld.SolverIterations when positive.
SolverIterations2D int
// SolverIterations3D overrides physics3d.World.SolverIterations when positive.
SolverIterations3D int
// Layers maps named collision layers (from game.yaml physics.layers) to bit indices 0..31.
Layers *PhysicsLayerTable
}PhysicsSettings configures the 2D and 3D physics worlds constructed by BuildPhysics.
type PhysicsTriggerEvent struct {
Kind PhysicsTriggerEventKind
TriggerID string
BodyID string
Is3D bool
}PhysicsTriggerEvent records one trigger overlap transition emitted during PhysicsScene.Step.
type PhysicsTriggerEventKind intPhysicsTriggerEventKind identifies enter, stay, or exit transitions on built scene triggers.
const (
// TriggerEnter fires on the first step a matching body overlaps a trigger.
TriggerEnter PhysicsTriggerEventKind = iota
// TriggerStay fires on each subsequent step the body remains overlapping.
TriggerStay
// TriggerExit fires on the first step the body stops overlapping.
TriggerExit
)func (k PhysicsTriggerEventKind) String() stringString returns "enter", "stay", or "exit".
type Point struct {
// X is the horizontal coordinate in object-local space.
X float64 `yaml:"x"`
// Y is the vertical coordinate in object-local space.
Y float64 `yaml:"y"`
}Point is a 2D point in an object's local coordinate space, used by FieldPoint and FieldPolygon component fields.
func ParsePoint(v any) (Point, error)ParsePoint converts a component field value (Point or decoded YAML map) to a validated Point.
func ParsePolygon(v any) ([]Point, error)ParsePolygon converts a component field value ([]Point or decoded YAML sequence of maps) to a validated []Point.
func (p Point) MarshalYAML() (any, error)MarshalYAML encodes Point with deterministic key order matching YAML map decoding ("x", "y").
type ProjectionKind stringProjectionKind selects a 3D camera's projection (Camera3DDoc.Projection).
const (
// ProjectionPerspective projects a perspective view frustum.
ProjectionPerspective ProjectionKind = "perspective"
// ProjectionOrthographic projects a parallel orthographic view volume.
ProjectionOrthographic ProjectionKind = "orthographic"
)type Rect struct {
// X is the left edge coordinate in object-local space.
X float64 `yaml:"x"`
// Y is the top edge coordinate in object-local space.
Y float64 `yaml:"y"`
// Width is the horizontal extent in object-local space (non-negative).
Width float64 `yaml:"width" schema:"minimum=0"`
// Height is the vertical extent in object-local space (non-negative).
Height float64 `yaml:"height" schema:"minimum=0"`
}Rect is an axis-aligned 2D rectangle in an object's local coordinate space, used by FieldRect component fields.
func ParseRect(v any) (Rect, error)ParseRect converts a component field value (Rect or decoded YAML map) to a validated Rect.
func (r Rect) MarshalYAML() (any, error)MarshalYAML encodes Rect with deterministic alphabetical key order matching YAML map decoding ("height", "width", "x", "y").
type ReflectionProbeDoc struct {
// Center is the optional local-space center [x, y, z] of the influence box relative to the object's origin; nil centers it at [0, 0, 0].
Center *[3]float32 `yaml:"center,omitempty,flow"`
// Size is the local-space [width, height, depth] extents of the influence box; nil defaults to [10, 10, 10]. When set, every axis must be finite and positive.
Size *[3]float32 `yaml:"size,omitempty,flow"`
// BlendDistance is the inward fade width in world units from the influence box faces; 0 gives a sharp boundary. Must be finite and non-negative.
BlendDistance float32 `yaml:"blendDistance,omitempty" schema:"minimum=0"`
// Intensity scales the probe's reflected radiance; nil defaults to 1. Must be finite and non-negative.
Intensity *float32 `yaml:"intensity,omitempty" schema:"minimum=0"`
// Priority breaks ties when reflection probes overlap; higher values take precedence.
Priority int `yaml:"priority,omitempty"`
// BoxProjection enables parallax-corrected ray-AABB reflection lookup when true; nil defaults to true.
BoxProjection *bool `yaml:"boxProjection,omitempty"`
// Resolution is the cubemap face edge length in texels used when baking; 0 defaults to 64. Must be in [0, 1024].
Resolution int `yaml:"resolution,omitempty" schema:"minimum=0,maximum=1024"`
// Cubemap optionally names the baked cubemap image file by its slash-separated path from the project root, such as "probes/room_refl.hdr" (Radiance .hdr or .pic).
Cubemap string `yaml:"cubemap,omitempty"`
}ReflectionProbeDoc configures a local 3D reflection probe attached to an object (ObjectDoc.ReflectionProbe). Its cubemap is captured at the object's 3D world position and blended across the axis-aligned influence box defined by Center and Size in local space. Version 4.
func (p *ReflectionProbeDoc) Clone() *ReflectionProbeDocClone returns a deep copy of p, or nil when p is nil.
func (p *ReflectionProbeDoc) EffectiveBoxProjection() boolEffectiveBoxProjection reports whether parallax-corrected box projection is enabled, defaulting to true when nil.
func (p *ReflectionProbeDoc) EffectiveCenter() [3]float32EffectiveCenter returns p.Center, defaulting to [0, 0, 0] when nil.
func (p *ReflectionProbeDoc) EffectiveIntensity() float32EffectiveIntensity returns p.Intensity, defaulting to 1 when nil.
func (p *ReflectionProbeDoc) EffectiveResolution() intEffectiveResolution returns p.Resolution, defaulting to DefaultReflectionProbeResolution (64) when 0.
func (p *ReflectionProbeDoc) EffectiveSize() [3]float32EffectiveSize returns p.Size, defaulting to [10, 10, 10] when nil or all zero.
func (p *ReflectionProbeDoc) LocalBounds() (lo, hi [3]float32)LocalBounds returns the local-space min and max corners of the probe's influence box.
type SceneDoc struct {
// Version is the schema version, from MinVersion to CurrentVersion. Encode writes it back as it is.
Version int `yaml:"version" schema:"required"`
// UID is the scene 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 resource.NewUID returns it. Resolve keeps the UID of the scene it resolves, not its base's. Both versions accept it.
UID string `yaml:"uid,omitempty"`
// Inherits optionally names a base scene file by its slash-separated path from the project root, such as "scenes/enemy.scene.yaml". The scene then starts as a copy of its base and changes only what it declares: its own scalar fields, camera and tilemaps replace the base's when set, its Overrides and LayerOverrides change inherited objects and layers, and its Layers add objects to the base's layers of the same name or add new layers after them. Resolve applies it. Version 2.
Inherits string `yaml:"inherits,omitempty"`
// Name is the scene's human-readable name.
Name string `yaml:"name,omitempty"`
// NavMesh optionally names the scene's baked navigation mesh file by its slash-separated path from the project root, such as "levels/level1.navmesh.yaml": a navbake3d file with one mesh per agent type, which the game navmesh command writes from the scene's geometry. In a scene that inherits another, a NavMesh set replaces the base's. Both versions accept it.
// VirtualWidth and VirtualHeight are the scene's virtual viewport size in points. Both must be 0 or both positive.
VirtualWidth float32 `yaml:"virtualWidth,omitempty" schema:"minimum=0"`
VirtualHeight float32 `yaml:"virtualHeight,omitempty" schema:"minimum=0"`
// BackgroundColor is an optional CSS color string parsed with core.ParseColor.
BackgroundColor string `yaml:"backgroundColor,omitempty"`
// AmbientColor is an optional CSS color string parsed with core.ParseColor (for example "rgba(12, 16, 30, 0.85)" or "#0c101ed8") that sets the 2D lighting ambient darkness tint (lights2d.Scene.Ambient). Both versions accept it.
AmbientColor string `yaml:"ambientColor,omitempty"`
// Camera holds the default camera transform for world-space layers. Nil leaves world space untransformed.
Camera *CameraDoc `yaml:"camera,omitempty"`
// Environment holds 3D sky, ambient/IBL lighting, fog, tone mapping and exposure settings. Version 4.
Environment *EnvironmentDoc `yaml:"environment,omitempty"`
// Tilemaps defines reusable named tilemaps referenced by layers via TilemapDoc.Ref.
Tilemaps map[string]*TilemapDoc `yaml:"tilemaps,omitempty"`
// LayerOverrides changes the inherited layers named by its keys; it requires Inherits. Version 2.
LayerOverrides map[string]LayerOverride `yaml:"layerOverrides,omitempty"`
// Overrides changes the inherited objects whose IDs are its keys, nested children and the objects of instanced scenes (such as "enemy_1/body") included; it requires Inherits. Version 2.
Overrides map[string]ObjectOverride `yaml:"overrides,omitempty"`
// Layers are the scene's layers, drawn lowest Order first and in slice order for equal Order. In a scene that inherits another, a layer named like one of the base's adds its objects to that layer and may set nothing else (LayerOverrides changes the layer itself), and any other layer is added after the base's layers.
Layers []LayerDoc `yaml:"layers,omitempty"`
// Connections connect events of the scene's objects to handlers of its objects, as Godot's connections in a .tscn file do, so a button can open a door with no Go code that wires the two. Connect binds them to the handlers a ComponentRegistry declares, and Resolve carries the connections of instanced and inherited scenes into the scene that uses them.
Connections []ConnectionDoc `yaml:"connections,omitempty"`
}SceneDoc is the root of a versioned YAML scene document.
func Parse(data []byte) (*SceneDoc, error)Parse decodes a YAML scene document and validates it. Unknown YAML fields and trailing YAML documents are rejected. Component payloads are not checked against any registry; use ParseWith to check them.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it, and wrap the *FieldError Validate returned for a document that decodes but breaks the schema; a caller that read data from a file names it with loaderr.WithFile, or with ParseOptions.File.
func ParseWith(data []byte, opts ParseOptions) (*SceneDoc, error)ParseWith is Parse with a source name for errors and an optional component registry. Defaults of unset component fields are not written into the document, so saving it again changes nothing; read them with ComponentRegistry.Resolve.
func Resolve(doc *SceneDoc, scenes SceneResolver) (*SceneDoc, error)Resolve validates doc and returns a copy of it with every scene it instances or inherits loaded through scenes and merged in, so that the copy refers to no other scene file. An instance object gets the instanced scene's objects, with its overrides applied, as its first children, their IDs prefixed by its own ID and a slash ("enemy_1/body"). A scene that inherits another becomes a copy of its base with its own fields, overrides, layer overrides and layers applied, as SceneDoc.Inherits describes. Connections come along: an instanced scene's connections, with the objects they name prefixed like its objects' IDs, in the order the instances appear, then the scene's own; an inheriting scene keeps its base's connections and adds its own after them. Scenes referred to in turn are resolved the same way, each file loaded once per call.
Resolve refuses a cycle of scenes that instance or inherit each other, a chain deeper than MaxSceneNesting files, a result of more than MaxResolvedObjects objects, a scene file that fails to load or validate, an instanced scene with a tilemap, an override that names no object or layer of the scene it changes, a layer that extends a base layer and sets more than its objects, and a result that does not validate, such as one whose instanced IDs collide with others. It never modifies doc or the documents scenes returns, and scenes may be nil when doc refers to no other scene. The result has doc's version.
func (doc *SceneDoc) Clone() *SceneDocClone returns a deep copy of doc: its camera, tilemaps, layers, objects, overrides, connections and maps are all new, so changing the copy never changes doc.
func (doc *SceneDoc) RefersToScenes() boolRefersToScenes reports whether doc instances or inherits another scene file, so that Resolve must load them before doc can be spawned (SpawnEntities) or built into 3D nodes (BuildNodes3D). Build resolves such a scene itself.
type SceneResolver interface {
// Scene returns the scene document at path, a slash-separated path from the project root. Resolve validates what it returns and never modifies it, so a resolver may return the same document for every request of one path.
Scene(path string) (*SceneDoc, error)
}SceneResolver loads the scene files that a scene instances (ObjectDoc.Scene) or inherits (SceneDoc.Inherits). An AssetResolver passed to Build may implement it, and FSScenes reads scene files from a file system.
type Signals struct {
// contains filtered or unexported fields
}Signals dispatches the events a scene's objects emit to the handlers its connections name. Connect makes one, and SpawnConnected makes one whose events also address the entities the objects were spawned as. Emit runs the handlers at once; Enqueue holds the event until Flush, which a game calls once per update step so that events raised during the step run after it, in the order they were raised. It is not safe for concurrent use: emit from the goroutine that runs the game's update.
func Connect(doc *SceneDoc, reg *ComponentRegistry, ctx any) (*Signals, error)Connect checks doc's components and connections against reg and returns the Signals that run them; ctx is passed to every handler as Call.Context. doc must be valid, must not instance or inherit other scene files (pass it through Resolve first, or use BuiltScene.Doc), and every connected handler must have a Func. Calls point into doc, so handlers see and may change its objects. The Signals is a snapshot of doc's objects as Connect finds them: after adding or removing objects in doc, which may also move the others in memory, call Connect again, since the old Signals would hand handlers stale objects and refuse events of the new ones.
func SpawnConnected(doc *SceneDoc, w *entities.World, reg *ComponentRegistry, ctx any) (map[string]entities.Entity, *Signals, error)SpawnConnected checks doc as Connect does and spawns its objects into w as SpawnEntities does, and returns each object ID's entity and the Signals that runs doc's connections between those entities: EmitEntity and EnqueueEntity address an object by its entity, and every Call carries the entities at both ends. doc must be valid and refer to no other scene file (pass it through Resolve first, or use BuiltScene.Doc). Every check runs before the first entity is spawned, so a scene whose connections name a missing object, event, handler or Func, or whose components break their registered types, spawns nothing.
Once an entity is destroyed, its object emits nothing: Emit, Enqueue and their entity forms refuse it, Flush drops the events it enqueued before, and the connections to it are skipped, a once connection staying connected.
func (s *Signals) Emit(from, event string, payload any) errorEmit fires the event named event of the object with ID from, passing payload, and calls the handler of every connection from that event, in the order the scene lists them. event is a bare name, such as "pressed", or "button.pressed" to say which component when several of the object's components declare it. A once connection runs the first time only. An event no connection names does nothing. Handlers run before Emit returns, so a handler that emits runs the next handlers inside the first; use Enqueue to run them after the current step instead.
Emit returns an error, and calls nothing, when the scene has no object from, when none of its registered components declares the event or two declare a bare name, when the object's entity has been destroyed (SpawnConnected), and when handlers that emit events have nested more than MaxEmitDepth levels.
func (s *Signals) EmitEntity(e entities.Entity, event string, payload any) errorEmitEntity is Emit for the object that SpawnConnected spawned as e. It returns an error when e is not one of those entities or is no longer alive.
func (s *Signals) Enqueue(from, event string, payload any) errorEnqueue checks the event as Emit does and holds it, with payload, until the next Flush, which runs its handlers in the order the events were enqueued. A handler may enqueue events, its own included, without re-entering the handlers that are running: they wait for the Flush after the one that runs it.
Enqueue returns an error, and queues nothing, when the scene has no object from, when none of its registered components declares the event or two declare a bare name, and when the object's entity has been destroyed (SpawnConnected).
func (s *Signals) EnqueueEntity(e entities.Entity, event string, payload any) errorEnqueueEntity is Enqueue for the object that SpawnConnected spawned as e. It returns an error when e is not one of those entities or is no longer alive.
func (s *Signals) Entity(id string) (entities.Entity, bool)Entity returns the entity the object with ID id was spawned as, and whether there is one: false when Connect made s, or the scene has no object id.
func (s *Signals) Flush() errorFlush runs the events enqueued before it began, in enqueue order, each as Emit would run it. Events their handlers enqueue are held for the next Flush, so one Flush always ends, even when handlers keep enqueueing each other. An event whose object's entity was destroyed after it was enqueued is dropped (SpawnConnected). Call it once per update step, such as at the end of game.Loop's Update, to run what the step raised after it.
Flush returns an error, and runs nothing, when a handler calls it: events then run only from the update, never inside another event's handlers. A handler's panic passes through Flush; the events after the one whose handler panicked stay queued, ahead of those enqueued since, for the next Flush.
func (s *Signals) Pending() intPending returns how many events Enqueue holds for the next Flush.
type SkeletonResolver interface {
Skeleton(path string) (*skeletal.SkeletonData, error)
}SkeletonResolver may optionally be implemented by an AssetResolver to load .skel.yaml rigs referenced by a "skeletal" component. Without it, Build reads the file through FileResolver and parses it with skeletal.Load.
type SkyDoc struct {
// Kind selects SkyColor ("color"), SkyGradient ("gradient") or SkyHDR ("hdr").
Kind SkyKind `yaml:"kind" schema:"required,enum=color|gradient|hdr"`
// Color is the CSS color of a SkyColor sky; empty defaults to "#141824". Refused on other sky kinds.
Color string `yaml:"color,omitempty"`
// Zenith is the upper-hemisphere CSS color of a SkyGradient sky; empty defaults to "#3d6194". Refused on other sky kinds.
Zenith string `yaml:"zenith,omitempty"`
// Horizon is the horizon-band CSS color of a SkyGradient sky; empty defaults to "#a8b8c7". Refused on other sky kinds.
Horizon string `yaml:"horizon,omitempty"`
// Ground is the lower-hemisphere CSS color of a SkyGradient sky; empty defaults to "#2b2b2e". Refused on other sky kinds.
Ground string `yaml:"ground,omitempty"`
// HDR is the slash-separated path from the project root to an equirectangular Radiance .hdr or .pic panorama for a SkyHDR sky, such as "env/studio.hdr". Required for SkyHDR and refused on other sky kinds.
HDR string `yaml:"hdr,omitempty"`
}SkyDoc configures the 3D scene sky and IBL source (EnvironmentDoc.Sky). Version 4.
func (s *SkyDoc) Clone() *SkyDocClone returns a deep copy of s, or nil when s is nil.
func (s *SkyDoc) EffectiveColor() stringEffectiveColor returns s.Color, defaulting to "#141824" when empty.
func (s *SkyDoc) EffectiveGround() stringEffectiveGround returns s.Ground, defaulting to "#2b2b2e" when empty.
func (s *SkyDoc) EffectiveHorizon() stringEffectiveHorizon returns s.Horizon, defaulting to "#a8b8c7" when empty.
func (s *SkyDoc) EffectiveZenith() stringEffectiveZenith returns s.Zenith, defaulting to "#3d6194" when empty.
type SkyKind stringSkyKind selects how the 3D scene sky background and environment map are generated (SkyDoc.Kind).
const (
// SkyColor fills the sky background with a single solid color (SkyDoc.Color).
SkyColor SkyKind = "color"
// SkyGradient draws a procedural three-band gradient sky from Zenith through Horizon to Ground.
SkyGradient SkyKind = "gradient"
// SkyHDR loads an equirectangular Radiance .hdr panorama from SkyDoc.HDR into an HDR cubemap for both skybox rendering and image-based lighting.
SkyHDR SkyKind = "hdr"
)type Space stringSpace is the coordinate space a layer draws in.
const (
// SpaceWorld draws the layer under the scene's camera transform.
SpaceWorld Space = "world"
// SpaceScreen draws the layer directly in canvas coordinates, ignoring the camera.
SpaceScreen Space = "screen"
)type SpriteRef struct {
// Atlas names the sprite.Atlas an AssetResolver looks up.
Atlas string `yaml:"atlas" schema:"required,minLength=1"`
// Frame names the frame inside the atlas.
Frame string `yaml:"frame" schema:"required,minLength=1"`
}SpriteRef identifies one frame inside a named sprite.Atlas.
type TerrainResolver interface {
Terrain(path string) (*world3d.Heightmap, error)
}TerrainResolver may optionally be implemented by an AssetResolver to load *world3d.Heightmap assets referenced by heightfield 3D colliders. If the resolver instead implements FileResolver (such as *project.Resolver or FSAssets), BuildPhysics loads *.terrain.yaml files from it automatically via world3d.LoadTerrainFS.
type TileLayerDoc struct {
// Name identifies the layer within its tilemap; tilemap.Tilemap.Layer finds it by this name once built.
Name string `yaml:"name" schema:"required,minLength=1"`
// Visible controls whether the layer draws; nil defaults to true.
Visible *bool `yaml:"visible,omitempty"`
// Opacity is the layer's opacity in [0, 1]; nil defaults to 1.
Opacity *float32 `yaml:"opacity,omitempty" schema:"minimum=0,maximum=1"`
// Rows are the layer's Height rows from the top, each Width cells separated by spaces. A cell is "." when empty, or the local ID of a tile of the tileset (0, 1, ...) followed by any of h, v and d to flip it horizontally, vertically or across its diagonal, as Tiled's flip bits do: "3", "3h" and "3hvd". Encode writes the cells separated by single spaces with the letters in the order h, v, d.
Rows []string `yaml:"rows,omitempty"`
}TileLayerDoc is one named layer of tiles of a layered grid (TilemapDoc.TileLayers), the text counterpart of one of Godot's TileMapLayer nodes.
func (l *TileLayerDoc) Cell(col, row int) (uint32, error)Cell returns the cell at (col, row) of the layer as a tile value: 0 for an empty cell, or the tile's local ID plus 1 with tilemap's flip bits (tilemap.FlipHorizontal, FlipVertical and FlipDiagonal) set, which is the GID the cell has in the tilemap.Tilemap Build makes, whose tileset starts at GID 1.
func (l *TileLayerDoc) Cells() ([]uint32, error)Cells returns the layer's cells row by row from the top, as Cell returns each.
func (l *TileLayerDoc) EffectiveOpacity() float32EffectiveOpacity returns Opacity, defaulting to 1 when nil.
func (l *TileLayerDoc) IsVisible() boolIsVisible reports whether the tile layer is visible, defaulting to true when Visible is nil.
func (l *TileLayerDoc) SetCell(col, row int, cell uint32) errorSetCell sets the cell at (col, row) of the layer to the tile value cell, as Cell returns it, and writes that row in the form Encode does.
type TilemapDoc struct {
// Ref names an entry in SceneDoc.Tilemaps. Only valid on a layer's Tilemap.
Ref string `yaml:"ref,omitempty"`
// Source is the slash-separated path from the project root of an external map: a Tiled map (.tmj or .tmx) or an LDtk project (.ldtk). Build loads it itself when its resolver implements FileResolver, as FSAssets does, or through a TilemapResolver.
Source string `yaml:"source,omitempty"`
// Level names the level of an LDtk Source to build; empty builds the project's first level. It requires a .ldtk Source. Build reads a source with a Level through a FileResolver even when the resolver implements TilemapResolver. Version 2.
Level string `yaml:"level,omitempty"`
// OffsetX and OffsetY shift the tilemap's top-left corner (cell 0, 0) in its layer's coordinate space in points. Version 3.
OffsetX float32 `yaml:"offsetX,omitempty"`
OffsetY float32 `yaml:"offsetY,omitempty"`
// TileWidth and TileHeight are each tile's size in points for an inline grid.
TileWidth int `yaml:"tileWidth,omitempty" schema:"minimum=0"`
TileHeight int `yaml:"tileHeight,omitempty" schema:"minimum=0"`
// Width and Height are the inline grid dimensions in tiles.
Width int `yaml:"width,omitempty" schema:"minimum=0"`
Height int `yaml:"height,omitempty" schema:"minimum=0"`
// Tileset is, for a single grid, the atlas name providing frames keyed by 1-based tile ID ("1", "2", ...).
Tileset string `yaml:"tileset,omitempty"`
// TilesetFile is, for a layered grid, the YAML tileset (*.tileset.yaml, tilemap.TilesetDoc) whose tiles the cells place, by its slash-separated path from the project root. Version 2.
TilesetFile string `yaml:"tilesetFile,omitempty"`
// Data holds a single grid's Width*Height row-major tile IDs; 0 is an empty cell.
Data []int `yaml:"data,omitempty,flow"`
// TileLayers are a layered grid's tile layers, drawn in order, each Width by Height cells, at most MaxTileLayers of them. Version 2.
TileLayers []TileLayerDoc `yaml:"tileLayers,omitempty"`
}TilemapDoc describes a tilemap in one of three modes: a reference to a named top-level tilemap (Ref), an external Tiled or LDtk map (Source), or an inline grid. An inline grid is either a single grid of atlas frame numbers (Tileset and Data) or, in version 2, a layered grid that places the tiles of a YAML tileset (TilesetFile and TileLayers).
func (t *TilemapDoc) HasTilesetFile() boolHasTilesetFile reports whether t names a YAML tileset file (TilesetFile), either in a layered grid (TileLayers) or in place of a sprite atlas on a single inline grid (Data).
func (t *TilemapDoc) IsExternal() boolIsExternal reports whether t references an external tilemap source file.
func (t *TilemapDoc) IsInline() boolIsInline reports whether t carries an inline tile grid, single or layered.
func (t *TilemapDoc) IsLayered() boolIsLayered reports whether t is a layered grid, one that holds tile layers (TileLayers) or names a YAML tileset (TilesetFile) without flat Data.
func (t *TilemapDoc) IsRef() boolIsRef reports whether t references a top-level tilemap by name.
func (t *TilemapDoc) TileLayer(name string) *TileLayerDocTileLayer returns the tile layer of a layered grid named name, or nil.
type TilemapResolver interface {
Tilemap(source string) (*TilemapDoc, error)
}TilemapResolver may optionally be implemented by an AssetResolver to load external tilemap sources into an inline TilemapDoc. Build uses it, when the resolver implements it, for every TilemapDoc.Source that names no Level, ahead of reading the source itself through a FileResolver. A source with a Level (an LDtk level) is always read through a FileResolver, since Tilemap has no way to receive the level.
type TonemapMode stringTonemapMode selects the HDR-to-LDR tone mapping operator (EnvironmentDoc.Tonemapping).
const (
// TonemapNone clamps exposed linear radiance to [0, 1] without highlight roll-off.
TonemapNone TonemapMode = "none"
// TonemapReinhard applies per-channel Reinhard compression.
TonemapReinhard TonemapMode = "reinhard"
// TonemapACES applies the fitted ACES filmic curve.
TonemapACES TonemapMode = "aces"
// TonemapNeutral applies the Khronos PBR Neutral tone mapper.
TonemapNeutral TonemapMode = "neutral"
// TonemapAgX applies the AgX filmic tone mapper.
TonemapAgX TonemapMode = "agx"
)