sceneformat

package
v0.4.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 63 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sceneformat is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

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

Index

Examples

Constants

View Source
const (
	// AnimatorComponentName is the built-in sprite animation state machine component type name in scene and prefab YAML files.
	AnimatorComponentName = "animator"

	// AnimatorEventStateChanged is the event emitted when an animator transitions to a new state.
	AnimatorEventStateChanged = "stateChanged"
	// AnimatorEventClipEvent is the event emitted when an animator's active clip crosses a named cue event.
	AnimatorEventClipEvent = "clipEvent"

	// AnimatorHandlerSetState is the handler that switches an animator directly to a named state.
	AnimatorHandlerSetState = "setState"
	// AnimatorHandlerTrigger is the handler that pulses a named trigger parameter on an animator.
	AnimatorHandlerTrigger = "trigger"
)
View Source
const (
	// PlatformComponentName drives a physics.CharacterBody with platformer.Controller.
	PlatformComponentName = "platform"
	// EightDirectionComponentName drives deterministic 4- or 8-direction top-down movement.
	EightDirectionComponentName = "eight_direction"
	// TileMovementComponentName steps an object whole grid cells at a time, blocked by solid tiles.
	TileMovementComponentName = "tile_movement"
	// CarComponentName drives arcade 2D vehicle steering, acceleration and drift.
	CarComponentName = "car"
	// DragDropComponentName allows dragging an object with a pointer along x, y, or both axes.
	DragDropComponentName = "drag_drop"
	// TurretComponentName tracks and fires at objects in scene groups within range.
	TurretComponentName = "turret"
	// LineOfSightComponentName checks range, sight cone and physics line of sight to objects.
	LineOfSightComponentName = "line_of_sight"
	// PathAgentComponentName drives an object along BuiltScene.NavMesh2D via pathfind.NavAgent.
	PathAgentComponentName = "path_agent"
)

Built-in 2D input-driven controller component type names in scene YAML files.

View Source
const (
	DependencyAtlas     = "atlas"
	DependencyImage     = "image"
	DependencyTilemap   = "tilemap"
	DependencyTileset   = "tileset"
	DependencyMaterial  = "material"
	DependencyParticles = "particles"
	DependencyScene     = "scene"
	DependencyModel     = "model"
	DependencySound     = "sound"
	DependencySkeleton  = "skeleton"
)

Dependency kind values reported in Dependency.Kind.

View Source
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.

View Source
const (
	// Light2DComponentName is the built-in 2D point, spotlight, textured, or directional light 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.

View Source
const (
	// Line2DComponentVersion is the schema version of the built-in "line2d" component.
	Line2DComponentVersion = 1
	// Polygon2DComponentVersion is the schema version of the built-in "polygon2d" component.
	Polygon2DComponentVersion = 1
)

Schema versions of the built-in 2D mesh sprite components (line2d and polygon2d).

View Source
const (
	// Line2DComponentName is the built-in textured/gradient polyline component rendered by sprite.Line.
	Line2DComponentName = "line2d"
	// Polygon2DComponentName is the built-in textured/colored polygon component rendered by sprite.Polygon.
	Polygon2DComponentName = "polygon2d"
)

Built-in 2D mesh sprite component type names in scene YAML files.

View Source
const (
	// BulletComponentName moves an object linearly with speed, acceleration, gravity, optional rotation and solid bouncing.
	BulletComponentName = "bullet"
	// SineComponentName oscillates an object's x, y, angle, scale or alpha periodically.
	SineComponentName = "sine"
	// RotateComponentName spins an object continuously at an angular speed and acceleration.
	RotateComponentName = "rotate"
	// OrbitComponentName revolves an object around a target object or its initial position.
	OrbitComponentName = "orbit"
	// MoveToComponentName drives an object toward a target coordinate with optional acceleration and solid stopping.
	MoveToComponentName = "move_to"
	// WrapComponentName wraps an object leaving one side of the scene or view onto the opposite side.
	WrapComponentName = "wrap"
	// BoundComponentName clamps an object inside the scene bounds by its edge or origin.
	BoundComponentName = "bound"
	// DestroyOutsideComponentName frees an object once it travels past the scene or view bounds plus a margin.
	DestroyOutsideComponentName = "destroy_outside"
	// FadeComponentName drives an opacity fade-in, wait and fade-out envelope, optionally freeing the object at the end.
	FadeComponentName = "fade"
	// FlashComponentName blinks an object's visibility on and off for a requested duration.
	FlashComponentName = "flash"
)

Built-in 2D motion behavior component type names in scene YAML files.

View Source
const (
	PartitionPlaneXY = "xy"
	PartitionPlaneXZ = "xz"
)

PartitionPlane selects the 2D coordinate plane used for spatial partitioning: "xy" (default, 2D scenes) or "xz" (3D scenes, matching world3d.ChunkStreamer).

View Source
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.

View Source
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
)
View Source
const (
	// GameTargetID is the reserved built-in connection target for game-wide actions:
	// vars.set, vars.add, sound.play, scene.change, and save.slot.
	GameTargetID = "game"
	// SceneHandlerSet is the built-in handler namespace available on every scene object:
	// scene.destroy, scene.spawn, scene.set, scene.show, scene.hide, and scene.emit.
	SceneHandlerSet = "scene"
)
View Source
const (
	// VCamComponentName is the built-in virtual camera component key in scene YAML files.
	VCamComponentName = "vcam"
	// VCamTriggerComponentName is the built-in camera trigger-zone component key in scene YAML files.
	VCamTriggerComponentName = "vcam_trigger"
)

Built-in virtual camera component keys in scene YAML files.

View Source
const BehaviorComponentVersion = 1

BehaviorComponentVersion is the schema version of the built-in 2D motion behavior components.

View Source
const ConflictVersion = 1

ConflictVersion is the schema version of the YAML conflict file written by the scene merge driver when a three-way merge encounters conflicts.

View Source
const ControllerComponentVersion = 1

ControllerComponentVersion is the schema version of the eight built-in input-driven controller components.

View Source
const ControllerSnapshotVersion = 1

ControllerSnapshotVersion is the format version written by BuiltScene.Snapshot and accepted by BuiltScene.Restore.

View Source
const CoverPointComponentName = "cover_point"

CoverPointComponentName is the canonical scene YAML component key for authored cover points.

View Source
const CurrentVersion = 4

CurrentVersion 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), 3D terrains (ObjectDoc.Terrain) and scene environment settings (SceneDoc.Environment).

View Source
const DefaultFogVolumeDensity float32 = 0.3

DefaultFogVolumeDensity is the default volumetric extinction density when FogVolumeDoc.Density is nil.

View Source
const DefaultMapEventAction = "action"

DefaultMapEventAction is the Input action name checked for "action" trigger map events when BuiltScene.EventAction is empty.

View Source
const DefaultPartitionManifestFile = "partition.manifest.yaml"

DefaultPartitionManifestFile is the manifest file name written by WritePartition and read by NewStreamer when StreamerConfig.ManifestPath is empty.

View Source
const Lights2DComponentVersion = 2

Lights2DComponentVersion is the current schema version of the built-in 2D lighting components (light2d and occluder2d). Version 1 components remain loadable for backward compatibility; version 2 adds directional lights, light textures, blend modes, shadow color/softness, normal-map height, and light/shadow masks.

View Source
const MapEventComponentName = "map_event"

MapEventComponentName is the canonical scene YAML component key for map events.

View Source
const MapEventComponentVersion = 1

MapEventComponentVersion is the schema version of the built-in "map_event" scene component.

View Source
const MaxEmitDepth = 64

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

View Source
const MaxObjectDepth = 64

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

View Source
const MaxPath2DPoints = 4096

MaxPath2DPoints caps the number of control points accepted in a single FieldBezierPoints field so untrusted scene files cannot force unbounded arc-length table allocations.

View Source
const MaxResolvedObjects = 1 << 17

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

View Source
const MaxSceneNesting = 64

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

View Source
const MaxTileLayers = 64

MaxTileLayers is the most tile layers one layered grid may hold (TilemapDoc.TileLayers).

View Source
const MinVersion = 1

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

View Source
const NavLinkComponentName = "nav_link"

NavLinkComponentName is the canonical scene YAML component key for authored off-mesh navigation links (jumps, ledge drops, ladders, doors, and teleporters).

View Source
const NavRegion2DComponentName = "navregion2d"

NavRegion2DComponentName is the built-in 2D navigation region polygon component key in scene YAML files.

View Source
const NavRegion2DComponentVersion = 1

NavRegion2DComponentVersion is the schema version of the built-in 2D navigation region component (navregion2d).

View Source
const OnScreenComponentName = "on_screen"

OnScreenComponentName is the built-in on-screen notifier component name in scene YAML files.

View Source
const OnScreenComponentVersion = 1

OnScreenComponentVersion is the schema version of the built-in "on_screen" component.

View Source
const PartitionManifestVersion = 1

PartitionManifestVersion is the YAML schema version of PartitionManifest.

View Source
const Path2DComponentName = "path2d"

Path2DComponentName is the built-in 2D cubic Bézier path component key in scene YAML files.

View Source
const Path2DComponentVersion = 1

Path2DComponentVersion is the schema version of the built-in "path2d" and "path_follow2d" components.

View Source
const PathFollow2DComponentName = "path_follow2d"

PathFollow2DComponentName is the built-in 2D path follower component key in scene YAML files.

View Source
const PhysicsComponentVersion = 1

PhysicsComponentVersion is the schema version of the built-in 2D and 3D physics components.

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

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

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

SchemaCommentV2 is the first line Encode writes for a version 2 document, pointing a YAML language server at SchemaURLV2.

View Source
const SchemaCommentV3 = "# yaml-language-server: $schema=" + SchemaURLV3

SchemaCommentV3 is the first line Encode writes for a version 3 document, pointing a YAML language server at SchemaURLV3.

View Source
const SchemaCommentV4 = "# yaml-language-server: $schema=" + SchemaURLV4

SchemaCommentV4 is the first line Encode writes for a version 4 document, pointing a YAML language server at SchemaURLV4.

View Source
const SchemaURL = "https://nsgo.games/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.

View Source
const SchemaURLV2 = "https://nsgo.games/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.

View Source
const SchemaURLV3 = "https://nsgo.games/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.

View Source
const SchemaURLV4 = "https://nsgo.games/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.

View Source
const SkeletalComponentName = "skeletal"

SkeletalComponentName is the built-in 2D skeletal rig component name in scene YAML files.

View Source
const SkeletalComponentVersion = 1

SkeletalComponentVersion is the schema version of the built-in "skeletal" component.

View Source
const SmartObjectComponentName = "smart_object"

SmartObjectComponentName is the canonical scene YAML component key for smart objects.

View Source
const SmartObjectComponentVersion = 1

SmartObjectComponentVersion is the schema version of the built-in "smart_object" scene component.

View Source
const SoundComponentName = "sound"

SoundComponentName is the canonical scene YAML component key for placed 2D and 3D sound emitters.

View Source
const StreamStateVersion = 1

StreamStateVersion is the schema version of StreamStateSnapshot.

View Source
const TimerComponentName = "timer"

TimerComponentName is the built-in timer component type name in scene and prefab YAML files.

View Source
const VCamComponentVersion = 1

VCamComponentVersion is the schema version of the built-in "vcam" and "vcam_trigger" components.

Variables

This section is empty.

Functions

func BehaviorComponentNames

func BehaviorComponentNames() []string

BehaviorComponentNames returns the names of all ten built-in 2D motion behavior component types in sorted order.

func Bool

func Bool(v bool) *bool

Bool returns a pointer to v for optional YAML boolean fields such as LayerDoc.Visible.

func BuildLights2D

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

func BuildNavMesh2D(scene *BuiltScene) (*navbake.Mesh, *pathfind.NavMesh, error)

BuildNavMesh2D constructs a baked *navbake.Mesh and runtime *pathfind.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 *pathfind.NavMesh without error.

func CapturePersistence

func CapturePersistence(doc *SceneDoc, w *entities.World, spawned map[string]entities.Entity, p *save.Persistence, scenePath string)

CapturePersistence records into p the current destroyed and moved states of doc's objects from w and spawned (as returned by SpawnEntities / SpawnEntitiesWith) before leaving scenePath. Pass the scene as parsed from its file, not a copy returned by ApplyPersistence, since positions are compared against doc's values.

Any object in doc whose entity is missing from spawned or no longer alive in w is marked destroyed; any live object whose Transform2D position or rotation differs from its SceneDoc values has its new position or rotation recorded, and one whose position or rotation matches doc again has that override cleared. Existing component overrides, switches and vars on live objects are preserved.

func CheckObjectCamera3D

func CheckObjectCamera3D(o *ObjectDoc) error

CheckObjectCamera3D checks o.Camera as Validate checks it in a version 4 scene.

func CheckObjectFogVolume

func CheckObjectFogVolume(o *ObjectDoc) error

CheckObjectFogVolume checks o.FogVolume as Validate checks it in a version 4 scene.

func CheckObjectLight

func CheckObjectLight(o *ObjectDoc) error

CheckObjectLight checks o.Light as Validate checks it in a version 4 scene.

func CheckObjectLightProbeGrid

func CheckObjectLightProbeGrid(o *ObjectDoc) error

CheckObjectLightProbeGrid checks o.LightProbeGrid as Validate checks it in a version 4 scene.

func CheckObjectModel

func CheckObjectModel(o *ObjectDoc) error

CheckObjectModel 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 CSG with Mesh, Model, GridMap or Terrain, 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

func CheckObjectReflectionProbe(o *ObjectDoc) error

CheckObjectReflectionProbe checks o.ReflectionProbe as Validate checks it in a version 4 scene.

func CheckObjectTree

func CheckObjectTree(o *ObjectDoc) error

CheckObjectTree 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 CheckParameterValue

func CheckParameterValue(p SceneParameter, value any) error

CheckParameterValue checks that value matches p's declared type and any asset-kind constraints of p's bindings.

func ComponentTypeSchema

func ComponentTypeSchema(t ComponentType) *jsonschema.Schema

ComponentTypeSchema returns a draft-07 JSON Schema for a single component mapping of type t. Every FieldKind is mapped to its JSON Schema representation, along with each field's description, default (when set), numeric bounds and string enum. Unknown field keys are refused.

func Encode

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

func EncodeConflict(doc *ConflictDoc) ([]byte, error)

EncodeConflict validates doc and serializes it as deterministic 2-space YAML.

func EncodePartitionManifest

func EncodePartitionManifest(m *PartitionManifest) ([]byte, error)

EncodePartitionManifest validates and encodes m as deterministic 2-space YAML.

func EncodeStreamStateJSON

func EncodeStreamStateJSON(snap StreamStateSnapshot) ([]byte, error)

EncodeStreamStateJSON validates and encodes snap as deterministic indented JSON.

func EncodeStreamStateYAML

func EncodeStreamStateYAML(snap StreamStateSnapshot) ([]byte, error)

EncodeStreamStateYAML validates and encodes snap as deterministic 2-space YAML.

func EvaluateWhen

func EvaluateWhen(expression string, ctx RuleContext) (bool, error)

EvaluateWhen evaluates a connection's When expression (pkg/expr syntax) against ctx. An empty expression returns true. Names are read from ctx.Numbers, ctx.Strings, ctx.Bools, and ctx.Vars, and custom functions from ctx.Funcs. Legacy unquoted string comparisons such as `mode == combat` remain supported when `mode` is a string variable.

func ExtractBuiltCoverPoints

func ExtractBuiltCoverPoints(scene *BuiltScene) ([]ai.CoverPoint, error)

ExtractBuiltCoverPoints extracts all authored "cover_point" components from a resolved BuiltScene.

func ExtractBuiltNavLinks2D

func ExtractBuiltNavLinks2D(scene *BuiltScene) ([]pathfind.NavOffMeshLink, error)

ExtractBuiltNavLinks2D extracts all authored "nav_link" components from a resolved BuiltScene as 2D links.

func ExtractBuiltNavLinks3D

func ExtractBuiltNavLinks3D(scene *BuiltScene) ([]pathfind3d.NavOffMeshLink, error)

ExtractBuiltNavLinks3D extracts all authored "nav_link" components from a resolved BuiltScene as 3D links.

func ExtractBuiltSmartObjects

func ExtractBuiltSmartObjects(scene *BuiltScene) ([]ai.SmartObject, error)

ExtractBuiltSmartObjects extracts all authored "smart_object" components from a resolved BuiltScene.

func ExtractCoverPoints

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 ExtractLine2D

func ExtractLine2D(o *ObjectDoc, resolver ImageResolver) (*sprite.Line, bool, error)

ExtractLine2D resolves a built-in "line2d" component from o into a ready-to-draw *sprite.Line. It returns (nil, false, nil) when o has no "line2d" component.

func ExtractNavLinks2D

func ExtractNavLinks2D(doc *SceneDoc) ([]pathfind.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 pathfind.NavOffMeshLink values ready for pathfind.NavMesh.AddOffMeshLink.

func ExtractNavLinks3D

func ExtractNavLinks3D(doc *SceneDoc) ([]pathfind3d.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 pathfind3d.NavOffMeshLink values ready for pathfind3d.NavMesh.AddOffMeshLink or navbake3d.

func ExtractPath2D

func ExtractPath2D(o *ObjectDoc) (*tween.BezierPath, bool, error)

ExtractPath2D resolves an object's built-in "path2d" component into a local-space *tween.BezierPath. Reports ok == false when o has no "path2d" component.

func ExtractPath2DWorld

func ExtractPath2DWorld(o *ObjectDoc, world math2d.Affine) (*tween.BezierPath, bool, error)

ExtractPath2DWorld resolves an object's built-in "path2d" component into a world-space *tween.BezierPath transformed by world (composing anchor positions and relative in/out handle vectors). Reports ok == false when o has no "path2d" component.

func ExtractPolygon2D

func ExtractPolygon2D(o *ObjectDoc, resolver ImageResolver) (*sprite.Polygon, bool, error)

ExtractPolygon2D resolves a built-in "polygon2d" component from o into a ready-to-draw *sprite.Polygon. It returns (nil, false, nil) when o has no "polygon2d" component.

func ExtractSmartObjects

func ExtractSmartObjects(doc *SceneDoc) ([]ai.SmartObject, error)

ExtractSmartObjects extracts all authored "smart_object" components from doc in deterministic document order (including nested child objects, composing parent 2D transforms).

func ExtractSoundZones2D

func ExtractSoundZones2D(doc *SceneDoc) []sound.Zone

ExtractSoundZones2D extracts all ObjectDoc.SoundZone regions from doc in document order as 2D sound.Zone values.

func ExtractSoundZones3D

func ExtractSoundZones3D(doc *SceneDoc) []sound.Zone

ExtractSoundZones3D extracts all ObjectDoc.SoundZone regions from doc in document order as 3D sound.Zone values.

func Float32

func Float32(v float32) *float32

Float32 returns a pointer to v for optional YAML float fields such as ScaleX, ScaleY, Alpha and Zoom.

func Float64

func Float64(v float64) *float64

Float64 returns a pointer to v for a Field's optional Min and Max.

func FormatTileRow

func FormatTileRow(cells []uint32) string

FormatTileRow 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 FormatTileRowCells

func FormatTileRowCells(cells []tilemap.TileCell) string

FormatTileRowCells writes cells as one canonical row of a tile layer: single spaces between cells, "." for empty, flip letters in the order h, v, d, and an optional a<alt> suffix when Alt > 0.

func InputBehaviorComponentNames

func InputBehaviorComponentNames() []string

InputBehaviorComponentNames lists the input-driven controller components InputBehaviorComponent knows, in registration order.

func Int

func Int(v int) *int

Int returns a pointer to v for optional YAML integer fields such as ObjectOverride.Z and LayerOverride.Order.

func IsBehaviorComponent

func IsBehaviorComponent(name string) bool

IsBehaviorComponent reports whether name is one of the ten built-in 2D motion behavior components.

func IsGridMapPath

func IsGridMapPath(p string) bool

IsGridMapPath 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

func IsHDRPath(p string) bool

IsHDRPath reports whether p names a Radiance HDR image by its extension, .hdr or .pic in any case, as SkyDoc.HDR requires.

func IsInputBehaviorComponent

func IsInputBehaviorComponent(name string) bool

IsInputBehaviorComponent reports whether name is one of the eight built-in input-driven controller components.

func IsLightProbeGridPath

func IsLightProbeGridPath(p string) bool

IsLightProbeGridPath reports whether p names a YAML light probe grid file by its extension (.yaml or .yml in any case).

func IsLights2DComponent

func IsLights2DComponent(name string) bool

IsLights2DComponent reports whether name is one of the built-in 2D lighting component types.

func IsLine2DComponent

func IsLine2DComponent(name string) bool

IsLine2DComponent reports whether name is the built-in "line2d" component type.

func IsMapEventComponent

func IsMapEventComponent(name string) bool

IsMapEventComponent reports whether name is the built-in "map_event" component type.

func IsMesh2DComponent

func IsMesh2DComponent(name string) bool

IsMesh2DComponent reports whether name is either "line2d" or "polygon2d".

func IsModelPath

func IsModelPath(p string) bool

IsModelPath reports whether p names a glTF 2.0 file by its extension, .gltf or .glb in any case, as ObjectDoc.Model requires.

func IsNavRegion2DComponent

func IsNavRegion2DComponent(name string) bool

IsNavRegion2DComponent reports whether name is the built-in 2D navigation region component type.

func IsPath2DComponent

func IsPath2DComponent(name string) bool

IsPath2DComponent reports whether name is one of the built-in 2D path component types ("path2d" or "path_follow2d").

func IsPhysicsComponent

func IsPhysicsComponent(name string) bool

IsPhysicsComponent reports whether name is one of the built-in 2D or 3D physics component types.

func IsPolygon2DComponent

func IsPolygon2DComponent(name string) bool

IsPolygon2DComponent reports whether name is the built-in "polygon2d" component type.

func IsSkeletalComponent

func IsSkeletalComponent(name string) bool

IsSkeletalComponent reports whether name is the built-in "skeletal" component type.

func IsSmartObjectComponent

func IsSmartObjectComponent(name string) bool

IsSmartObjectComponent reports whether name is the built-in "smart_object" component type.

func IsSoundComponent

func IsSoundComponent(name string) bool

IsSoundComponent reports whether name is the built-in "sound" component type.

func IsTerrainPath

func IsTerrainPath(p string) bool

IsTerrainPath reports whether p names a terrain file.

func IsVCamComponent

func IsVCamComponent(name string) bool

IsVCamComponent reports whether name is one of the built-in virtual camera component types ("vcam" or "vcam_trigger").

func LightmapSceneHash

func LightmapSceneHash(doc *SceneDoc) string

LightmapSceneHash returns a deterministic SHA-256 digest ("sha256:<64 hex>") of every field in doc that affects baked lightmaps and baked light probe grids: environment sky/ambient/IBL, static lightmapped geometry (and parent transforms/visibility), 3D lights, and light probe grids (excluding LightProbeGridDoc.Data so writing baked outputs does not self-invalidate the hash).

Pass a resolved scene (from Resolve) when the scene inherits or instances other scenes so changes in inherited or instanced geometry and lights are reflected in the hash.

func Lights2DComponentNames

func Lights2DComponentNames() []string

Lights2DComponentNames returns the names of all built-in 2D lighting component types in canonical order.

func LocateError

func LocateError(err error, file string, data []byte) error

LocateError turns a *FieldError (such as one returned by Validate or Resolve) into a *loaderr.Error pointing at file and the 1-based line and column in data. Errors without a *FieldError are returned with file attached via loaderr.WithFile.

func Mesh2DComponentNames

func Mesh2DComponentNames() []string

Mesh2DComponentNames returns the names of the built-in 2D mesh sprite components in canonical order.

func MeshPrimitives

func MeshPrimitives() []string

MeshPrimitives returns the built-in primitive names ObjectDoc.Mesh accepts, sorted.

func ObjectLocalTransform3D

func ObjectLocalTransform3D(o *ObjectDoc) math3d.Transform

ObjectLocalTransform3D 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

func ParseTileRow(row string) ([]uint32, error)

ParseTileRow parses one row of a tile layer (TileLayerDoc.Rows) into its cell GIDs, as TileLayerDoc.Cell returns each. Cells are separated by spaces or tabs, flip letters (h, v, d) may come in any order each at most once, and an optional a<alt> alternative suffix is accepted and validated.

func ParseTileRowCells

func ParseTileRowCells(row string) ([]tilemap.TileCell, error)

ParseTileRowCells parses one row of a tile layer (TileLayerDoc.Rows) into tilemap.TileCell values carrying both raw GID (with flip flags) and optional positive alternative ID. Cells are separated by spaces or tabs. A cell is "." when empty, or a local tile ID followed by any of h, v, d (each at most once) and an optional a<alt> positive integer suffix (in any order).

func PhysicsComponentNames

func PhysicsComponentNames() []string

PhysicsComponentNames returns the names of all built-in physics component types in canonical order.

func PopulateSmartObjects

func PopulateSmartObjects(scene *BuiltScene, reg *ai.SmartObjects) error

PopulateSmartObjects extracts all "smart_object" components from scene and registers them on reg, disabling any whose authored enabled flag is false.

func RegisterAnimatorComponent

func RegisterAnimatorComponent(reg *ComponentRegistry) error

RegisterAnimatorComponent registers the built-in "animator" component type on reg.

func RegisterBehaviorComponents

func RegisterBehaviorComponents(reg *ComponentRegistry) error

RegisterBehaviorComponents registers all ten built-in 2D motion behavior component types on reg.

func RegisterCoverPoint

func RegisterCoverPoint(reg *ComponentRegistry) error

RegisterCoverPoint registers the built-in "cover_point" component type on reg.

func RegisterInputBehaviorComponents

func RegisterInputBehaviorComponents(reg *ComponentRegistry) error

RegisterInputBehaviorComponents registers the schema of every input-driven controller component on reg. It is separate from RegisterBehaviorComponents, which registers the motion behaviors.

func RegisterLights2DComponents

func RegisterLights2DComponents(reg *ComponentRegistry) error

RegisterLights2DComponents registers the built-in light2d and occluder2d component types on reg.

func RegisterLine2DComponent

func RegisterLine2DComponent(reg *ComponentRegistry) error

RegisterLine2DComponent registers the built-in "line2d" component type on reg.

func RegisterMapEventComponent

func RegisterMapEventComponent(reg *ComponentRegistry) error

RegisterMapEventComponent registers the built-in "map_event" component type on reg.

func RegisterMesh2DComponents

func RegisterMesh2DComponents(reg *ComponentRegistry) error

RegisterMesh2DComponents registers both "line2d" and "polygon2d" component types on reg.

func RegisterNavLink(reg *ComponentRegistry) error

RegisterNavLink registers the built-in "nav_link" component type on reg.

func RegisterNavRegion2DComponent

func RegisterNavRegion2DComponent(reg *ComponentRegistry) error

RegisterNavRegion2DComponent registers the built-in "navregion2d" component type on reg.

func RegisterOnScreen

func RegisterOnScreen(reg *ComponentRegistry) error

RegisterOnScreen registers the built-in "on_screen" component type on reg.

func RegisterPath2DComponents

func RegisterPath2DComponents(reg *ComponentRegistry) error

RegisterPath2DComponents registers both built-in 2D path component types ("path2d" and "path_follow2d") on reg.

func RegisterPhysicsComponents

func RegisterPhysicsComponents(reg *ComponentRegistry) error

RegisterPhysicsComponents registers all six built-in 2D and 3D physics component types on reg.

func RegisterPolygon2DComponent

func RegisterPolygon2DComponent(reg *ComponentRegistry) error

RegisterPolygon2DComponent registers the built-in "polygon2d" component type on reg.

func RegisterSkeletalComponent

func RegisterSkeletalComponent(reg *ComponentRegistry) error

RegisterSkeletalComponent registers the built-in "skeletal" component type on reg.

func RegisterSmartObjectComponent

func RegisterSmartObjectComponent(reg *ComponentRegistry) error

RegisterSmartObjectComponent registers the built-in "smart_object" component type on reg.

func RegisterSoundComponent

func RegisterSoundComponent(reg *ComponentRegistry) error

RegisterSoundComponent registers the built-in "sound" component type on reg.

func RegisterTimerComponent

func RegisterTimerComponent(reg *ComponentRegistry) error

RegisterTimerComponent registers the built-in "timer" component type on reg.

func RegisterVCamComponents

func RegisterVCamComponents(reg *ComponentRegistry) error

RegisterVCamComponents registers "vcam" and "vcam_trigger" on reg.

func SaveVarsSlot

func SaveVarsSlot(store *save.Store, vars *flow.Vars) func(name string) error

SaveVarsSlot returns a GameActions.SaveSlot callback that writes vars.Snapshot() to slot name in store via save.Store.Save.

func SceneManagerChanger

func SceneManagerChanger(mgr *scene.Manager, load func(path string) (*scene.Controller, error), defaultDuration time.Duration) func(path, transition string) error

SceneManagerChanger returns a GameActions.ChangeScene callback that loads the target scene's *scene.Controller via load(path) and switches mgr to it using scene.Manager.Switch (passing the *scene.Transition from SceneTransition, or nil for an immediate switch).

func SceneSchema

func SceneSchema(reg *ComponentRegistry) (*jsonschema.Schema, error)

SceneSchema returns a draft-07 JSON Schema for scene YAML files (versions MinVersion through CurrentVersion) whose objects' components are checked against reg. When reg is non-nil, ObjectDoc.components and ObjectOverride.components reference reg.JSONSchema(), refusing unregistered component names and validating every registered field. When reg is nil, built-in scene components are typed while any custom component mapping remains allowed.

func SceneTransition

func SceneTransition(name string, duration time.Duration) (*scene.Transition, error)

SceneTransition parses a named transition for the built-in game target's scene.change handler ("", "none", "fade", "crossfade", "fade_black", "fade_white", "wipe_left", "wipe_right", "wipe_up", "wipe_down") into a *scene.Transition lasting duration (defaulting to 300ms when <= 0). Empty or "none" returns (nil, nil) for an immediate switch.

func SchemaCommentFor

func SchemaCommentFor(version int) string

SchemaCommentFor 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

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. It is equivalent to SpawnEntitiesWith(doc, w, SpawnOptions{}).

func SpawnEntitiesWith

func SpawnEntitiesWith(doc *SceneDoc, w *entities.World, opts SpawnOptions) (map[string]entities.Entity, error)

SpawnEntitiesWith spawns doc's objects into w as SpawnEntities does, and when opts.Components is non-nil validates and resolves every object's components against opts.Components before the first entity is spawned, then runs each registered ComponentType.Spawn factory on its entity. All scene entities are created and linked into Hierarchy2D before any ComponentType.Spawn runs, so FieldObject references resolve to their target's entities.Entity regardless of object declaration order (including forward references). Objects' ComponentType.Spawn factories then run in depth-first document order (each parent before its children), and within each object its components run in ascending component-name order.

If any ComponentType.Spawn returns an error, SpawnEntitiesWith destroys every entity it created (leaving pre-existing entities in w untouched) and returns the error naming the layer, object ID and component.

Example

SpawnEntitiesWith validates a scene's components against a registry, resolves defaults, and runs each registered ComponentType.Spawn factory to attach typed ECS components to the spawned entities.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/entities"
	"github.com/nsgo-dev/game/pkg/sceneformat"
)

func main() {
	type Health struct {
		HP, Max int
	}
	reg := sceneformat.NewComponentRegistry()
	reg.MustRegister(sceneformat.ComponentType{
		Name: "health",
		Fields: []sceneformat.Field{
			{Name: "hp", Kind: sceneformat.FieldInt, Default: 10},
			{Name: "max", Kind: sceneformat.FieldInt, Default: 10},
		},
		Spawn: func(w *entities.World, e entities.Entity, fields map[string]any) error {
			entities.Set(w, e, Health{HP: fields["hp"].(int), Max: fields["max"].(int)})
			return nil
		},
	})
	doc, err := sceneformat.ParseWith([]byte(`version: 1
layers:
  - name: actors
    objects:
      - id: hero
        components:
          health:
            hp: 7
`), sceneformat.ParseOptions{Components: reg})
	if err != nil {
		fmt.Println(err)
		return
	}
	world := entities.NewWorld()
	spawned, err := sceneformat.SpawnEntitiesWith(doc, world, sceneformat.SpawnOptions{Components: reg})
	if err != nil {
		fmt.Println(err)
		return
	}
	h, _ := entities.Get[Health](world, spawned["hero"])
	fmt.Println(h.HP, h.Max)
}
Output:
7 10

func String

func String(v string) *string

String returns a pointer to v for optional YAML string fields such as ObjectOverride.Name.

func StringSlice

func StringSlice(v ...string) *[]string

StringSlice returns a pointer to a cloned string slice for optional override fields such as ObjectOverride.VisibilityLayers and LayerOverride.VisibilityLayers. Calling StringSlice() with no arguments returns a non-nil pointer to an empty slice, which clears an inherited layer list when applied.

func Strings

func Strings(v ...string) *[]string

Strings returns a pointer to a copy of v for optional YAML string-slice fields such as ObjectOverride.Groups. Calling Strings() with no arguments returns a pointer to a non-nil empty slice so an override explicitly clears inherited groups.

func Uint32

func Uint32(v uint32) *uint32

Uint32 returns a pointer to v for optional YAML uint32 bitmask fields such as LayerDoc.LightMask and ObjectDoc.LightMask.

func ValidGroupName

func ValidGroupName(name string) bool

ValidGroupName reports whether name is a valid scene object group name: non-empty, starting with an ASCII letter (A-Z, a-z) or underscore (_), followed by ASCII letters, digits (0-9), underscores (_), or hyphens (-).

func Validate

func Validate(doc *SceneDoc) error

Validate 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

func ValidateComponents(doc *SceneDoc, reg *ComponentRegistry) error

ValidateComponents checks the components of every object in doc, children included, against reg: unregistered component types, unknown fields, wrong kinds, out-of-range values, and (when doc does not refer to other scene files) FieldObject references to missing objects 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

func ValidateConflict(doc *ConflictDoc) error

ValidateConflict checks that doc conforms to ConflictVersion's schema.

func ValidateConnections

func ValidateConnections(doc *SceneDoc, reg *ComponentRegistry) error

ValidateConnections 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", or as a custom "scene.<name>" event), each handler likewise on its To object (or a built-in "scene.*" handler on any object, or a built-in "game" target handler when To is "game"), 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 ValidateConnectionsWith

func ValidateConnectionsWith(doc *SceneDoc, reg *ComponentRegistry, opts ConnectOptions) error

ValidateConnectionsWith is ValidateConnections with optional variable declarations and custom functions (opts.Vars / opts.VarsDoc and opts.Funcs) to type-check When expressions, expression-valued Args, and built-in game vars.set/vars.add handlers.

func ValidateParameterValue

func ValidateParameterValue(t ParameterType, value any) error

ValidateParameterValue checks that value has the type t declares.

func ValidatePhysicsLayers

func ValidatePhysicsLayers(doc *SceneDoc, layers *PhysicsLayerTable) error

ValidatePhysicsLayers 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 ValidateVisibilityLayers

func ValidateVisibilityLayers(doc *SceneDoc, layers *VisibilityLayerTable) error

ValidateVisibilityLayers checks every named visibility layer in doc (layers, layerOverrides, objects, and overrides) against layers. Unknown or misspelled layer names return a *loaderr.Error naming the field path. Prefer ParseWith with ParseOptions.VisibilityLayers when loading files so errors also carry exact 1-based line and column numbers.

func WalkObjects

func WalkObjects(objs []ObjectDoc, fn func(o, parent *ObjectDoc) bool) bool

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

func WritePartition

func WritePartition(res *PartitionResult, dir string) ([]string, error)

WritePartition writes res's manifest, always-loaded scene, and all per-cell YAML fragments deterministically under dir, removing any stale generated cell files left over from earlier partition runs. It refuses a dir that holds a cells directory but no partition manifest, since that directory was not written by WritePartition. It returns the sorted list of written file paths relative to dir.

Types

type ActionInput

type ActionInput interface {
	Pressed(name string) bool
	JustPressed(name string) bool
	JustReleased(name string) bool
	Axis(name string) float64
}

ActionInput supplies named input actions and axes read by built-in controller components during BuiltScene.Step. *input.Actions, *replay.Player, *replay.Recorder, and any replay.ActionSource satisfy ActionInput.

type AnimatorClipEvent

type AnimatorClipEvent struct {
	// ObjectID is the ID of the object whose active clip crossed the cue.
	ObjectID string
	// State is the name of the active state whose clip emitted the cue.
	State string
	// Name is the cue event name declared in the clip.
	Name string
}

AnimatorClipEvent is the payload emitted with an object's "animator.clipEvent" event.

type AnimatorConfig

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

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 AnimatorController

type AnimatorController interface {
	SetState(name string) bool
	Trigger(name string)
}

AnimatorController is the runtime state machine interface driven by the built-in "animator" component's setState and trigger handlers. *animclip.StateMachine implements it.

type AnimatorProvider

type AnimatorProvider interface {
	Animator(objectID string) AnimatorController
}

AnimatorProvider may be implemented by Call.Context (as *BuiltScene does) to supply the AnimatorController for an object ID when none was bound directly on Signals.

type AnimatorStateChangedEvent

type AnimatorStateChangedEvent struct {
	// ObjectID is the ID of the object whose animator transitioned.
	ObjectID string
	// From is the state left.
	From string
	// To is the state entered.
	To string
}

AnimatorStateChangedEvent is the payload emitted with an object's "animator.stateChanged" event.

type AssetResolver

type AssetResolver interface {
	Atlas(name string) (*sprite.Atlas, error)
}

AssetResolver resolves sprite atlases named in a SceneDoc when building a BuiltScene.

type AtlasMap

type AtlasMap map[string]*sprite.Atlas

AtlasMap is an AssetResolver backed by a map of atlas names to atlases.

func (AtlasMap) Atlas

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 AutoExposureDoc

type AutoExposureDoc struct {
	// Enabled turns automatic exposure on or off; nil defaults to true when AutoExposure is present.
	Enabled *bool `yaml:"enabled,omitempty"`
	// MinEV is the lowest exposure value the adaptation reaches; must be finite and at most MaxEV. When MinEV and MaxEV are both 0 (or omitted), the range defaults to [-4, 4].
	MinEV float32 `yaml:"minEV,omitempty"`
	// MaxEV is the highest exposure value the adaptation reaches; must be finite and at least MinEV. When MinEV and MaxEV are both 0 (or omitted), the range defaults to [-4, 4].
	MaxEV float32 `yaml:"maxEV,omitempty"`
	// Speed is how fast exposure adapts to a change in brightness; must be finite and non-negative. 0 defaults to 2.
	Speed float32 `yaml:"speed,omitempty" schema:"minimum=0"`
	// Scale multiplies the adapted exposure target; must be finite and non-negative. 0 defaults to 1.
	Scale float32 `yaml:"scale,omitempty" schema:"minimum=0"`
}

AutoExposureDoc configures adapted exposure limits and response speed (EnvironmentDoc.AutoExposure).

func (*AutoExposureDoc) Clone

func (a *AutoExposureDoc) Clone() *AutoExposureDoc

Clone returns a deep copy of a, or nil when a is nil.

func (*AutoExposureDoc) EffectiveEVRange

func (a *AutoExposureDoc) EffectiveEVRange() (minEV, maxEV float32)

EffectiveEVRange returns a.MinEV and a.MaxEV, defaulting to [-4, 4] when a is nil or both are zero, since a [0, 0] range would pin exposure at 0 EV and never adapt.

func (*AutoExposureDoc) EffectiveEnabled

func (a *AutoExposureDoc) EffectiveEnabled() bool

EffectiveEnabled reports whether auto exposure is active (true when a is non-nil and Enabled is nil or true).

func (*AutoExposureDoc) EffectiveScale

func (a *AutoExposureDoc) EffectiveScale() float32

EffectiveScale returns a.Scale, defaulting to 1 when zero or nil.

func (*AutoExposureDoc) EffectiveSpeed

func (a *AutoExposureDoc) EffectiveSpeed() float32

EffectiveSpeed returns a.Speed, defaulting to 2 when zero or nil.

type BehaviorConfig

type BehaviorConfig struct {
	Version      int      `yaml:"version"`
	Kind         string   `yaml:"kind"`
	Axis         string   `yaml:"axis,omitempty"`
	MaxSpeed     float32  `yaml:"maxSpeed,omitempty"`
	Acceleration float32  `yaml:"acceleration,omitempty"`
	Deceleration float32  `yaml:"deceleration,omitempty"`
	Directions   int      `yaml:"directions,omitempty"`
	TileSize     float32  `yaml:"tileSize,omitempty"`
	Range        float32  `yaml:"range,omitempty"`
	RotateSpeed  float32  `yaml:"rotateSpeed,omitempty"`
	FireRate     float32  `yaml:"fireRate,omitempty"`
	Targets      []string `yaml:"targets,omitempty"`
}

BehaviorConfig is the shared, versioned configuration for input-driven scene behaviors (#1752).

func ParseBehaviorConfig

func ParseBehaviorConfig(data []byte) (BehaviorConfig, error)

ParseBehaviorConfig decodes one behavior config from YAML, refusing unknown fields and trailing documents, and validates it.

func (BehaviorConfig) Validate

func (c BehaviorConfig) Validate() error

Validate checks a behavior config independently of a scene registry.

type BehaviorSceneProvider

type BehaviorSceneProvider interface {
	BehaviorScene() *BuiltScene
}

BehaviorSceneProvider may be implemented by Call.Context to supply the *BuiltScene driven by motion behavior connection handlers when Call.Context is not a *BuiltScene directly. *BuiltScene implements BehaviorSceneProvider.

type BoundsDoc

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

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
	// Tint is the parsed layer tint color multiplying every item in this layer; opaque white when unset.
	Tint core.Color
	// Opacity multiplies the opacity of every item in this layer, in [0, 1]; defaults to 1.
	Opacity float32
	// ParallaxX and ParallaxY are the layer's horizontal and vertical parallax scroll factors, defaulting to 1.
	ParallaxX float32
	ParallaxY float32
	// OffsetX and OffsetY are the layer's current scroll offset in layer points, advanced by Step when AutoscrollX/Y are non-zero.
	OffsetX float32
	OffsetY float32
	// AutoscrollX and AutoscrollY are the layer's continuous scroll speeds in layer points per second.
	AutoscrollX float32
	AutoscrollY float32
	// Scale is the layer's uniform scale factor, defaulting to 1.
	Scale float32
	// Rotation is the layer's clockwise rotation in radians.
	Rotation float32
	// VisibilityLayers is the 32-bit visibility bitmask resolved from LayerDoc.VisibilityLayers; 0 matches every cull mask.
	VisibilityLayers uint32
	// LightMask is the 32-bit 2D light mask bitmask resolved from LayerDoc.LightMask; defaults to 1 (bit 0) and 0 marks an unlit layer that keeps its place in the draw order but is never lit.
	LightMask uint32
	// 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
	// Effects are the layer's built objects that carry a live particle effect player (ObjectDoc.Particles.Effect), in document order.
	Effects []*BuiltObject
	// Skeletons are the layer's built objects that carry a live 2D skeletal rig (BuiltObject.Skeleton), in Z order.
	Skeletons []*BuiltObject
	// Lines are the layer's built objects that carry a live 2D polyline mesh (BuiltObject.Line), in Z order.
	Lines []*BuiltObject
	// Polygons are the layer's built objects that carry a live 2D polygon mesh (BuiltObject.Polygon), in Z order.
	Polygons []*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 (*BuiltLayer) Draw

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, applying the layer's Tint and Opacity. When view is nil, every tile of Map draws without culling.

func (*BuiltLayer) DrawObjects

func (l *BuiltLayer) DrawObjects(d *core.Drawing)

DrawObjects draws the layer's sprite batches, particle emitters, particle effects, skeletal rigs, polygons, and polylines into d in exact Z order.

func (*BuiltLayer) RepeatTileRanges

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.

func (*BuiltLayer) Step

func (l *BuiltLayer) Step(dt time.Duration)

Step advances the built layer's OffsetX and OffsetY by AutoscrollX and AutoscrollY over dt. When RepeatX (or RepeatY) is enabled with a positive finite RepeatWidth (or RepeatHeight), the scrolled offset wraps cleanly into [0, period). Non-positive dt and non-finite speeds or offsets are ignored.

type BuiltObject

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
	// Line is the live 2D polyline mesh built from the object's "line2d" component, or nil when none is configured.
	Line *sprite.Line
	// Polygon is the live 2D polygon mesh built from the object's "polygon2d" component, or nil when none is configured.
	Polygon *sprite.Polygon
	// Material is the material resolved from Doc.Material, or nil when the object names none. When Doc.LocalMaterial is false it is the resolver's shared value, so an edit reloaded into it reaches every scene that uses it; when Doc.LocalMaterial is true it is an independent clone (resource.Clone) whose unmodified fields still follow hot reloads via SyncMaterials.
	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
	// Effect is the live effect player built from Doc.Particles.Effect, or nil when the object has none. BuiltScene.Update steps it and BuiltScene.Draw draws it at the object's world transform; BuiltObject.Sync and BuiltScene.SetParticleQuality keep its placement and quality current.
	Effect *particles.EffectPlayer
	// SoundEmitter is the live 2D sound emitter built from Doc.Sound or the built-in "sound" component, or nil when the object has none.
	SoundEmitter *SoundEmitter2D
	// 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
	// WorldModulate is the object's composed RGBA modulate color for its own drawables (parent inherited modulate * Doc.Modulate * Doc.SelfModulate); opaque white when untinted.
	WorldModulate core.Color
	// WorldVisible reports whether this object and every ancestor are visible; false skips drawing and hit testing for the entire subtree.
	WorldVisible bool
	// VisibilityLayers is the 32-bit visibility bitmask resolved from Doc.VisibilityLayers; 0 matches every cull mask.
	VisibilityLayers uint32
	// Hidden suppresses rendering of this object and its descendants without changing the document alpha.
	Hidden bool
	// LightMask is the 32-bit 2D light mask bitmask resolved from Doc.LightMask (inheriting parent or layer LightMask when unset); 0 marks an unlit object drawn right after its layer's light pass, above the layer's lit content.
	LightMask uint32
	// contains filtered or unexported fields
}

BuiltObject is one object instantiated from an ObjectDoc.

func (*BuiltObject) Active

func (bo *BuiltObject) Active() bool

Active reports whether bo is live and active (neither freed nor paused in a data layer whose effective state is DataLayerLoaded).

func (*BuiltObject) Find

func (o *BuiltObject) Find(path string) *BuiltObject

Find resolves a slash-separated path relative to o (such as "body/sprite" or "Body/Sprite") and returns the matching live descendant (or ancestor via "..", or o itself via "."), or nil if no live object matches.

Each path segment matches direct children in priority order: exact ID, local ID suffix after the last '/' (so instanced children such as "enemy_1/body" match "body"), then display Name (Doc.Name). Find performs zero heap allocations.

func (*BuiltObject) Freed

func (bo *BuiltObject) Freed() bool

Freed reports whether bo has been removed from its BuiltScene via BuiltScene.Free.

func (*BuiltObject) Sync

func (bo *BuiltObject) Sync() bool

Sync recomputes the object's World, WorldAlpha, WorldModulate and WorldVisible from its document and its parent's, copies its transform, sprite frame (when found in Atlas), origin, flip, alpha, modulate and visibility onto its sprite, emitter and skeleton, 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 BuiltPathFollower

type BuiltPathFollower struct {
	// Object is the built child object moved along Path.
	Object *BuiltObject
	// PathObject is the parent built object carrying the "path2d" component.
	PathObject *BuiltObject
	// Path is the parent object's local-space BezierPath.
	Path *tween.BezierPath
	// Follower is the underlying tween.PathFollower advancing along Path.
	Follower *tween.PathFollower
	// Rotates reports whether Sync writes Follower.Angle() onto Object.Doc.Rotation.
	Rotates bool
	// contains filtered or unexported fields
}

BuiltPathFollower is the runtime state of one built-in "path_follow2d" component attached to a child of a "path2d" object. BuiltScene.Update advances Follower and copies its local position (and heading angle when Rotates is true) onto Object before calling Object.Sync().

func (*BuiltPathFollower) Sync

func (pf *BuiltPathFollower) Sync()

Sync applies Follower's current Position (and Angle when Rotates is true) onto Object.Doc, updates Object's composed world transform and children via Object.Sync(), and updates any attached 2D physics body on BuiltScene.Physics.

type BuiltScene

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
	// Modulate is the parsed whole-scene modulate color multiplying every layer; opaque white when unset.
	Modulate core.Color
	// CullMask restricts Draw and HitTest to layers and objects whose VisibilityLayers matches CullMask; 0 includes all layers and objects.
	CullMask uint32
	// 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.
	NavBake2D *navbake.Mesh
	// NavMesh2D is the runtime 2D pathfind.NavMesh constructed from NavBake2D (including any authored 2D nav_link components), or nil when the scene defines no navregion2d components.
	NavMesh2D *pathfind.NavMesh
	// 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

	// Notifiers are the runtime states of the scene's built-in "on_screen" components, in document order, or nil when the scene defines none. Update steps them against the camera views and pauses the parts each one's pause list names while it is off-screen.
	Notifiers []*ScreenNotifier
	// Paths2D indexes the local-space *tween.BezierPath built for every object carrying a built-in "path2d" component, by object ID, or nil when the scene defines none.
	Paths2D map[string]*tween.BezierPath
	// PathFollowers are the runtime states of the scene's built-in "path_follow2d" components whose parent carries a "path2d" component, in document order, or nil when the scene defines none. Update advances them and syncs each follower object's transform.
	PathFollowers []*BuiltPathFollower
	// ScreenSignals, when non-nil, receives the "on_screen.entered" and "on_screen.exited" events the Notifiers fire during Update. Set it to the Signals Connect made for the scene's connections to run their handlers.
	ScreenSignals *Signals
	// Signals, when non-nil, receives events emitted by built-in motion and controller behavior components during Step (falling back to ScreenSignals when nil).
	Signals *Signals
	// Physics is the PhysicsScene built from this scene by BuildPhysics (set automatically by BuildPhysics), used by built-in motion behaviors such as bullet.bounceOffSolids and move_to.stopOnSolids and controller behaviors such as platform and line_of_sight.
	Physics *PhysicsScene
	// SoundEmitters are the 2D sound emitters built from ObjectDoc.Sound and the built-in "sound" component, in document order.
	SoundEmitters []*SoundEmitter2D
	// SoundZones is the 2D sound zone router built from ObjectDoc.SoundZone regions, or nil when the scene defines none.
	SoundZones *sound.ZoneRouter
	// SoundMixer, when set, receives live 2D listener updates and zone bus crossfade weights during UpdateSounds / Update.
	SoundMixer *sound.Mixer
	// SoundSoftware, when set, receives zone reverb send levels during UpdateSounds / Update.
	SoundSoftware *sound.SoftwareMixer
	// SoundListener2D, when non-nil, supplies the 2D listener used automatically by Update / UpdateWithViews.
	SoundListener2D *sound.Listener2D
	// Input, when non-nil, supplies named actions, axes, and vectors read by built-in input-driven controller components during Step (*input.Actions, *replay.Player, *replay.Recorder, or any replay.ActionSource).
	Input ActionInput
	// Pointer holds the world-space pointer state read by built-in drag_drop components during Step (update directly or call SetPointer).
	Pointer PointerInput
	// Vars, when non-nil, supplies the shared project variable store used by built-in map_event components.
	Vars *flow.Vars
	// EventCommands, when non-nil, validates and executes call commands inside built-in map_event components.
	EventCommands *flow.CommandRegistry
	// EventLists maps named command lists invoked by run.list inside built-in map_event components.
	EventLists map[string][]flow.EventCommand
	// EventCallbacks configures game hooks invoked when built-in map_event components execute commands.
	EventCallbacks MapEventCallbacks
	// EventPlayerID optionally names the player object used for touch and action map_event triggers (defaults to the "player" group or object ID "player").
	EventPlayerID string
	// EventAction names the Input action that triggers facing/overlapping "action" map_event components (defaults to DefaultMapEventAction).
	EventAction string

	// 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

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.

Example

Build turns a parsed scene into sprites ready to draw, resolving each sprite's atlas through an AssetResolver such as an AtlasMap.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/sceneformat"
	"github.com/nsgo-dev/game/pkg/sprite"
	"github.com/nsgo-dev/nsgo/core"
)

const room = `# yaml-language-server: $schema=https://nsgo.games/schemas/scene.v1.json
version: 1
name: cave
layers:
  - name: props
    objects:
      - id: chest
        x: 120
        "y": 64
        sprite:
          atlas: props
          frame: chest
      - id: door
        x: 200
        "y": 64
        sprite:
          atlas: props
          frame: door
`

func main() {
	doc, _ := sceneformat.Parse([]byte(room))
	props, err := sprite.LoadAtlas(core.ImageSource{URI: "asset:props.png"}, []byte(`{"frames": {
		"chest": {"frame": {"x": 0, "y": 0, "w": 16, "h": 16}, "sourceSize": {"w": 16, "h": 16}},
		"door": {"frame": {"x": 16, "y": 0, "w": 16, "h": 32}, "sourceSize": {"w": 16, "h": 32}}
	}, "meta": {"scale": "1"}}`))
	if err != nil {
		fmt.Println(err)
		return
	}
	built, err := sceneformat.Build(doc, sceneformat.AtlasMap{"props": props})
	if err != nil {
		fmt.Println(err)
		return
	}
	door := built.Object("door")
	fmt.Println(door.Layer, door.Sprite.X, door.Sprite.Y, door.Sprite.Frame.H)
}
Output:
props 200 64 32

func BuildWithPersistence

func BuildWithPersistence(doc *SceneDoc, resolver AssetResolver, p *save.Persistence, scenePath string) (*BuiltScene, error)

BuildWithPersistence resolves doc (when it instances or inherits other scenes), applies any persisted object state for scenePath from p, and builds the resulting BuiltScene.

func (*BuiltScene) Animator

func (s *BuiltScene) Animator(objectID string) AnimatorController

Animator returns the AnimatorController attached to objectID on this built scene, or nil when none is set.

func (*BuiltScene) ApplyDataLayerStates

func (s *BuiltScene) ApplyDataLayerStates(states map[string]DataLayerState) error

ApplyDataLayerStates restores a map of saved data layer states onto s in deterministic sorted order, returning an error if any layer name or state is invalid.

func (*BuiltScene) BehaviorScene

func (s *BuiltScene) BehaviorScene() *BuiltScene

BehaviorScene returns s so *BuiltScene satisfies BehaviorSceneProvider.

func (*BuiltScene) BindSounds

func (s *BuiltScene) BindSounds(resolver SoundResolver) error

BindSounds resolves all unbound 2D sound emitters on s using resolver.

func (*BuiltScene) BuildVCamDirector

func (s *BuiltScene) BuildVCamDirector(viewWidth, viewHeight float32, opts VCamBuildOptions) (*VCamSystem, error)

BuildVCamDirector builds a VCamSystem attached to this BuiltScene.

func (*BuiltScene) BuiltScene

func (s *BuiltScene) BuiltScene() *BuiltScene

BuiltScene returns s, implementing BuiltSceneProvider.

func (*BuiltScene) CarState

func (s *BuiltScene) CarState(objectID string) (CarRuntimeState, bool)

CarState returns the current runtime state of objectID's "car" controller.

func (*BuiltScene) ChooseMapEvent

func (s *BuiltScene) ChooseMapEvent(objectID string, choice int) error

ChooseMapEvent selects choice index for a paused choose command on objectID's map event.

func (*BuiltScene) ClearTurretTarget

func (s *BuiltScene) ClearTurretTarget(objectID string) bool

ClearTurretTarget clears objectID's currently acquired "turret" target.

func (*BuiltScene) ContinueMapEvent

func (s *BuiltScene) ContinueMapEvent(objectID string) error

ContinueMapEvent advances past a paused say command on objectID's map event.

func (*BuiltScene) DataLayerState

func (s *BuiltScene) DataLayerState(name string) DataLayerState

DataLayerState returns the configured runtime state of the named data layer, or DataLayerActive when s is nil or name is not declared.

func (*BuiltScene) DataLayerStates

func (s *BuiltScene) DataLayerStates() map[string]DataLayerState

DataLayerStates returns a snapshot map of all declared data layers and their current configured states (suitable for saving with game state).

func (*BuiltScene) DragDropState

func (s *BuiltScene) DragDropState(objectID string) (DragDropRuntimeState, bool)

DragDropState returns the current runtime state of objectID's "drag_drop" controller.

func (*BuiltScene) Draw

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. When Lights2D is active, layers still draw in order and lit world-space layers are illuminated per LightMask (DrawLayersLit), while unlit layers (LightMask == 0), unlit objects (BuiltObject.LightMask == 0), and screen-space layers are never lit. 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 (*BuiltScene) DrawLayer

func (s *BuiltScene) DrawLayer(d *core.Drawing, layer *BuiltLayer, view *tilemap.Camera)

DrawLayer draws layer into d applying both the scene's Modulate and CullMask alongside the layer's Tint and Opacity. When view is nil, every tile of Map draws without culling.

func (*BuiltScene) DrawLayerPart

func (s *BuiltScene) DrawLayerPart(d *core.Drawing, layer *BuiltLayer, view *tilemap.Camera, part LightPart)

DrawLayerPart is DrawLayer restricted to part of the layer's content: LightPartLit draws its tilemaps and the objects with a non-zero LightMask, LightPartUnlit only the objects with LightMask 0, and LightPartAll everything, like DrawLayer.

func (*BuiltScene) DrawLayersLit

func (s *BuiltScene) DrawLayersLit(d *core.Drawing, layers []*BuiltLayer, width, height float32, drawLayer func(dst *core.Drawing, layer *BuiltLayer, part LightPart), drawLights func(dst *core.Drawing, mask uint32))

DrawLayersLit draws layers into d in the given order with 2D lighting split by light mask; Draw uses it for the scene's visible layers, and the editor for its lighting preview. Consecutive world-space layers with the same non-zero LightMask form a run: drawLayer draws the run, then drawLights(dst, mask) lights it. Screen-space layers, world layers with LightMask 0, and objects with LightMask 0 (drawn with LightPartUnlit right after their layer's run) keep their place in the order and are never lit. When unlit content or an earlier run was already drawn, a run is lit in an offscreen surface of width by height points so the light pass does not darken what lies beneath; with no size it is lit in place. When layers has no world-space layer, drawLights(d, all bits) runs first, as before any layer.

func (*BuiltScene) DropDrag

func (s *BuiltScene) DropDrag(objectID string) bool

DropDrag ends an active "drag_drop" drag on objectID and emits drag_drop.dropped.

func (*BuiltScene) EffectiveDataLayerState

func (s *BuiltScene) EffectiveDataLayerState(name string) DataLayerState

EffectiveDataLayerState returns the effective runtime state of name: the minimum of its own state and every ancestor layer's state. Unknown layers return DataLayerActive.

func (*BuiltScene) EightDirectionState

func (s *BuiltScene) EightDirectionState(objectID string) (EightDirectionRuntimeState, bool)

EightDirectionState returns the current runtime state of objectID's "eight_direction" controller.

func (*BuiltScene) FlushFree

func (s *BuiltScene) FlushFree() int

FlushFree tears down every object queued by QueueFree or deferred Free calls and returns how many queued roots were freed. Calling FlushFree while an Update, Step, or PhysicsScene.Step is active returns 0; those frees flush automatically when the step finishes.

func (*BuiltScene) Free

func (s *BuiltScene) Free(id string) bool

Free removes the built object with ID id and all of its descendants from s (and from s.Doc) so they are no longer drawn, updated, stepped, lit, navigated, or queried in physics, unwires their connections from Signals, and destroys any live ECS entities spawned for them.

When called during BuiltScene.Update, BuiltScene.Step, or PhysicsScene.Step, Free marks the object and its descendants as pending-free so they stop stepping immediately and defers structural teardown to the end of the step. Free is idempotent and returns false when s is nil or has no live object with ID id.

func (*BuiltScene) HasTarget

func (s *BuiltScene) HasTarget(objectID string) bool

HasTarget reports whether objectID's "turret", "line_of_sight", or "path_agent" controller currently has a target.

func (*BuiltScene) HitTest

func (s *BuiltScene) HitTest(x, y float32) *BuiltObject

HitTest returns the topmost visible BuiltObject hit by canvas/virtual-viewport point (x, y), or nil if none hits. Hidden layers, layers/objects excluded by BuiltScene.CullMask, and objects with WorldVisible == false (along with their entire subtrees) are skipped.

func (*BuiltScene) HitTestAll

func (s *BuiltScene) HitTestAll(x, y float32) []*BuiltObject

HitTestAll returns all visible BuiltObjects hit by canvas/virtual-viewport point (x, y), ordered topmost to bottommost. Hidden layers, layers/objects excluded by BuiltScene.CullMask, and objects with WorldVisible == false (along with their entire subtrees) are skipped.

func (*BuiltScene) InGroup

func (s *BuiltScene) InGroup(group string) []*BuiltObject

InGroup returns all live built objects in s that belong to group, in deterministic build order (layer draw order and depth-first document order, with runtime-instanced objects appended in instantiation order).

When no member of group is pending deferred free, InGroup reads the scene's per-group index directly and performs zero heap allocations. Callers must not modify the returned slice.

func (*BuiltScene) Instantiate

func (s *BuiltScene) Instantiate(doc *SceneDoc, resolver AssetResolver, opts InstanceOptions) (*Instance, error)

Instantiate resolves and validates doc, builds its objects under opts.Layer (optionally parented under opts.Parent) at local position (opts.X, opts.Y), appends them and their prefixed connections to BuiltScene.Doc, and registers them with all active runtime systems (sprites/batches in Z order, emitters, skeletons, materials, 2D/3D physics, 2D lighting, 2D navigation, on-screen notifiers, motion behaviors, optional ECS World entities and ComponentType.Spawn factories, and optional Signals connections).

Nothing in s, s.Doc, opts.World, or opts.Signals changes if validation, resolution, asset loading, component spawning, or connection wiring fails. Cyclic scene references (static or recursive runtime instancing) and nesting deeper than MaxSceneNesting are refused.

Example

A level scene's built-in timer spawns an enemy scene file into the running BuiltScene at runtime via Instantiate, wires its internal connections and ECS components, and frees it with Free when it dies.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/entities"
	"github.com/nsgo-dev/game/pkg/sceneformat"
)

func main() {
	type HP struct{ Value int }

	world := entities.NewWorld()
	reg := sceneformat.NewComponentRegistry()
	_ = sceneformat.RegisterTimerComponent(reg)

	var built *sceneformat.BuiltScene
	var sig *sceneformat.Signals
	var enemyDoc *sceneformat.SceneDoc
	var spawnedIDs []string

	reg.MustRegister(sceneformat.ComponentType{
		Name: "spawner",
		Handlers: []sceneformat.Handler{{
			Name: "spawn",
			Func: func(c sceneformat.Call) {
				inst, err := built.Instantiate(enemyDoc, nil, sceneformat.InstanceOptions{
					Layer:      "actors",
					X:          float32(len(spawnedIDs)+1) * 32,
					Y:          64,
					Source:     "prefabs/goblin.scene.yaml",
					World:      world,
					Signals:    sig,
					Components: reg,
				})
				if err != nil {
					fmt.Println("spawn error:", err)
					return
				}
				spawnedIDs = append(spawnedIDs, inst.Prefix)
				fmt.Println("spawned", inst.Prefix)
			},
		}},
	})
	reg.MustRegister(sceneformat.ComponentType{
		Name:   "enemy",
		Fields: []sceneformat.Field{{Name: "hp", Kind: sceneformat.FieldInt, Default: 2}},
		Events: []sceneformat.Event{{Name: "hit"}, {Name: "died"}},
		Handlers: []sceneformat.Handler{{
			Name: "hurt",
			Func: func(c sceneformat.Call) {
				hp, ok := entities.Get[HP](world, c.TargetEntity)
				if !ok {
					return
				}
				hp.Value--
				entities.Set(world, c.TargetEntity, hp)
				if hp.Value <= 0 {
					_ = c.Signals.Emit(c.Target.ID, "enemy.died", nil)
				}
			},
		}},
		Spawn: func(w *entities.World, e entities.Entity, fields map[string]any) error {
			entities.Set(w, e, HP{Value: fields["hp"].(int)})
			return nil
		},
	})

	levelDoc, _ := sceneformat.ParseWith([]byte(`version: 1
layers:
  - name: actors
    objects:
      - id: wave_spawner
        components:
          timer: {seconds: 1, autostart: true}
          spawner: {}
      - {id: dummy, components: {enemy: {hp: 1}}}
connections:
  - {from: wave_spawner, event: timer.timeout, to: wave_spawner, handler: spawner.spawn}
`), sceneformat.ParseOptions{Components: reg})

	enemyDoc, _ = sceneformat.ParseWith([]byte(`version: 1
layers:
  - name: p
    objects:
      - id: body
        components:
          enemy: {hp: 2}
connections:
  - {from: body, event: enemy.hit, to: body, handler: enemy.hurt}
`), sceneformat.ParseOptions{Components: reg})

	built, _ = sceneformat.Build(levelDoc, nil)
	_, sig, _ = sceneformat.SpawnConnected(built.Doc, world, reg, built)
	built.Signals = sig

	// Free each enemy root as soon as its body emits enemy.died.
	stop, _ := sig.Listen("", "enemy.died", func(c sceneformat.Call) {
		if body := built.Object(c.Source.ID); body != nil && body.Parent != nil {
			rootID := body.Parent.ID
			built.Free(rootID)
			fmt.Println("freed", rootID)
		}
	}, sceneformat.ListenOptions{})
	defer stop()

	// Step the timer once to spawn goblin#1, hit it twice so it dies and frees itself.
	_ = sig.Update(time.Second)
	_ = sig.Flush()
	_ = sig.Emit("goblin#1/body", "enemy.hit", nil)
	_ = sig.Emit("goblin#1/body", "enemy.hit", nil)
	fmt.Println("alive:", built.Object("goblin#1") != nil)
}
Output:
spawned goblin#1
freed goblin#1
alive: false

func (*BuiltScene) InteractMapEvent

func (s *BuiltScene) InteractMapEvent() (string, bool)

InteractMapEvent finds the idle action-triggered map_event facing or overlapping the player and starts it.

func (*BuiltScene) IsMapEventBlocking

func (s *BuiltScene) IsMapEventBlocking() bool

IsMapEventBlocking reports whether an autorun map_event is currently blocking player controller input.

func (*BuiltScene) IsMoving

func (s *BuiltScene) IsMoving(objectID string) bool

IsMoving reports whether any built-in controller component on objectID is currently moving.

func (*BuiltScene) IsOnFloor

func (s *BuiltScene) IsOnFloor(objectID string) bool

IsOnFloor reports whether objectID's "platform" controller is currently grounded.

func (*BuiltScene) LastSceneTileError

func (s *BuiltScene) LastSceneTileError() error

LastSceneTileError returns the most recent error produced while instancing a scene tile at run time via Tilemap.SetTile, or nil.

func (*BuiltScene) Layer

func (s *BuiltScene) Layer(name string) *BuiltLayer

Layer returns the built layer named name, or nil if none exists.

func (*BuiltScene) LineOfSightState

func (s *BuiltScene) LineOfSightState(objectID string) (LineOfSightRuntimeState, bool)

LineOfSightState returns the current runtime state of objectID's "line_of_sight" controller.

func (*BuiltScene) MapEventState

func (s *BuiltScene) MapEventState(objectID string) (MapEventRuntimeState, bool)

MapEventState returns the runtime status of objectID's built-in "map_event" component.

func (*BuiltScene) MoveTo

func (s *BuiltScene) MoveTo(objectID string, x, y float64) bool

MoveTo commands objectID's built-in "move_to" behavior to move toward (x, y).

func (*BuiltScene) NewCamera

func (s *BuiltScene) NewCamera() *tilemap.Camera

NewCamera constructs a tilemap.Camera from BuiltScene.Camera and the scene's virtual viewport size (Doc.VirtualWidth by Doc.VirtualHeight). When Camera is nil, it returns a default camera centered on the virtual viewport (or the origin when virtual dimensions are 0).

func (*BuiltScene) NewCameraRig

func (s *BuiltScene) NewCameraRig(cam *tilemap.Camera) *tilemap.CameraRig

NewCameraRig constructs a tilemap.CameraRig from BuiltScene.Camera.Follow bound to cam. When cam is nil, it builds one via NewCamera.

func (*BuiltScene) NewInstancePool

func (s *BuiltScene) NewInstancePool(doc *SceneDoc, resolver AssetResolver, opts InstanceOptions) (*InstancePool, error)

NewInstancePool validates and pre-compiles doc for repeated steady-state spawning on s under opts.Layer (and optional opts.Parent, opts.World, opts.Signals, opts.Components). Nothing in s changes if doc, assets, components, physics, lights, or connections are invalid.

func (*BuiltScene) Object

func (s *BuiltScene) Object(id string) *BuiltObject

Object returns the built object with ID id, or nil if none exists.

func (*BuiltScene) PathAgentMoveTo

func (s *BuiltScene) PathAgentMoveTo(objectID string, x, y float64) bool

PathAgentMoveTo commands objectID's "path_agent" component to walk to (x, y) on BuiltScene.NavMesh2D.

func (*BuiltScene) PathAgentState

func (s *BuiltScene) PathAgentState(objectID string) (PathAgentRuntimeState, bool)

PathAgentState returns the current runtime state of objectID's "path_agent" controller.

func (*BuiltScene) PathAgentStop

func (s *BuiltScene) PathAgentStop(objectID string) bool

PathAgentStop clears objectID's "path_agent" target.

func (*BuiltScene) PathFollower

func (s *BuiltScene) PathFollower(objectID string) *BuiltPathFollower

PathFollower returns the runtime BuiltPathFollower attached to objectID, or nil when none exists.

func (*BuiltScene) PlatformState

func (s *BuiltScene) PlatformState(objectID string) (PlatformRuntimeState, bool)

PlatformState returns the current runtime state of objectID's "platform" controller.

func (*BuiltScene) QueueFree

func (s *BuiltScene) QueueFree(id string) bool

QueueFree marks object id and its descendants as pending-free and schedules them for teardown on the next FlushFree (or at the end of the current/next Update, Step, or PhysicsScene.Step). It is idempotent and returns false when s has no live object with ID id.

func (*BuiltScene) Restore

func (s *BuiltScene) Restore(snap ControllerSnapshot) error

Restore validates snap and atomically restores all snapshotted controller states and object transforms on s. If validation fails for any object or field, s is left completely unchanged.

func (*BuiltScene) SetAnimator

func (s *BuiltScene) SetAnimator(objectID string, ctrl AnimatorController)

SetAnimator attaches ctrl as the runtime AnimatorController for objectID on this built scene (passing nil removes it). BuiltScene implements AnimatorProvider, so passing a BuiltScene as Call.Context to Connect lets the built-in "animator" component's setState and trigger handlers drive any animator registered here.

func (*BuiltScene) SetBehaviorEnabled

func (s *BuiltScene) SetBehaviorEnabled(objectID, component string, enabled bool) bool

SetBehaviorEnabled enables or disables the named motion behavior component on objectID. It returns false when s has no live objectID with that behavior.

func (*BuiltScene) SetBulletSpeed

func (s *BuiltScene) SetBulletSpeed(objectID string, speed float64) bool

SetBulletSpeed updates objectID's built-in "bullet" travel speed in points per second.

func (*BuiltScene) SetControllerEnabled

func (s *BuiltScene) SetControllerEnabled(objectID, component string, enabled bool) bool

SetControllerEnabled enables or disables the named input-driven controller component on objectID.

func (*BuiltScene) SetDataLayer

func (s *BuiltScene) SetDataLayer(name string, state DataLayerState) error

SetDataLayer sets the runtime state of declared data layer name to state ("unloaded", "loaded", or "active") and updates all affected objects in the scene (including any child layers whose effective state depends on name and any cells currently loaded by an attached Streamer).

Objects whose effective state transitions to "unloaded" have their changed state captured and are removed from BuiltScene; objects transitioning to "loaded" are instanced in BuiltScene.Objects without being drawn or simulated; objects transitioning to "active" become live, drawn, and simulated.

func (*BuiltScene) SetMapEventEnabled

func (s *BuiltScene) SetMapEventEnabled(objectID string, enabled bool) bool

SetMapEventEnabled enables or disables objectID's map_event component.

func (*BuiltScene) SetParticleQuality

func (s *BuiltScene) SetParticleQuality(level quality.Level)

SetParticleQuality sets the quality level every built effect player compares its emitters' minQuality against, such as the level quality.Selector currently picks. BuiltScene.Update steps players whose emitters are below the level without emitting, and BuiltScene.Draw skips them.

func (*BuiltScene) SetPointer

func (s *BuiltScene) SetPointer(x, y float32, pressed bool)

SetPointer updates s.Pointer in world coordinates and computes JustPressed / JustReleased edges relative to the previous pressed state.

func (*BuiltScene) SimulateControl

func (s *BuiltScene) SimulateControl(objectID, component, action string) bool

SimulateControl queues one simulated control action on objectID's named controller component for the next Step.

func (*BuiltScene) Snapshot

func (s *BuiltScene) Snapshot() ControllerSnapshot

Snapshot returns a versioned, deterministic, YAML/JSON-serializable snapshot of all live input-driven controller components on s and their objects' transforms.

func (*BuiltScene) Step

func (s *BuiltScene) Step(dt time.Duration)

Step advances all built-in 2D motion behavior components on s by dt on the fixed loop (deterministic, no wall clock). It updates each object's transform and opacity, syncs sprites/emitters/skeletons/children, emits behavior events through Signals (or ScreenSignals), and frees objects whose destroy_outside or fade (destroy: true) completes.

func (*BuiltScene) StepWithViews

func (s *BuiltScene) StepWithViews(dt time.Duration, views ...*tilemap.Camera)

StepWithViews is Step with extra camera views used by behaviors whose mode is "view" (wrap and destroy_outside), matching BuiltScene.UpdateWithViews.

func (*BuiltScene) StopSounds

func (s *BuiltScene) StopSounds()

StopSounds stops every 2D sound emitter in s so no active playbacks remain.

func (*BuiltScene) SyncLights2D

func (s *BuiltScene) SyncLights2D() error

SyncLights2D rebuilds s.Lights2D from the scene's current object transforms, component values, ambient color, and tilemaps, preserving Mode, BufferScale, LightComposite, and DisableShadows when a Lights2D scene already existed.

func (*BuiltScene) SyncMaterials

func (s *BuiltScene) SyncMaterials()

SyncMaterials merges hot-reloaded changes into any local material copies (keeping fields modified on the object's copy) and 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 materials or sprites without drawing.

func (*BuiltScene) SyncNavMesh2D

func (s *BuiltScene) SyncNavMesh2D() error

SyncNavMesh2D rebuilds s.NavBake2D and s.NavMesh2D from the scene's current object transforms, navregion2d components, and tilemaps.

func (*BuiltScene) TileMovementState

func (s *BuiltScene) TileMovementState(objectID string) (TileMovementRuntimeState, bool)

TileMovementState returns the current runtime state of objectID's "tile_movement" controller.

func (*BuiltScene) TriggerFlash

func (s *BuiltScene) TriggerFlash(objectID string, duration float64) bool

TriggerFlash commands objectID's built-in "flash" behavior to blink for duration seconds.

func (*BuiltScene) TriggerMapEvent

func (s *BuiltScene) TriggerMapEvent(objectID string) error

TriggerMapEvent starts objectID's active map-event page (when enabled and idle).

func (*BuiltScene) TurretState

func (s *BuiltScene) TurretState(objectID string) (TurretRuntimeState, bool)

TurretState returns the current runtime state of objectID's "turret" controller.

func (*BuiltScene) Update

func (s *BuiltScene) Update(dt time.Duration)

Update advances any built-in "path_follow2d" followers (BuiltScene.PathFollowers), 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 positions, frames and poses. An emitter or rig whose object carries an "on_screen" component pausing it is skipped while the notifier is off-screen and resumes where it stopped when the object comes back into view.

func (*BuiltScene) UpdateSounds

func (s *BuiltScene) UpdateSounds(listener sound.Listener2D, dt time.Duration)

UpdateSounds refreshes SoundMixer's 2D listener (when set), updates every 2D sound emitter against listener over dt (handling live pan, Doppler, distance cutoff, and distance culling beyond Far), and steps SoundZones against listener.Position.

func (*BuiltScene) UpdateWithViews

func (s *BuiltScene) UpdateWithViews(dt time.Duration, views ...*tilemap.Camera)

UpdateWithViews is Update with extra camera views counting toward the "on_screen" notifiers' visibility, such as every scene.SplitScreen viewport's camera; an object is on screen when any view sees it. The scene's own camera view (its virtual viewport through BuiltScene.Camera) always counts, nil views are ignored, and a scene with no virtual size and no extra views treats every notifier as on-screen.

type BuiltSceneProvider

type BuiltSceneProvider interface {
	BuiltScene() *BuiltScene
}

BuiltSceneProvider may be implemented by Call.Context to supply the live scene used by built-in scene handlers.

type BulletBouncedEvent

type BulletBouncedEvent struct {
	ObjectID string
	X, Y     float32
	NormalX  float32
	NormalY  float32
	Angle    float64
}

BulletBouncedEvent is the payload emitted with an object's "bullet.bounced" event.

type CSGDoc

type CSGDoc struct {
	// Op is how this node combines with the CSG siblings before it in its parent combiner: "union", "intersection" or "subtract", default "union", on a combiner and a primitive alike. It has no effect on a CSG node that is not inside a combiner, nor on the first CSG child of a combiner, which starts the result; game check reports a value other than "union" in either place.
	Op string `yaml:"op,omitempty" schema:"enum=union|intersection|subtract"`
	// Shape is the primitive's shape: "box", "sphere", "cylinder", "cone", "capsule", "plane", "torus", "polygon" or "mesh"; empty makes the node a combiner.
	Shape string `yaml:"shape,omitempty" schema:"enum=box|sphere|cylinder|cone|capsule|plane|torus|polygon|mesh"`
	// Size is a box's or plane's width, height and depth; each must be positive for those shapes and finite and non-negative otherwise.
	Size [3]float32 `yaml:"size,omitempty"`
	// Radius is a sphere's, cylinder's, cone's, capsule's or torus's (major) radius, and the bottom radius of a cylinder or cone; must be positive for those shapes, except that a cylinder or cone with a positive TopRadius may leave it 0.
	Radius float32 `yaml:"radius,omitempty" schema:"minimum=0"`
	// TubeRadius is a torus's minor (tube) radius; must be positive and smaller than Radius for a torus.
	TubeRadius float32 `yaml:"tubeRadius,omitempty" schema:"minimum=0"`
	// TopRadius is the radius at the top (+Y) of a cylinder or cone, whose bottom radius is Radius, for tapered cylinders and frustums; 0 or omitted keeps each shape's own top, Radius for a cylinder and a point for a cone. Radius and TopRadius must not both be 0.
	TopRadius float32 `yaml:"topRadius,omitempty" schema:"minimum=0"`
	// Height is a cylinder's, cone's or capsule's height; must be positive for those shapes.
	Height float32 `yaml:"height,omitempty" schema:"minimum=0"`
	// Segments is the optional radial tessellation count for round shapes; 0 uses the shape default.
	Segments int `yaml:"segments,omitempty" schema:"minimum=0"`
	// Rings is the optional ring count for sphere, capsule or torus shapes; 0 uses the shape default.
	Rings int `yaml:"rings,omitempty" schema:"minimum=0"`
	// Points are the 2D XY cross-section vertices for a "polygon" shape: at least three finite points forming a simple outline with non-zero area whose edges do not cross or touch; in "spin" mode every point has X >= 0 and at least one has X > 0.
	Points [][2]float32 `yaml:"points,omitempty"`
	// Mode selects how a "polygon" shape is extruded: "depth" (default), "spin" or "path".
	Mode string `yaml:"mode,omitempty" schema:"enum=depth|spin|path"`
	// Depth is the Z extrusion distance for a "polygon" shape in "depth" mode.
	Depth float32 `yaml:"depth,omitempty" schema:"minimum=0"`
	// SpinDegrees is the revolution angle in degrees for a "polygon" shape in "spin" mode, in (0, 360]; 0 defaults to 360.
	SpinDegrees float32 `yaml:"spinDegrees,omitempty" schema:"minimum=0,maximum=360"`
	// SpinSides is the angular step count for a "polygon" shape in "spin" mode; 0 uses the default.
	SpinSides int `yaml:"spinSides,omitempty" schema:"minimum=0"`
	// Path names a Path3D object ID in the scene for a "polygon" shape in "path" mode.
	Path string `yaml:"path,omitempty"`
	// Interval is the arc-length step between cross-sections for a "polygon" shape in "path" mode; 0 picks a default.
	Interval float32 `yaml:"interval,omitempty" schema:"minimum=0"`
	// Rotation controls cross-section orientation along Path for a "polygon" shape in "path" mode: "polygon", "path" (default) or "pathFollow".
	Rotation string `yaml:"rotation,omitempty" schema:"enum=polygon|path|pathFollow"`
	// Joined closes a "polygon" path sweep seamlessly back to its first cross-section without end caps.
	Joined bool `yaml:"joined,omitempty"`
	// Mesh is the slash-separated project-relative path to a .gltf or .glb model for a "mesh" shape.
	Mesh string `yaml:"mesh,omitempty"`
	// Collision asks the scene builder to generate a physics3d.TriMeshCollider for the combined geometry.
	Collision bool `yaml:"collision,omitempty"`
	// CollisionLayer is the optional physics layer bitmask for the generated collider; 0 uses the default layer.
	CollisionLayer uint32 `yaml:"collisionLayer,omitempty"`
	// CollisionMask is the optional physics collision mask for the generated collider; 0 uses the default mask.
	CollisionMask uint32 `yaml:"collisionMask,omitempty"`
}

CSGDoc describes one constructive-solid-geometry node or primitive (ObjectDoc.CSG). A combiner sets no Shape and combines its CSG children in order, starting from the first and applying each later child with that child's Op; a primitive sets Shape and has no children. A primitive whose parent is not a combiner is valid and is evaluated on its own as a root CSG object, with its Op ignored. Package scenemodel evaluates CSG subtrees with pkg/world3d/csg into meshes and optional physics3d.TriMeshCollider colliders.

type Call

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

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"`
	// DOF optionally configures depth of field for this camera; nil leaves it disabled.
	DOF *DOFDoc `yaml:"dof,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 (*Camera3DDoc) Clone

func (c *Camera3DDoc) Clone() *Camera3DDoc

Clone returns a deep copy of c, or nil when c is nil.

func (*Camera3DDoc) EffectiveFOV

func (c *Camera3DDoc) EffectiveFOV() float32

EffectiveFOV returns a perspective camera's vertical field of view in degrees, defaulting to 60 when nil.

func (*Camera3DDoc) EffectiveFar

func (c *Camera3DDoc) EffectiveFar() float32

EffectiveFar returns the far clip plane distance, defaulting to 1000 when nil.

func (*Camera3DDoc) EffectiveNear

func (c *Camera3DDoc) EffectiveNear() float32

EffectiveNear returns the near clip plane distance, defaulting to 0.1 when nil.

func (*Camera3DDoc) EffectiveOrthoHeight

func (c *Camera3DDoc) EffectiveOrthoHeight() float32

EffectiveOrthoHeight returns an orthographic camera's full vertical world height, defaulting to 10 when nil.

func (*Camera3DDoc) EffectiveProjection

func (c *Camera3DDoc) EffectiveProjection() ProjectionKind

EffectiveProjection returns c.Projection, defaulting to ProjectionPerspective when empty.

type CameraDeadZoneDoc

type CameraDeadZoneDoc struct {
	// Left is the drag margin fraction extending left from the view center, in [0, 1].
	Left float32 `yaml:"left,omitempty" schema:"minimum=0,maximum=1"`
	// Right is the drag margin fraction extending right from the view center, in [0, 1].
	Right float32 `yaml:"right,omitempty" schema:"minimum=0,maximum=1"`
	// Top is the drag margin fraction extending upward from the view center, in [0, 1].
	Top float32 `yaml:"top,omitempty" schema:"minimum=0,maximum=1"`
	// Bottom is the drag margin fraction extending downward from the view center, in [0, 1].
	Bottom float32 `yaml:"bottom,omitempty" schema:"minimum=0,maximum=1"`
}

CameraDeadZoneDoc defines the 2D camera drag-margin dead zone as non-negative fractions of the view size from the view center in each direction. Left+Right and Top+Bottom may each be at most 1.

func (*CameraDeadZoneDoc) Clone

Clone returns a deep copy of d, or nil when d is nil.

type CameraDoc

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"`
	// Follow optionally configures a tilemap.CameraRig for target tracking, drag margins, look-ahead, separate smoothing and smoothed limits.
	Follow *CameraFollowDoc `yaml:"follow,omitempty"`
	// Shake optionally configures trauma-driven camera shake (tilemap.ShakeProfile).
	Shake *CameraShakeDoc `yaml:"shake,omitempty"`
}

CameraDoc describes a 2D camera transform and optional follow rig and trauma shake settings for world-space layers.

func (*CameraDoc) BuildCamera

func (c *CameraDoc) BuildCamera(viewWidth, viewHeight float32) *tilemap.Camera

BuildCamera constructs a tilemap.Camera initialized from c for a viewport of viewWidth by viewHeight points. When c is nil, it returns a default camera with Zoom 1 at the origin.

func (*CameraDoc) BuildRig

func (c *CameraDoc) BuildRig(cam *tilemap.Camera) *tilemap.CameraRig

BuildRig constructs a tilemap.CameraRig bound to cam using c.Follow when set. When cam is nil, it creates one with c.BuildCamera(0, 0).

func (*CameraDoc) Clone

func (c *CameraDoc) Clone() *CameraDoc

Clone returns a deep copy of c, or nil when c is nil.

func (*CameraDoc) EffectiveZoom

func (c *CameraDoc) EffectiveZoom() float32

EffectiveZoom returns the camera's zoom factor, defaulting to 1 when Zoom is nil.

type CameraFollowDoc

type CameraFollowDoc struct {
	// OffsetX shifts the view center horizontally relative to the target in world points.
	OffsetX float32 `yaml:"offsetX,omitempty"`
	// OffsetY shifts the view center vertically relative to the target in world points.
	OffsetY float32 `yaml:"offsetY,omitempty"`
	// DeadZone optionally defines the drag-margin dead zone as fractions of the view size from the view center; nil disables the dead zone.
	DeadZone *CameraDeadZoneDoc `yaml:"deadZone,omitempty"`
	// LookAheadX scales horizontal target velocity into world-point lead ahead of the target.
	LookAheadX float32 `yaml:"lookAheadX,omitempty"`
	// LookAheadY scales vertical target velocity into world-point lead ahead of the target.
	LookAheadY float32 `yaml:"lookAheadY,omitempty"`
	// MaxLookAhead caps the Euclidean length of the look-ahead vector in world points; 0 leaves it uncapped. Must be non-negative.
	MaxLookAhead float32 `yaml:"maxLookAhead,omitempty" schema:"minimum=0"`
	// PositionSpeed is the exponential smoothing rate per second for camera position and look-ahead; 0 snaps immediately. Must be non-negative.
	PositionSpeed float32 `yaml:"positionSpeed,omitempty" schema:"minimum=0"`
	// RotationSpeed is the exponential smoothing rate per second for camera rotation when FollowRotation is true; 0 snaps immediately. Must be non-negative.
	RotationSpeed float32 `yaml:"rotationSpeed,omitempty" schema:"minimum=0"`
	// ZoomSpeed is the exponential smoothing rate per second for zoom changes set via CameraRig.SetZoom; 0 snaps immediately. Must be non-negative.
	ZoomSpeed float32 `yaml:"zoomSpeed,omitempty" schema:"minimum=0"`
	// LimitSpeed is the exponential smoothing rate per second for easing into changed camera Bounds; 0 hard-clamps immediately. Must be non-negative.
	LimitSpeed float32 `yaml:"limitSpeed,omitempty" schema:"minimum=0"`
	// FollowRotation rotates the camera toward the target's rotation along the shortest arc when true; false ignores target rotation.
	FollowRotation bool `yaml:"followRotation,omitempty"`
}

CameraFollowDoc configures a 2D camera follow rig (tilemap.CameraRig) in a scene file.

func (*CameraFollowDoc) Clone

func (f *CameraFollowDoc) Clone() *CameraFollowDoc

Clone returns a deep copy of f, or nil when f is nil.

type CameraShakeDoc

type CameraShakeDoc struct {
	// MaxOffset is the maximum world-point translation displacement at full trauma (1); 0 disables translation unless MaxRoll is also 0. Must be non-negative.
	MaxOffset float32 `yaml:"maxOffset,omitempty" schema:"minimum=0"`
	// MaxRoll is the maximum clockwise rotational displacement in radians at full trauma (1); 0 disables roll unless MaxOffset is also 0. Must be non-negative.
	MaxRoll float32 `yaml:"maxRoll,omitempty" schema:"minimum=0"`
	// Frequency is the smooth noise sampling frequency in cycles per second; 0 uses the default (12). Must be non-negative.
	Frequency float32 `yaml:"frequency,omitempty" schema:"minimum=0"`
	// Decay is the linear trauma decay rate per second; 0 uses the default (1.5). Must be non-negative.
	Decay float32 `yaml:"decay,omitempty" schema:"minimum=0"`
	// Seed seeds deterministic camera shake noise; 0 uses the fixed default seed.
	Seed uint64 `yaml:"seed,omitempty"`
}

CameraShakeDoc configures trauma-driven 2D camera shake (tilemap.ShakeProfile and tilemap.Camera.ShakeSeed) in a scene file.

func (*CameraShakeDoc) Clone

func (s *CameraShakeDoc) Clone() *CameraShakeDoc

Clone returns a deep copy of s, or nil when s is nil.

type CarControllerSnapshot

type CarControllerSnapshot struct {
	Enabled   bool    `yaml:"enabled" json:"enabled"`
	VelocityX float64 `yaml:"velocityX,omitempty" json:"velocityX,omitempty"`
	VelocityY float64 `yaml:"velocityY,omitempty" json:"velocityY,omitempty"`
	Heading   float64 `yaml:"heading,omitempty" json:"heading,omitempty"`
}

CarControllerSnapshot is the serializable state of a "car" controller.

type CarRuntimeState

type CarRuntimeState struct {
	Enabled   bool
	IsMoving  bool
	VelocityX float32
	VelocityY float32
	Speed     float32
	Heading   float64
}

CarRuntimeState is the readable runtime state of an object's "car" controller.

type CastShadowMode

type CastShadowMode string

CastShadowMode selects whether a 3D object casts shadows and draws in the main pass (ObjectDoc.CastShadow).

const (
	// CastShadowOn draws the object in both the main pass and shadow passes (the empty default).
	CastShadowOn CastShadowMode = "on"
	// CastShadowOff draws the object in the main pass and excludes it from shadow passes.
	CastShadowOff CastShadowMode = "off"
	// CastShadowDoubleSided draws the object in the main pass and renders both faces in shadow passes.
	CastShadowDoubleSided CastShadowMode = "doubleSided"
	// CastShadowOnly skips the object in the main pass and renders it only in shadow passes.
	CastShadowOnly CastShadowMode = "only"
)

type CellAssignment

type CellAssignment struct {
	AlwaysLoaded bool
	Grid         string
	Coord        CellCoord
	Promoted     bool
}

CellAssignment records where PartitionScene placed an object (and its descendants).

func (CellAssignment) Key

func (a CellAssignment) Key() CellKey

Key returns the CellKey for a non-AlwaysLoaded assignment.

type CellCoord

type CellCoord struct{ X, Y int }

CellCoord is the integer coordinate of a partition cell; cell (0, 0) covers [0, CellSize) on both axes.

type CellKey

type CellKey struct {
	Grid  string
	Coord CellCoord
}

CellKey uniquely identifies a cell across all grids of a partitioned scene. Grid is "" for the primary (default) grid, or the PartitionGrid.Name for an extra grid.

type CellObject

type CellObject struct {
	ID            string
	X, Y          float64
	Width, Height float64
	AlwaysLoaded  bool
}

CellObject is the bounds of an object to assign to cells: a rectangle of Width by Height centered on (X, Y). An AlwaysLoaded object belongs to no cell and stays loaded whatever the sources.

type Circle

type Circle struct {
	// X is the horizontal center coordinate in object-local space.
	X float64 `yaml:"x" json:"x"`
	// Y is the vertical center coordinate in object-local space.
	Y float64 `yaml:"y" json:"y"`
	// Radius is the circle's radius in object-local space (non-negative).
	Radius float64 `yaml:"radius" json:"radius" schema:"minimum=0"`
}

Circle is a 2D circle in an object's local coordinate space, used by FieldCircle component fields.

func ParseCircle

func ParseCircle(v any) (Circle, error)

ParseCircle converts a component field value (Circle or decoded YAML map) to a validated Circle.

func (Circle) MarshalYAML

func (c Circle) MarshalYAML() (any, error)

MarshalYAML encodes Circle with deterministic alphabetical key order matching YAML map decoding ("radius", "x", "y").

type ColorAdjustDoc

type ColorAdjustDoc struct {
	// Brightness scales the image's brightness; must be finite and non-negative. 0 defaults to 1.
	Brightness float32 `yaml:"brightness,omitempty" schema:"minimum=0"`
	// Contrast scales the image's contrast; must be finite and non-negative. 0 defaults to 1.
	Contrast float32 `yaml:"contrast,omitempty" schema:"minimum=0"`
	// Saturation scales the image's color saturation; must be finite and non-negative. 0 defaults to 1.
	Saturation float32 `yaml:"saturation,omitempty" schema:"minimum=0"`
	// LUT is the slash-separated path from the project root to a color lookup table (.cube text file or 2D horizontal strip image); empty applies none.
	LUT string `yaml:"lut,omitempty"`
	// LUTStrength blends between the adjusted color (0) and the LUT output (1) in [0, 1]; nil defaults to 1 when LUT is set.
	LUTStrength *float32 `yaml:"lutStrength,omitempty" schema:"minimum=0,maximum=1"`
}

ColorAdjustDoc configures post-tone-map brightness, contrast, saturation and an optional LUT path (EnvironmentDoc.Adjustments).

func (*ColorAdjustDoc) Clone

func (c *ColorAdjustDoc) Clone() *ColorAdjustDoc

Clone returns a deep copy of c, or nil when c is nil.

func (*ColorAdjustDoc) EffectiveBrightness

func (c *ColorAdjustDoc) EffectiveBrightness() float32

EffectiveBrightness returns c.Brightness, defaulting to 1 when zero or nil.

func (*ColorAdjustDoc) EffectiveContrast

func (c *ColorAdjustDoc) EffectiveContrast() float32

EffectiveContrast returns c.Contrast, defaulting to 1 when zero or nil.

func (*ColorAdjustDoc) EffectiveLUTStrength

func (c *ColorAdjustDoc) EffectiveLUTStrength() float32

EffectiveLUTStrength returns c.LUTStrength when set, 1 when LUT is non-empty and LUTStrength is nil, and 0 otherwise.

func (*ColorAdjustDoc) EffectiveSaturation

func (c *ColorAdjustDoc) EffectiveSaturation() float32

EffectiveSaturation returns c.Saturation, defaulting to 1 when zero or nil.

type ComponentError

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 (*ComponentError) Error

func (e *ComponentError) Error() string

Error formats the error as "file:line:col: sceneformat: object "id" component "name" field "f": msg", leaving out the parts that are unknown.

type ComponentRegistry

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

func AnimatorComponentRegistry() *ComponentRegistry

AnimatorComponentRegistry returns a new ComponentRegistry containing the built-in "animator" component.

func BehaviorComponentRegistry

func BehaviorComponentRegistry() *ComponentRegistry

BehaviorComponentRegistry returns a new ComponentRegistry pre-populated with all ten built-in 2D motion behavior components.

func InputBehaviorComponentRegistry

func InputBehaviorComponentRegistry() *ComponentRegistry

InputBehaviorComponentRegistry returns a new ComponentRegistry pre-populated with all eight built-in controller components.

func Lights2DComponentRegistry

func Lights2DComponentRegistry() *ComponentRegistry

Lights2DComponentRegistry returns a new ComponentRegistry pre-populated with the built-in 2D lighting components.

func MapEventComponentRegistry

func MapEventComponentRegistry() *ComponentRegistry

MapEventComponentRegistry returns a new ComponentRegistry pre-populated with the built-in "map_event" component.

func Mesh2DComponentRegistry

func Mesh2DComponentRegistry() *ComponentRegistry

Mesh2DComponentRegistry returns a new ComponentRegistry pre-populated with "line2d" and "polygon2d".

func NavRegion2DComponentRegistry() *ComponentRegistry

NavRegion2DComponentRegistry returns a new ComponentRegistry pre-populated with the built-in "navregion2d" component.

func NewComponentRegistry

func NewComponentRegistry() *ComponentRegistry

NewComponentRegistry returns an empty registry.

func OnScreenComponentRegistry

func OnScreenComponentRegistry() *ComponentRegistry

OnScreenComponentRegistry returns a new ComponentRegistry pre-populated with the built-in "on_screen" component.

func Path2DComponentRegistry

func Path2DComponentRegistry() *ComponentRegistry

Path2DComponentRegistry returns a new ComponentRegistry pre-populated with "path2d" and "path_follow2d".

func PhysicsComponentRegistry

func PhysicsComponentRegistry() *ComponentRegistry

PhysicsComponentRegistry returns a new ComponentRegistry pre-populated with all built-in 2D and 3D physics components.

func SkeletalComponentRegistry

func SkeletalComponentRegistry() *ComponentRegistry

SkeletalComponentRegistry returns a new ComponentRegistry pre-populated with the built-in "skeletal" component.

func SmartObjectComponentRegistry

func SmartObjectComponentRegistry() *ComponentRegistry

SmartObjectComponentRegistry returns a new ComponentRegistry pre-populated with the built-in "smart_object" component.

func SoundComponentRegistry

func SoundComponentRegistry() *ComponentRegistry

SoundComponentRegistry returns a new ComponentRegistry pre-populated with the built-in "sound" component.

func TimerComponentRegistry

func TimerComponentRegistry() *ComponentRegistry

TimerComponentRegistry returns a new ComponentRegistry containing the built-in "timer" component.

func VCamComponentRegistry

func VCamComponentRegistry() *ComponentRegistry

VCamComponentRegistry returns a new ComponentRegistry pre-populated with "vcam" and "vcam_trigger".

func (*ComponentRegistry) CheckComponent

func (r *ComponentRegistry) CheckComponent(component string, value any) error

CheckComponent 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 (*ComponentRegistry) CheckField

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 (*ComponentRegistry) JSONSchema

func (r *ComponentRegistry) JSONSchema() *jsonschema.Schema

JSONSchema returns the schema of a scene's components map for r's types, in Names order. When r is non-nil, unregistered component names are refused; when r is nil, any component mapping is accepted.

Example

JSONSchema returns a draft-07 JSON Schema for a scene object's components map in ascending component name order.

package main

import (
	"fmt"

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

func main() {
	reg := sceneformat.NewComponentRegistry()
	reg.MustRegister(sceneformat.ComponentType{
		Name:   "hitbox",
		Fields: []sceneformat.Field{{Name: "bounds", Kind: sceneformat.FieldRect}},
	})
	s := reg.JSONSchema()
	fmt.Println(s.Validate(map[string]any{
		"hitbox": map[string]any{"bounds": map[string]any{"x": 0, "y": 0, "width": 16, "height": 16}},
	}))
	fmt.Println(s.Validate(map[string]any{
		"hitbox": map[string]any{"bounds": "not-a-rect"},
	}) != nil)
}
Output:
<nil>
true

func (*ComponentRegistry) Lookup

func (r *ComponentRegistry) Lookup(name string) (ComponentType, bool)

Lookup returns a copy of the component type named name and whether it is registered.

func (*ComponentRegistry) Merge

func (r *ComponentRegistry) Merge(other *ComponentRegistry) error

Merge registers every type of other into r, refusing a name r already has. Merge is all-or-nothing: when any name collides, r is left unchanged and the error names the colliding type and describes both the existing and incoming definitions. Names are checked in ascending order so the error is deterministic, and r keeps its own copies of other's types. Merging a nil or empty other is a no-op.

Example

Merge combines two component registries in an all-or-nothing step, refusing any colliding component name.

package main

import (
	"fmt"

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

func main() {
	game := sceneformat.NewComponentRegistry()
	game.MustRegister(sceneformat.ComponentType{
		Name:   "health",
		Fields: []sceneformat.Field{{Name: "hp", Kind: sceneformat.FieldInt, Default: 10}},
	})
	plugin := sceneformat.NewComponentRegistry()
	plugin.MustRegister(sceneformat.ComponentType{
		Name:   "hitbox",
		Fields: []sceneformat.Field{{Name: "bounds", Kind: sceneformat.FieldRect}},
	})

	fmt.Println(game.Merge(plugin))
	fmt.Println(game.Names())
}
Output:
<nil>
[health hitbox]

func (*ComponentRegistry) MustRegister

func (r *ComponentRegistry) MustRegister(t ComponentType)

MustRegister is Register for package-level setup; it panics when Register returns an error.

func (*ComponentRegistry) Names

func (r *ComponentRegistry) Names() []string

Names returns the registered type names in ascending order.

func (*ComponentRegistry) Register

func (r *ComponentRegistry) Register(t ComponentType) error

Register 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, an Editor hint containing spaces, control characters, or a leading ':', 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 (*ComponentRegistry) Resolve

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, decoded to its runtime Go type (ObjectRef for FieldObject, string for FieldColor, FieldScene and FieldResource, and the corresponding Go type for the other kinds). Use it at runtime to read a component without repeating its defaults; the scene document itself keeps only the fields its author wrote.

func (*ComponentRegistry) Types

func (r *ComponentRegistry) Types() []ComponentType

Types returns copies of the registered types ordered by name.

type ComponentType

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
	// Spawn attaches the component's runtime state to e, the entity spawned for an object that sets this component. fields are the object's values with defaults filled in (ComponentRegistry.Resolve). A registry used only to check files may leave it nil.
	Spawn func(w *entities.World, e entities.Entity, fields map[string]any) error
}

ComponentType is a registered component: the name it is keyed by under an object's components and its fields in declaration order.

func AnimatorComponent

func AnimatorComponent() ComponentType

AnimatorComponent 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 BehaviorComponents

func BehaviorComponents() []ComponentType

BehaviorComponents returns all ten built-in 2D motion behavior ComponentTypes in canonical order.

func Body2DComponent

func Body2DComponent() ComponentType

Body2DComponent returns the ComponentType schema for the built-in "body2d" component.

func Body3DComponent

func Body3DComponent() ComponentType

Body3DComponent returns the ComponentType schema for the built-in "body3d" component.

func BoundComponent

func BoundComponent() ComponentType

BoundComponent returns the ComponentType schema for the built-in "bound" motion behavior.

func BuiltinGameHandlerGroups

func BuiltinGameHandlerGroups() []ComponentType

BuiltinGameHandlerGroups returns the built-in handler groups exposed on the reserved "game" target: vars (set, add), sound (play), scene (change), and save (slot).

func BulletComponent

func BulletComponent() ComponentType

BulletComponent returns the ComponentType schema for the built-in "bullet" motion behavior.

func CarComponent

func CarComponent() ComponentType

CarComponent returns the ComponentType schema for the built-in "car" controller component.

func Collider2DComponent

func Collider2DComponent() ComponentType

Collider2DComponent returns the ComponentType schema for the built-in "collider2d" component.

func Collider3DComponent

func Collider3DComponent() ComponentType

Collider3DComponent returns the ComponentType schema for the built-in "collider3d" component.

func CoverPointComponent

func CoverPointComponent() ComponentType

CoverPointComponent 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 DestroyOutsideComponent

func DestroyOutsideComponent() ComponentType

DestroyOutsideComponent returns the ComponentType schema for the built-in "destroy_outside" motion behavior.

func DragDropComponent

func DragDropComponent() ComponentType

DragDropComponent returns the ComponentType schema for the built-in "drag_drop" controller component.

func EightDirectionComponent

func EightDirectionComponent() ComponentType

EightDirectionComponent returns the ComponentType schema for the built-in "eight_direction" controller component.

func FadeComponent

func FadeComponent() ComponentType

FadeComponent returns the ComponentType schema for the built-in "fade" motion behavior.

func FlashComponent

func FlashComponent() ComponentType

FlashComponent returns the ComponentType schema for the built-in "flash" motion behavior.

func InputBehaviorComponent

func InputBehaviorComponent(name string) (ComponentType, bool)

InputBehaviorComponent returns the schema (fields, events, and handlers) for one of the eight built-in input-driven controller components.

func InputBehaviorComponents

func InputBehaviorComponents() []ComponentType

InputBehaviorComponents returns all eight built-in input-driven controller ComponentTypes in canonical order.

func Light2DComponent

func Light2DComponent() ComponentType

Light2DComponent returns the ComponentType schema for the built-in "light2d" component.

func Line2DComponent

func Line2DComponent() ComponentType

Line2DComponent returns the ComponentType schema for the built-in "line2d" component.

func LineOfSightComponent

func LineOfSightComponent() ComponentType

LineOfSightComponent returns the ComponentType schema for the built-in "line_of_sight" controller component.

func MapEventComponent

func MapEventComponent() ComponentType

MapEventComponent returns the ComponentType schema for the built-in "map_event" component.

func MoveToComponent

func MoveToComponent() ComponentType

MoveToComponent returns the ComponentType schema for the built-in "move_to" motion behavior.

func NavLinkComponent() ComponentType

NavLinkComponent returns the ComponentType schema for authoring off-mesh navigation links in scene YAML files (for both 2D pathfind.NavMesh and 3D pathfind3d.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() ComponentType

NavRegion2DComponent returns the ComponentType schema for the built-in "navregion2d" component.

func Occluder2DComponent

func Occluder2DComponent() ComponentType

Occluder2DComponent returns the ComponentType schema for the built-in "occluder2d" component.

func OnScreenComponent

func OnScreenComponent() ComponentType

OnScreenComponent returns the ComponentType schema for the built-in "on_screen" component, which reports through its entered and exited events when the object's rectangle enters or leaves every camera view, and pauses the parts its pause list names (the object's particle emitter or skeletal rig) while it is off-screen.

The rectangle is in the object's local space and is transformed by its composed world transform, so moving or rotating the object (or a parent of it) moves the watched rectangle; a rotated rectangle is covered by the axis-aligned rectangle holding its corners.

Register it on a ComponentRegistry via RegisterOnScreen so ParseWith validates on_screen fields and scene connections may wire the entered and exited events.

func OrbitComponent

func OrbitComponent() ComponentType

OrbitComponent returns the ComponentType schema for the built-in "orbit" motion behavior.

func Path2DComponent

func Path2DComponent() ComponentType

Path2DComponent returns the ComponentType schema for the built-in "path2d" component: a multi-segment cubic Bézier curve in the object's local space with per-point relative in/out control handles, optional closed loop, and arc-length bake interval.

func PathAgentComponent

func PathAgentComponent() ComponentType

PathAgentComponent returns the ComponentType schema for the built-in "path_agent" controller component.

func PathFollow2DComponent

func PathFollow2DComponent() ComponentType

PathFollow2DComponent returns the ComponentType schema for the built-in "path_follow2d" component: placed on a child of a "path2d" object, BuiltScene.Update advances the child along the parent path's arc length with configurable speed, looping, tangent rotation, and lateral/longitudinal offsets.

func PlatformComponent

func PlatformComponent() ComponentType

PlatformComponent returns the ComponentType schema for the built-in "platform" controller component.

func Polygon2DComponent

func Polygon2DComponent() ComponentType

Polygon2DComponent returns the ComponentType schema for the built-in "polygon2d" component.

func RotateComponent

func RotateComponent() ComponentType

RotateComponent returns the ComponentType schema for the built-in "rotate" motion behavior.

func SineComponent

func SineComponent() ComponentType

SineComponent returns the ComponentType schema for the built-in "sine" motion behavior.

func SkeletalComponent

func SkeletalComponent() ComponentType

SkeletalComponent 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 SmartObjectComponent

func SmartObjectComponent() ComponentType

SmartObjectComponent returns the ComponentType schema for the built-in "smart_object" component.

func SoundComponent

func SoundComponent() ComponentType

SoundComponent returns the ComponentType schema for the built-in "sound" component, which places a positional 2D or 3D sound emitter referencing a .sound.yaml resource or audio clip on an object.

Register it on a ComponentRegistry via RegisterSoundComponent so ParseWith validates sound fields and rejects unknown keys, wrong types, or out-of-range values.

func TileMovementComponent

func TileMovementComponent() ComponentType

TileMovementComponent returns the ComponentType schema for the built-in "tile_movement" controller component.

func TimerComponent

func TimerComponent() ComponentType

TimerComponent returns the ComponentType schema for the built-in "timer" component: an object with a timer component emits timeout on the game clock after seconds of it, once or repeating, and a scene's connections wire that to any handler with no Go code. Signals.Update advances the timers of a connected scene, and the start and stop handlers restart and halt them.

func Trigger2DComponent

func Trigger2DComponent() ComponentType

Trigger2DComponent returns the ComponentType schema for the built-in "trigger2d" component.

func Trigger3DComponent

func Trigger3DComponent() ComponentType

Trigger3DComponent returns the ComponentType schema for the built-in "trigger3d" component.

func TurretComponent

func TurretComponent() ComponentType

TurretComponent returns the ComponentType schema for the built-in "turret" controller component.

func VCamComponent

func VCamComponent() ComponentType

VCamComponent returns the ComponentType schema for the built-in "vcam" component.

func VCamTriggerComponent

func VCamTriggerComponent() ComponentType

VCamTriggerComponent returns the ComponentType schema for the built-in "vcam_trigger" component.

func WrapComponent

func WrapComponent() ComponentType

WrapComponent returns the ComponentType schema for the built-in "wrap" motion behavior.

func (*ComponentType) Event

func (t *ComponentType) Event(name string) (Event, bool)

Event returns the event named name and whether the type declares it.

func (*ComponentType) Field

func (t *ComponentType) Field(name string) (Field, bool)

Field returns the field named name and whether the type has it.

func (*ComponentType) FieldNames

func (t *ComponentType) FieldNames() []string

FieldNames returns the type's field names in declaration order.

func (*ComponentType) Handler

func (t *ComponentType) Handler(name string) (Handler, bool)

Handler returns the handler named name and whether the type declares it.

type ConflictDoc

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

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

type ConflictKind string

ConflictKind 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 ConnectOptions

type ConnectOptions struct {
	// Vars supplies the live flow.Vars store for reading/writing game variables and for load-time
	// type checking of When conditions, expression-valued Args, and vars.set/vars.add.
	Vars *flow.Vars
	// VarsDoc optionally supplies variable declarations for static checking when no live flow.Vars
	// exists yet (such as in ParseWith or assetcheck). Ignored when Vars != nil.
	VarsDoc *flow.VarsDoc
	// Funcs supplies custom functions callable from When conditions and expression-valued Args.
	Funcs map[string]expr.Func
	// Game supplies runtime hooks for the built-in "game" target and scene.* handlers.
	Game GameActions
}

ConnectOptions configures variable/function type checking and built-in game action hooks for ConnectWith and ValidateConnectionsWith.

type ConnectionDoc

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", or a custom scene event "scene.<name>" emitted by scene.emit.
	Event string `yaml:"event" schema:"required,minLength=1"`
	// To is the ID of the object whose handler runs, or "game" for the built-in game target (vars.set, vars.add, sound.play, scene.change, save.slot).
	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", a built-in scene handler on any object (scene.destroy, scene.spawn, scene.set, scene.show, scene.hide, scene.emit), or a built-in game handler when To is "game".
	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, a string, or a pkg/expr expression string (such as "score * 2") evaluated against flow variables and event context.
	Args map[string]any `yaml:"args,omitempty"`
	// Once disconnects the connection after the first time the event fires.
	Once bool `yaml:"once,omitempty"`
	// When is an optional pkg/expr boolean condition the handler runs only while it holds, such as "score >= 10" or "has_item(\"key\")", evaluated against Signals.SetRuleContext / flow.Vars and event context. Empty means always. A once connection whose condition is false stays connected. Validate refuses an expression it cannot parse.
	When string `yaml:"when,omitempty"`
}

ConnectionDoc connects an event that one object emits to a handler of another object, of the same object, or of the built-in "game" target (SceneDoc.Connections). Signals.Emit calls the handler each time the object emits the event.

type ConnectionError

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", "args" or "when".
	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 (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error 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 ControllerSnapshot

type ControllerSnapshot struct {
	Version            int                        `yaml:"version" json:"version"`
	PrevPointerPressed bool                       `yaml:"prevPointerPressed,omitempty" json:"prevPointerPressed,omitempty"`
	Objects            []ObjectControllerSnapshot `yaml:"objects,omitempty" json:"objects,omitempty"`
	MapEvents          []MapEventObjectSnapshot   `yaml:"mapEvents,omitempty" json:"mapEvents,omitempty"`
}

ControllerSnapshot captures the deterministic runtime state of all built-in input-driven controller components on a BuiltScene as a plain-text YAML/JSON-serializable value (never encoding/gob).

type CrossCellConnection

type CrossCellConnection struct {
	Index      int
	Connection ConnectionDoc
	From       CellAssignment
	To         CellAssignment
}

CrossCellConnection reports a connection whose target lives in a different cell and is not AlwaysLoaded.

type DOFDoc

type DOFDoc struct {
	// FocusDistance is the distance from the camera that is in focus; must be finite and non-negative.
	FocusDistance float32 `yaml:"focusDistance,omitempty" schema:"minimum=0"`
	// FocusRange is the depth around FocusDistance that stays sharp; must be finite and non-negative.
	FocusRange float32 `yaml:"focusRange,omitempty" schema:"minimum=0"`
	// MaxBlur is the largest blur radius out of focus; must be finite and non-negative.
	MaxBlur float32 `yaml:"maxBlur,omitempty" schema:"minimum=0"`
}

DOFDoc configures practical depth of field (Camera3DDoc.DOF). The scene format records it for the renderer, which does not read it yet.

type DataLayerDoc

type DataLayerDoc struct {
	// Name uniquely identifies the data layer within the scene.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// State is the layer's initial runtime state: "unloaded", "loaded", or "active". Empty defaults to "active".
	State DataLayerState `yaml:"state,omitempty" schema:"enum=unloaded|loaded|active"`
	// Parent optionally names another data layer in this scene; the layer's effective state is the lower of its own state and its parent's effective state.
	Parent string `yaml:"parent,omitempty"`
	// EditorOnly marks objects belonging to this layer as editor-only; PartitionScene omits them from build output.
	EditorOnly bool `yaml:"editorOnly,omitempty"`
}

DataLayerDoc declares a named data layer in SceneDoc.DataLayers that groups objects to load, pause, and activate together at run time (for example night props, a quest stage, or a destroyed town), or marks editor-only layers that are excluded from partitioned build output.

func (*DataLayerDoc) EffectiveState

func (d *DataLayerDoc) EffectiveState() DataLayerState

EffectiveState returns State, defaulting to DataLayerActive when empty.

type DataLayerState

type DataLayerState string

DataLayerState is the runtime activation state of a scene data layer.

const (
	// DataLayerUnloaded means objects belonging to the layer are not instanced in the running scene.
	DataLayerUnloaded DataLayerState = "unloaded"
	// DataLayerLoaded means objects belonging to the layer are instanced in memory but neither simulated nor drawn.
	DataLayerLoaded DataLayerState = "loaded"
	// DataLayerActive means objects belonging to the layer are instanced, simulated, and drawn.
	DataLayerActive DataLayerState = "active"
)

type DecalDoc

type DecalDoc struct {
	// Texture is the slash-separated path from the project root to the projected color texture. Required.
	Texture string `yaml:"texture" schema:"required,minLength=1"`
	// Normal is the slash-separated path from the project root to an optional normal map projected with Texture.
	Normal string `yaml:"normal,omitempty"`
	// Size is the projection box's width, height and depth in local units; each must be finite and non-negative.
	Size [3]float32 `yaml:"size,omitempty"`
	// Near and Far bound the projection along its depth; both must be finite and non-negative, and Near no greater than a non-zero Far.
	Near float32 `yaml:"near,omitempty" schema:"minimum=0"`
	// Far is the far end of the projection; 0 leaves it to the renderer.
	Far float32 `yaml:"far,omitempty" schema:"minimum=0"`
	// Layers is the bit mask of render layers the decal projects onto; 0 leaves it to the renderer.
	Layers int `yaml:"layers,omitempty" schema:"minimum=0"`
}

DecalDoc places a projected texture on nearby geometry (ObjectDoc.Decal). The scene format records it; Build does not create a decal from it yet.

type Dependency

type Dependency struct {
	// Kind identifies the dependency kind: "atlas", "image", "tilemap", "tileset", "material", "particles", "scene", "model", "sound", or "skeleton".
	Kind string `json:"kind"`
	// Path is the slash-separated path relative to the project root, or for an atlas, the atlas name written in the scene.
	Path string `json:"path"`
}

Dependency is one resource a scene depends on, directly or through scenes it instances or inherits.

func Dependencies

func Dependencies(doc *SceneDoc, scenes SceneResolver) ([]Dependency, error)

Dependencies validates and resolves doc (loading any instanced or inherited scenes through scenes), collects every resource the resolved scene depends on, and returns them deduplicated and sorted by Kind then Path.

When scenes also implements FileResolver (such as FSAssets or project.Resolver), Dependencies also reads referenced YAML tilesets (*.tileset.yaml), Tiled maps (.tmj, .tmx), LDtk projects (.ldtk), and shared material files (*.material.yaml) to report the tilesets, atlases, and images they use.

type DestroyOutsideEvent

type DestroyOutsideEvent struct {
	ObjectID string
	X, Y     float32
}

DestroyOutsideEvent is the payload emitted with an object's "destroy_outside.destroyed" event.

type DragDropControllerSnapshot

type DragDropControllerSnapshot struct {
	Enabled     bool    `yaml:"enabled" json:"enabled"`
	Dragging    bool    `yaml:"dragging,omitempty" json:"dragging,omitempty"`
	GrabOffsetX float32 `yaml:"grabOffsetX,omitempty" json:"grabOffsetX,omitempty"`
	GrabOffsetY float32 `yaml:"grabOffsetY,omitempty" json:"grabOffsetY,omitempty"`
}

DragDropControllerSnapshot is the serializable state of a "drag_drop" controller.

type DragDropEvent

type DragDropEvent struct {
	ObjectID string
	X, Y     float32
}

DragDropEvent is emitted with "drag_drop.picked" and "drag_drop.dropped".

type DragDropRuntimeState

type DragDropRuntimeState struct {
	Enabled     bool
	Dragging    bool
	GrabOffsetX float32
	GrabOffsetY float32
}

DragDropRuntimeState is the readable runtime state of an object's "drag_drop" controller.

type EightDirectionConfig

type EightDirectionConfig struct {
	MaxSpeed     float32
	Acceleration float32
	Deceleration float32
	Directions   int
}

EightDirectionConfig configures deterministic top-down movement for an eight_direction scene component.

func (EightDirectionConfig) Validate

func (c EightDirectionConfig) Validate() error

Validate checks the numeric limits shared by the eight_direction component schema and runtime stepper.

type EightDirectionControllerSnapshot

type EightDirectionControllerSnapshot struct {
	Enabled    bool    `yaml:"enabled" json:"enabled"`
	VelocityX  float32 `yaml:"velocityX,omitempty" json:"velocityX,omitempty"`
	VelocityY  float32 `yaml:"velocityY,omitempty" json:"velocityY,omitempty"`
	DirectionX float32 `yaml:"directionX,omitempty" json:"directionX,omitempty"`
	DirectionY float32 `yaml:"directionY,omitempty" json:"directionY,omitempty"`
	Moving     bool    `yaml:"moving,omitempty" json:"moving,omitempty"`
	Angle      float32 `yaml:"angle,omitempty" json:"angle,omitempty"`
}

EightDirectionControllerSnapshot is the serializable state of an "eight_direction" controller.

type EightDirectionResult

type EightDirectionResult struct {
	VelocityX  float32
	VelocityY  float32
	DirectionX float32
	DirectionY float32
	Moving     bool
	Angle      float32
}

EightDirectionResult is the resolved velocity and direction for a fixed step.

func StepEightDirection

func StepEightDirection(state *EightDirectionState, axisX, axisY float32, dt time.Duration, cfg EightDirectionConfig) (EightDirectionResult, error)

StepEightDirection advances one mover using an input axis in [-1, 1]. Input is normalized and quantized to four or eight directions; the velocity then moves in a straight line toward the quantized direction at MaxSpeed by at most Acceleration*dt, or toward rest by at most Deceleration*dt when the input is released, so replaying the same inputs with the same fixed step duration gives the same velocities.

type EightDirectionRuntimeState

type EightDirectionRuntimeState struct {
	Enabled    bool
	IsMoving   bool
	VelocityX  float32
	VelocityY  float32
	DirectionX float32
	DirectionY float32
	Angle      float32
}

EightDirectionRuntimeState is the readable runtime state of an object's "eight_direction" controller.

type EightDirectionState

type EightDirectionState struct {
	VelocityX float32
	VelocityY float32
}

EightDirectionState is the persistent velocity state of one eight_direction mover.

type EnvironmentDoc

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"`
	// Adjustments optionally applies brightness, contrast, saturation and a color lookup table; nil leaves color unadjusted.
	Adjustments *ColorAdjustDoc `yaml:"adjustments,omitempty"`
	// AutoExposure optionally adapts exposure to the scene's brightness; nil keeps Exposure fixed.
	AutoExposure *AutoExposureDoc `yaml:"autoExposure,omitempty"`
	// SSR optionally enables screen-space reflections; nil leaves them disabled.
	SSR *SSRDoc `yaml:"ssr,omitempty"`
	// Glow optionally enables bloom on bright pixels; nil leaves it disabled.
	Glow *GlowDoc `yaml:"glow,omitempty"`
	// SSAO optionally enables screen-space ambient occlusion; nil leaves it disabled.
	SSAO *SSAODoc `yaml:"ssao,omitempty"`
	// Antialiasing selects "none", "fxaa", "msaa2x" or "msaa4x"; empty leaves the renderer default.
	Antialiasing string `yaml:"antialiasing,omitempty" schema:"enum=none|fxaa|msaa2x|msaa4x"`
}

EnvironmentDoc configures a 3D scene's sky, ambient fill, image-based lighting, fog, tone mapping and exposure (SceneDoc.Environment). Version 4.

func (*EnvironmentDoc) Clone

func (e *EnvironmentDoc) Clone() *EnvironmentDoc

Clone returns a deep copy of e, or nil when e is nil.

func (*EnvironmentDoc) EffectiveAmbientColor

func (e *EnvironmentDoc) EffectiveAmbientColor() string

EffectiveAmbientColor returns e.AmbientColor, defaulting to "#ffffff" when empty.

func (*EnvironmentDoc) EffectiveAmbientIntensity

func (e *EnvironmentDoc) EffectiveAmbientIntensity() float32

EffectiveAmbientIntensity returns e.AmbientIntensity, defaulting to 0.25 when nil.

func (*EnvironmentDoc) EffectiveExposure

func (e *EnvironmentDoc) EffectiveExposure() float32

EffectiveExposure returns e.Exposure, defaulting to 1 when nil.

func (*EnvironmentDoc) EffectiveIBLIntensity

func (e *EnvironmentDoc) EffectiveIBLIntensity() float32

EffectiveIBLIntensity returns e.IBLIntensity when set, 1 when Sky is SkyHDR, and 0 otherwise.

func (*EnvironmentDoc) EffectiveTonemapping

func (e *EnvironmentDoc) EffectiveTonemapping() TonemapMode

EffectiveTonemapping returns e.Tonemapping, defaulting to TonemapNone when empty.

type Event

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

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}).

Example

A layered tilemap places the tiles of a YAML tileset in named tile layers. FSAssets reads the tileset from the project's files, and Build makes the layer a tilemap.Tilemap that answers collision queries.

package main

import (
	"fmt"
	"testing/fstest"

	"github.com/nsgo-dev/game/pkg/sceneformat"
	"github.com/nsgo-dev/game/pkg/tilemap"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	project := fstest.MapFS{
		"tilesets/cave.tileset.yaml": {Data: []byte("version: 1\ntileWidth: 16\ntileHeight: 16\nimage: tiles/cave.png\ncolumns: 2\ntileCount: 2\ntiles:\n  - id: 0\n    solid: true\n")},
		"level.scene.yaml": {Data: []byte(`version: 2
layers:
  - name: ground
    tilemap:
      tileWidth: 16
      tileHeight: 16
      width: 3
      height: 1
      tilesetFile: tilesets/cave.tileset.yaml
      tileLayers:
        - name: floor
          rows:
            - 0 1h 0
`)},
	}
	assets := sceneformat.FSAssets{FS: project}
	doc, err := assets.Scene("level.scene.yaml")
	if err != nil {
		fmt.Println(err)
		return
	}
	built, err := sceneformat.Build(doc, assets)
	if err != nil {
		fmt.Println(err)
		return
	}
	m := built.Layer("ground").Map
	fmt.Println(m.Layers[0].Name, m.FlagsAt(0, 0) == tilemap.TileSolid, m.FlagsAt(1, 0))
	hit, _ := m.Raycast(core.Point{X: 24, Y: 8}, core.Point{X: 60, Y: 8}, tilemap.TileSolid)
	fmt.Println(hit.Col, hit.Point)
}
Output:
floor true 0
2 {32 8}

func (FSAssets) Atlas

func (a FSAssets) Atlas(name string) (*sprite.Atlas, error)

Atlas returns the atlas named name from a.Atlases.

func (FSAssets) ReadFile

func (a FSAssets) ReadFile(path string) ([]byte, error)

ReadFile reads the file at path from a.FS.

func (FSAssets) Scene

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

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 (FSScenes) Scene

func (s FSScenes) Scene(path string) (*SceneDoc, error)

Scene reads the file at path from s.FS and parses it.

type FadeFinishedEvent

type FadeFinishedEvent struct {
	ObjectID  string
	Destroyed bool
}

FadeFinishedEvent is the payload emitted with an object's "fade.finished" event.

type FadeSettings

type FadeSettings struct {
	// Begin is the distance from the camera at which the light starts to fade; must be finite and non-negative.
	Begin float32 `yaml:"begin,omitempty" schema:"minimum=0"`
	// Length is the distance over which the light fades out after Begin; must be finite and non-negative.
	Length float32 `yaml:"length,omitempty" schema:"minimum=0"`
	// Shadow is the distance from the camera at which the light's shadow starts to fade; must be finite and non-negative.
	Shadow float32 `yaml:"shadow,omitempty" schema:"minimum=0"`
}

FadeSettings controls distance-based light and shadow fading (LightDoc.Fade). The scene format records it for the renderer, which does not read it yet.

type Field

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
	// ResourceKind optionally restricts a FieldResource value to a specific resource kind, such as "curve", "material", "sound", "image", or a plugin kind ("<plugin>.<name>"). Empty accepts any resource file. Refused on other kinds.
	ResourceKind string
	// Doc is a one-line description shown by tools such as the editor's inspector.
	Doc string
	// Editor names how tools present the value, as "name" or "name:arg", e.g. "multiline",
	// "color", "angle", "asset:.png,.atlas.yaml", "object", or a plugin drawer such as "health.bar".
	// Empty keeps the kind's default control. It is presentation-only and does not change the stored
	// YAML value or validation; Register refuses spaces, control characters, and an empty name before ':'.
	Editor string
}

Field describes one field of a component type: its YAML key, value kind, default, optional inclusive range and documentation.

type FieldChange

type FieldChange struct {
	// Path names the field as it is written in YAML: nested mapping keys are joined by ".", and an entry of a sequence whose entries are mappings or sequences is named by its 0-based index in brackets, such as "x", "components.health.max" or "connections[0].event".
	Path string `json:"path"`
	// Before is the field's value in the first scene in compact YAML form, or nil when the field is absent. A null value is the string "null".
	Before *string `json:"before,omitempty"`
	// After is the field's value in the second scene in compact YAML form, or nil when the field is absent.
	After *string `json:"after,omitempty"`
}

FieldChange is one field of a scene document or of one of its objects whose value differs between two scenes.

func DiffSceneFields

func DiffSceneFields(before, after *SceneDoc) []FieldChange

DiffSceneFields compares the scene-level fields of two scenes, such as name, size, camera, environment, inheritance, overrides, layerOverrides, tilemaps and connections, and reports the changed ones. Layers and their objects are not included: DiffObjectDetails compares objects, and a layer's own settings are not compared. It returns removed and changed fields in the first scene's document order, followed by added fields in the second scene's.

func DiffYAMLFields

func DiffYAMLFields(before, after []byte) ([]FieldChange, error)

DiffYAMLFields compares the leaf values of two YAML documents by their paths and reports the changed ones, for documents that use the scene format's YAML conventions without being a SceneDoc, such as the prefab files named *.prefab.yaml. Paths name nested mapping keys joined by "." and the entries of sequences of mappings or sequences by their 0-based index in brackets, and values are written in compact YAML form. It returns removed and changed leaves in the first document's order, followed by added leaves in the second document's order. Either document may be nil, which has no leaves. It returns an error when a document is not one valid YAML document.

type FieldError

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 (*FieldError) Error

func (e *FieldError) Error() string

Error returns Err's message.

func (*FieldError) Unwrap

func (e *FieldError) Unwrap() error

Unwrap returns Err.

type FieldKind

type FieldKind uint8

FieldKind 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
	// FieldSmartSlots holds a list of smart-object interaction slot definitions and decodes to a Go []SmartSlotDoc.
	FieldSmartSlots
	// FieldBezierPoints holds a list of 2D cubic Bézier path points [{x, y, inX, inY, outX, outY}, ...] in object-local space and decodes to a Go []PathPoint2D.
	FieldBezierPoints
	// FieldEventPages holds a list of map-event pages (flow.EventPage) and decodes to a Go []flow.EventPage.
	FieldEventPages
	// FieldColor holds a CSS color string parsed with core.ParseColor (such as "#ff4040" or "rgba(255, 64, 64, 1)") and decodes to a Go string; empty is unset.
	FieldColor
	// FieldObject holds an object ID in the same scene (relative IDs inside an instanced scene are rewritten with the instance prefix by ResolveWith and BuiltScene.Instantiate). ComponentRegistry.Resolve decodes it to an ObjectRef, and SpawnEntitiesWith / BuiltScene.Instantiate populate ObjectRef.Entity and ObjectRef.Layer.
	FieldObject
	// FieldScene holds a slash-separated project-relative path to a .scene.yaml (or .scene.yml) file and decodes to a Go string.
	FieldScene
	// FieldResource holds a slash-separated project-relative path to a resource file (optionally restricted by Field.ResourceKind) and decodes to a Go string.
	FieldResource
)

func (FieldKind) IsNumeric

func (k FieldKind) IsNumeric() bool

IsNumeric reports whether the kind is FieldInt or FieldFloat, the kinds a Field's Min and Max apply to.

func (FieldKind) IsShape

func (k FieldKind) IsShape() bool

IsShape reports whether the kind is one of the 2D geometry shape kinds: FieldPoint, FieldRect, FieldCircle or FieldPolygon.

func (FieldKind) String

func (k FieldKind) String() string

String returns the kind's name as written in error messages: "bool", "int", "float", "string", "[]string", "[][2]float64", "point", "rect", "circle", "polygon", "smart_slots", "bezier_points", "event_pages", "color", "object", "scene" or "resource".

type FileResolver

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 FlashFinishedEvent

type FlashFinishedEvent struct {
	ObjectID string
}

FlashFinishedEvent is the payload emitted with an object's "flash.finished" event.

type FogDoc

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 (*FogDoc) Clone

func (f *FogDoc) Clone() *FogDoc

Clone returns a deep copy of f, or nil when f is nil.

func (*FogDoc) EffectiveColor

func (f *FogDoc) EffectiveColor() string

EffectiveColor returns f.Color, defaulting to "#8090a8" when empty.

func (*FogDoc) EffectiveMaxOpacity

func (f *FogDoc) EffectiveMaxOpacity() float32

EffectiveMaxOpacity returns f.MaxOpacity, defaulting to 1 when nil.

func (*FogDoc) EffectiveMode

func (f *FogDoc) EffectiveMode() FogMode

EffectiveMode returns f.Mode, defaulting to FogOff when empty.

type FogMode

type FogMode string

FogMode 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 FogVolumeDoc

type FogVolumeDoc struct {
	// Shape selects FogVolumeBox ("box"), FogVolumeEllipsoid ("ellipsoid") or FogVolumeCylinder ("cylinder"); empty defaults to box.
	Shape FogVolumeShape `yaml:"shape,omitempty" schema:"enum=box|ellipsoid|cylinder"`
	// Density is the base volumetric extinction coefficient in inverse world units; nil defaults to 0.3. Must be finite and non-negative.
	Density *float32 `yaml:"density,omitempty" schema:"minimum=0"`
	// Color is the optional CSS scattering albedo color (sRGB, converted to linear light when shaded); empty defaults to "#ffffff".
	Color string `yaml:"color,omitempty"`
	// Emission is the optional CSS self-luminous emission color (sRGB, converted to linear light when shaded); empty defaults to "#000000".
	Emission string `yaml:"emission,omitempty"`
	// HeightFalloff is the vertical exponential decay rate above the volume's bottom; must be finite and non-negative.
	HeightFalloff float32 `yaml:"heightFalloff,omitempty" schema:"minimum=0"`
	// EdgeFade is the soft boundary fade thickness as a fraction of the local half-extent; must be finite and non-negative.
	EdgeFade float32 `yaml:"edgeFade,omitempty" schema:"minimum=0"`
	// Anisotropy is the Henyey-Greenstein scattering phase asymmetry in [-1, 1] (0 is isotropic, positive favors forward scattering toward the directional light).
	Anisotropy float32 `yaml:"anisotropy,omitempty" schema:"minimum=-1,maximum=1"`
}

FogVolumeDoc configures a local analytic 3D fog volume attached to an object (ObjectDoc.FogVolume). Its position, rotation and world-space extents come from the object's 3D transform and scale. Version 4.

func (*FogVolumeDoc) Clone

func (f *FogVolumeDoc) Clone() *FogVolumeDoc

Clone returns a deep copy of f, or nil when f is nil.

func (*FogVolumeDoc) EffectiveColor

func (f *FogVolumeDoc) EffectiveColor() string

EffectiveColor returns f.Color, defaulting to "#ffffff" when empty.

func (*FogVolumeDoc) EffectiveDensity

func (f *FogVolumeDoc) EffectiveDensity() float32

EffectiveDensity returns f.Density, defaulting to DefaultFogVolumeDensity (0.3) when nil.

func (*FogVolumeDoc) EffectiveEmission

func (f *FogVolumeDoc) EffectiveEmission() string

EffectiveEmission returns f.Emission, defaulting to "#000000" when empty.

func (*FogVolumeDoc) EffectiveShape

func (f *FogVolumeDoc) EffectiveShape() FogVolumeShape

EffectiveShape returns f.Shape, defaulting to FogVolumeBox when empty.

type FogVolumeShape

type FogVolumeShape string

FogVolumeShape selects the analytic local fog volume primitive (FogVolumeDoc.Shape).

const (
	// FogVolumeBox fills the object's local [-0.5, 0.5]^3 box, sized by the object's 3D scale.
	FogVolumeBox FogVolumeShape = "box"
	// FogVolumeEllipsoid fills the ellipsoid inscribed in the object's local [-0.5, 0.5]^3 box, sized by the object's 3D scale.
	FogVolumeEllipsoid FogVolumeShape = "ellipsoid"
	// FogVolumeCylinder fills the Y-axis cylinder inscribed in the object's local [-0.5, 0.5]^3 box, sized by the object's 3D scale.
	FogVolumeCylinder FogVolumeShape = "cylinder"
)

type GameActions

type GameActions struct {
	// PlaySound plays the sound resource or cue named by path (game target: sound.play).
	PlaySound func(path string) error
	// ChangeScene switches to the scene at path with the optional named transition
	// (game target: scene.change). Use SceneManagerChanger to wire a *scene.Manager directly.
	ChangeScene func(path, transition string) error
	// SaveSlot persists the game's current state to the named save slot (game target: save.slot).
	// Use SaveVarsSlot to snapshot a *flow.Vars directly into a *save.Store.
	SaveSlot func(name string) error
	// BuiltScene is the live BuiltScene acted on by built-in scene.* handlers (destroy, spawn, set,
	// show, hide). When nil, handlers fall back to Call.Context when it is a *BuiltScene or implements
	// BuiltSceneProvider.
	BuiltScene *BuiltScene
	// Resolver loads scene files and assets for scene.spawn. When nil, handlers fall back to the
	// AssetResolver passed to Build when BuiltScene was constructed.
	Resolver AssetResolver
}

GameActions supplies the host callbacks for the built-in "game" target's handlers (sound.play, scene.change, save.slot) and optional BuiltScene/Resolver overrides for scene.* handlers. Attach it with Signals.SetGameActions or ConnectOptions.Game.

type GlowDoc

type GlowDoc struct {
	// Intensity scales the bloom added back to the image; must be finite and non-negative.
	Intensity float32 `yaml:"intensity,omitempty" schema:"minimum=0"`
	// Threshold is the brightness above which a pixel blooms; must be finite and non-negative.
	Threshold float32 `yaml:"threshold,omitempty" schema:"minimum=0"`
	// SoftKnee softens the threshold's cutoff, in [0, 1].
	SoftKnee float32 `yaml:"softKnee,omitempty" schema:"minimum=0,maximum=1"`
	// Radius is the blur radius in pixels; must be non-negative.
	Radius int `yaml:"radius,omitempty" schema:"minimum=0"`
	// HalfRes computes the bloom at half resolution.
	HalfRes bool `yaml:"halfRes,omitempty"`
}

GlowDoc configures bloom/glow extraction and compositing (EnvironmentDoc.Glow). The scene format records it for the renderer, which does not read it yet.

type Handler

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 BuiltinSceneHandlers

func BuiltinSceneHandlers() []Handler

BuiltinSceneHandlers returns the built-in "scene" handler set available on every scene object (written as scene.destroy, scene.spawn, scene.set, scene.show, scene.hide, and scene.emit).

func (*Handler) Param

func (h *Handler) Param(name string) (Field, bool)

Param returns the param named name and whether the handler has it.

type HandlerFunc

type HandlerFunc func(Call)

HandlerFunc runs a handler for one emitted event.

type ImageResolver

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 Instance

type Instance struct {
	// Prefix is the unique ID prefix assigned to this instance (also equal to Root.ID).
	Prefix string
	// Root is the root BuiltObject of the instance, holding all instanced top-level objects as Children.
	Root *BuiltObject
	// Entities maps each instanced object ID (Root and its descendants) to its spawned entities.Entity when a World was provided, or nil otherwise.
	Entities map[string]entities.Entity
}

Instance is one scene instance added to a running BuiltScene by Instantiate or InstancePool.Spawn.

type InstanceOptions

type InstanceOptions struct {
	// Layer is the name of the layer in BuiltScene to add the instance to; required.
	Layer string
	// Parent is the object ID to parent the instance under; empty adds the instance root to Layer directly.
	// When set, Parent must name a live object on Layer.
	Parent string
	// X and Y are the local position of the instance root (relative to Parent, or Layer when Parent is empty).
	X, Y float32
	// Prefix is the ID prefix for the instance root and its children ("<Prefix>/<childID>").
	// When empty, Instantiate picks "<base>#<n>" unique in the scene, deriving <base> from Source (file base name without .scene.yaml / .yaml), then doc.Name, then "instance".
	Prefix string
	// Source optionally names the source scene file path (such as "prefabs/enemy.scene.yaml"), used to derive the default Prefix base and for cycle detection when resolving nested or recursive instances.
	Source string
	// World optionally spawns ECS entities for the instance root and its descendants into World, parented under Parent's entity when Parent has a live entity in World.
	// When Signals was created by SpawnConnected and World is nil, Signals' world is used automatically.
	World *entities.World
	// Signals optionally registers the instance's objects and wires its connections into Signals in place, keeping pending queued events and once-connection state for other objects intact.
	Signals *Signals
	// Components optionally validates object components and invokes registered ComponentType.Spawn factories when spawning entities into World. When nil and Signals is non-nil, Signals' ComponentRegistry is used.
	Components *ComponentRegistry
}

InstanceOptions configures BuiltScene.Instantiate and BuiltScene.NewInstancePool.

type InstancePool

type InstancePool struct {
	// contains filtered or unexported fields
}

InstancePool pre-compiles a scene document for repeated runtime spawning and freeing on one BuiltScene layer with zero steady-state heap allocations after warm-up. Calling BuiltScene.Free(inst.Root.ID) or pool.Free(inst) tears down every subsystem (sprites, physics, 2D lights, signals, ECS entities) in the same step and recycles the slot back into the pool.

func (*InstancePool) Active

func (p *InstancePool) Active() int

Active returns how many instances from p are currently live in its BuiltScene.

func (*InstancePool) Available

func (p *InstancePool) Available() int

Available returns how many pre-allocated recycled slots are waiting in p.

func (*InstancePool) Free

func (p *InstancePool) Free(inst *Instance) bool

Free removes inst from p's BuiltScene and returns its slot to p. It returns false if inst is nil, already freed, or does not belong to p.

func (*InstancePool) Prewarm

func (p *InstancePool) Prewarm(n int) error

Prewarm ensures at least n recycled slots are ready in p so subsequent Spawn calls perform zero heap allocations.

func (*InstancePool) Spawn

func (p *InstancePool) Spawn(x, y float32) (*Instance, error)

Spawn activates one instance from p at local position (x, y) on p's layer (and optional parent) with zero steady-state heap allocations once p is warmed up.

type LDtkOptionsResolver

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 Label3DDoc

type Label3DDoc struct {
	// Text is the text the label draws.
	Text string `yaml:"text"`
	// Font is the slash-separated path from the project root to the font; empty uses the default font.
	Font string `yaml:"font,omitempty"`
	// Size is the text's height in world units; must be finite and non-negative, and 0 leaves it to the renderer.
	Size float32 `yaml:"size,omitempty" schema:"minimum=0"`
	// Billboard turns the text to face the camera.
	Billboard bool `yaml:"billboard,omitempty"`
	// Outline is an optional CSS color for the text's outline; empty draws none.
	Outline string `yaml:"outline,omitempty"`
}

Label3DDoc places world-space text (ObjectDoc.Label3D). The scene format records it; Build does not create a label from it yet.

type LayerDoc

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"`
	// Tint is an optional hex color ("#rrggbb" or "#rrggbbaa") multiplying every item in this layer; empty leaves the layer untinted.
	Tint string `yaml:"tint,omitempty"`
	// Opacity multiplies the opacity of every item in this layer, in [0, 1]; nil defaults to 1.
	Opacity *float32 `yaml:"opacity,omitempty" schema:"minimum=0,maximum=1"`
	// 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"`
	// AutoscrollX scrolls the layer horizontally in layer points per second during Update; wraps with RepeatWidth when RepeatX is true.
	AutoscrollX float32 `yaml:"autoscrollX,omitempty"`
	// AutoscrollY scrolls the layer vertically in layer points per second during Update; wraps with RepeatHeight when RepeatY is true.
	AutoscrollY float32 `yaml:"autoscrollY,omitempty"`
	// Scale uniformly scales the layer about its origin; nil defaults to 1.
	Scale *float32 `yaml:"scale,omitempty"`
	// Rotation turns the layer clockwise in radians about its origin.
	Rotation float32 `yaml:"rotation,omitempty"`
	// VisibilityLayers lists named visibility layers (from game.yaml) matched against viewport cull masks; empty draws in every viewport.
	VisibilityLayers []string `yaml:"visibilityLayers,omitempty,flow"`
	// LightMask is an optional 32-bit 2D light mask bitmask matched against Light.ItemMask; nil defaults to 1 (bit 0) and 0 marks an unlit layer that keeps its place in the draw order but is never lit. Version 4.
	LightMask *uint32 `yaml:"lightMask,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 (*LayerDoc) EffectiveLightMask

func (l *LayerDoc) EffectiveLightMask() uint32

EffectiveLightMask returns the layer's effective 32-bit 2D light mask, defaulting to 1 (bit 0) when LightMask is nil.

func (*LayerDoc) EffectiveOpacity

func (l *LayerDoc) EffectiveOpacity() float32

EffectiveOpacity returns Opacity, defaulting to 1 when nil.

func (*LayerDoc) EffectiveParallaxX

func (l *LayerDoc) EffectiveParallaxX() float32

EffectiveParallaxX returns ParallaxX, defaulting to 1 when nil.

func (*LayerDoc) EffectiveParallaxY

func (l *LayerDoc) EffectiveParallaxY() float32

EffectiveParallaxY returns ParallaxY, defaulting to 1 when nil.

func (*LayerDoc) EffectiveScale

func (l *LayerDoc) EffectiveScale() float32

EffectiveScale returns Scale, defaulting to 1 when nil.

func (*LayerDoc) EffectiveSpace

func (l *LayerDoc) EffectiveSpace() Space

EffectiveSpace returns SpaceWorld when Space is empty, and l.Space otherwise.

func (*LayerDoc) IsVisible

func (l *LayerDoc) IsVisible() bool

IsVisible reports whether the layer is visible, defaulting to true when Visible is nil.

type LayerOverride

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"`
	// Tint replaces the layer's hex tint color ("#rrggbb" or "#rrggbbaa") when set; "" clears it.
	Tint *string `yaml:"tint,omitempty"`
	// Opacity replaces the layer's opacity in [0, 1] when set.
	Opacity *float32 `yaml:"opacity,omitempty" schema:"minimum=0,maximum=1"`
	// 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"`
	// AutoscrollX replaces the layer's horizontal autoscroll speed in layer points per second when set.
	AutoscrollX *float32 `yaml:"autoscrollX,omitempty"`
	// AutoscrollY replaces the layer's vertical autoscroll speed in layer points per second when set.
	AutoscrollY *float32 `yaml:"autoscrollY,omitempty"`
	// Scale replaces the layer's uniform scale factor when set.
	Scale *float32 `yaml:"scale,omitempty"`
	// Rotation replaces the layer's clockwise rotation in radians when set.
	Rotation *float32 `yaml:"rotation,omitempty"`
	// VisibilityLayers replaces the layer's named visibility layers (from game.yaml) when set; an empty slice clears them to all viewports.
	VisibilityLayers *[]string `yaml:"visibilityLayers,omitempty,flow"`
	// LightMask replaces the layer's 32-bit 2D light mask when set; 0 marks an unlit layer. Version 4.
	LightMask *uint32 `yaml:"lightMask,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

type Light2DDebug struct {
	Version        int
	Kind           string
	Color          core.Color
	Radius         float32
	WorldRadius    float32
	Intensity      float32
	Energy         float32
	MaxDistance    float32
	Falloff        float32
	Direction      float32
	Angle          float32
	Texture        string
	TextureScale   float32
	Blend          lights2d.BlendMode
	CastShadows    bool
	ShadowColor    core.Color
	ShadowSoftness float32
	Height         float32
	ItemMask       uint32
	ShadowMask     uint32
	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

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 (nil for kind: "directional") and debug metadata.

func ExtractLight2DWithResolver

func ExtractLight2DWithResolver(o *ObjectDoc, world *math2d.Affine, resolver ImageResolver) (*lights2d.Light, *lights2d.DirectionalLight, Light2DDebug, error)

ExtractLight2DWithResolver resolves a light2d component from o at world (or o's local transform when world is nil), resolving optional cookie textures through resolver. For point and spot lights it returns (*lights2d.Light, nil, dbg, nil); for directional lights it returns (nil, *lights2d.DirectionalLight, dbg, nil).

type LightDoc

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"`
	// LightMask is the 32-bit bitmask of 3D render layers this light illuminates; 0 illuminates all layers.
	LightMask uint32 `yaml:"lightMask,omitempty"`
	// ShadowMask is the 32-bit bitmask of 3D render layers that cast shadows for this light; 0 includes all layers.
	ShadowMask uint32 `yaml:"shadowMask,omitempty"`
	// Bake selects how lightmap baking treats this light: "static" bakes it, "dynamic" leaves it real-time, "off" excludes it from bakes; empty leaves the renderer default.
	Bake string `yaml:"bake,omitempty" schema:"enum=static|dynamic|off"`

	// Shadow contains optional bias, opacity, softness, cascade and distance settings (ShadowSettings says which ones the renderer reads).
	Shadow ShadowSettings `yaml:"shadow,omitempty"`
	// Fade contains optional light and shadow distance fade settings, recorded for the renderer, which does not read them yet.
	Fade FadeSettings `yaml:"fade,omitempty"`
	// Projector is the slash-separated path from the project root to a cookie texture the light projects, recorded for the renderer, which does not read it yet.
	Projector string `yaml:"projector,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 (*LightDoc) Clone

func (l *LightDoc) Clone() *LightDoc

Clone returns a deep copy of l, or nil when l is nil.

func (*LightDoc) EffectiveColor

func (l *LightDoc) EffectiveColor() string

EffectiveColor returns l.Color, defaulting to "#ffffff" when empty.

func (*LightDoc) EffectiveIntensity

func (l *LightDoc) EffectiveIntensity() float32

EffectiveIntensity returns l.Intensity, defaulting to 1 when nil.

func (*LightDoc) EffectiveLightMask

func (l *LightDoc) EffectiveLightMask() uint32

EffectiveLightMask returns l.LightMask, defaulting zero to all 32 render layers (^uint32(0)).

func (*LightDoc) EffectiveOuterCone

func (l *LightDoc) EffectiveOuterCone() float32

EffectiveOuterCone returns a spot light's outer cone half-angle in degrees, defaulting to 45 when nil.

func (*LightDoc) EffectiveShadowMask

func (l *LightDoc) EffectiveShadowMask() uint32

EffectiveShadowMask returns l.ShadowMask, defaulting zero to all 32 render layers (^uint32(0)).

type LightKind

type LightKind string

LightKind 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 LightPart

type LightPart uint8

LightPart selects which content of a layer a draw call renders when 2D lighting splits the layer by light mask (BuiltScene.DrawLayerPart, BuiltScene.DrawLayersLit).

const (
	// LightPartAll draws all of the layer's content.
	LightPartAll LightPart = iota
	// LightPartLit draws the layer's tilemaps and the objects whose LightMask is non-zero.
	LightPartLit
	// LightPartUnlit draws only the layer's objects whose LightMask is zero.
	LightPartUnlit
)

type LightProbeGridDoc

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 (*LightProbeGridDoc) Clone

Clone returns a deep copy of g, or nil when g is nil.

func (*LightProbeGridDoc) EffectiveCenter

func (g *LightProbeGridDoc) EffectiveCenter() [3]float32

EffectiveCenter returns g.Center, defaulting to [0, 0, 0] when nil.

func (*LightProbeGridDoc) EffectiveCounts

func (g *LightProbeGridDoc) EffectiveCounts() [3]int

EffectiveCounts returns g.Counts, defaulting to [3, 2, 3] when nil or all zero.

func (*LightProbeGridDoc) EffectiveIntensity

func (g *LightProbeGridDoc) EffectiveIntensity() float32

EffectiveIntensity returns g.Intensity, defaulting to 1 when nil.

func (*LightProbeGridDoc) EffectiveSize

func (g *LightProbeGridDoc) EffectiveSize() [3]float32

EffectiveSize returns g.Size, defaulting to [10, 6, 10] when nil or all zero.

func (*LightProbeGridDoc) LocalBounds

func (g *LightProbeGridDoc) LocalBounds() (lo, hi [3]float32)

LocalBounds returns the local-space min and max corners of the grid's volume.

type LightmapDoc

type LightmapDoc struct {
	// Static includes the object's geometry in baked lightmaps.
	Static bool `yaml:"static,omitempty"`
	// TexelScale multiplies the scene's lightmap texel density for this object; 0 uses 1.
	TexelScale float32 `yaml:"texelScale,omitempty" schema:"minimum=0"`
}

LightmapDoc marks static geometry for baked lightmap sampling.

func (*LightmapDoc) EffectiveTexelScale

func (l *LightmapDoc) EffectiveTexelScale() float32

EffectiveTexelScale returns l.TexelScale, defaulting to 1 when l is nil or TexelScale is 0.

type LineOfSightControllerSnapshot

type LineOfSightControllerSnapshot struct {
	Enabled     bool     `yaml:"enabled" json:"enabled"`
	TargetID    string   `yaml:"targetID,omitempty" json:"targetID,omitempty"`
	SeenTargets []string `yaml:"seenTargets,omitempty" json:"seenTargets,omitempty"`
}

LineOfSightControllerSnapshot is the serializable state of a "line_of_sight" controller.

type LineOfSightEvent

type LineOfSightEvent struct {
	ObjectID string
	TargetID string
	X, Y     float32
	TargetX  float32
	TargetY  float32
	Distance float32
}

LineOfSightEvent is emitted with "line_of_sight.seen" and "line_of_sight.lost".

type LineOfSightRuntimeState

type LineOfSightRuntimeState struct {
	Enabled     bool
	HasTarget   bool
	TargetID    string
	SeenTargets []string
}

LineOfSightRuntimeState is the readable runtime state of an object's "line_of_sight" controller.

type ListenOptions

type ListenOptions struct {
	// Once runs the listener only the first time the event fires after Listen.
	Once bool
	// Deferred queues each run for the Flush after the event instead of running inside it; one emission queues one run, and a once listener is used up by the emission that queues it.
	Deferred bool
}

ListenOptions configures one Signals.Listen subscription.

type MapEventCallbacks

type MapEventCallbacks struct {
	OnSay      func(objectID string, cmd flow.SayCommand) bool
	OnChoose   func(objectID string, prompt flow.ChoosePrompt)
	OnGive     func(objectID string, cmd flow.ItemCommand) error
	OnTake     func(objectID string, cmd flow.ItemCommand) error
	OnTransfer func(objectID string, cmd flow.TransferCommand) error
	OnSound    func(objectID string, cmd flow.SoundCommand)
	OnDialogue func(objectID string, node string) flow.Step
	ItemCount  func(item string) int
	Funcs      map[string]expr.Func
}

MapEventCallbacks configures game-level hooks invoked when built-in "map_event" components run commands.

type MapEventFinishedEvent

type MapEventFinishedEvent struct {
	ObjectID string
	Page     int
}

MapEventFinishedEvent is emitted with "map_event.finished" when a page finishes running.

type MapEventItemEvent

type MapEventItemEvent struct {
	ObjectID string
	Item     string
	Count    int
}

MapEventItemEvent is emitted with "map_event.give" or "map_event.take" when an item command runs.

type MapEventObjectSnapshot

type MapEventObjectSnapshot struct {
	ID          string             `yaml:"id" json:"id"`
	Enabled     bool               `yaml:"enabled" json:"enabled"`
	ActivePage  int                `yaml:"activePage" json:"activePage"`
	WasTouching bool               `yaml:"wasTouching,omitempty" json:"wasTouching,omitempty"`
	Event       flow.EventSnapshot `yaml:"event" json:"event"`
	MoveRoute   *MoveRouteSnapshot `yaml:"moveRoute,omitempty" json:"moveRoute,omitempty"`
}

MapEventObjectSnapshot captures the serializable runtime state of one "map_event" object.

type MapEventPageChangedEvent

type MapEventPageChangedEvent struct {
	ObjectID string
	Page     int
	Sprite   string
}

MapEventPageChangedEvent is emitted with "map_event.page_changed" when an event's active page changes.

type MapEventRuntimeState

type MapEventRuntimeState struct {
	Enabled    bool
	ActivePage int
	Trigger    string
	Sprite     string
	Running    bool
	Waiting    flow.CommandWaitKind
	Err        error
}

MapEventRuntimeState is the readable runtime status of an object's "map_event" component.

type MapEventSayEvent

type MapEventSayEvent struct {
	ObjectID string
	Text     string
	Speaker  string
}

MapEventSayEvent is emitted with "map_event.say" when a say command runs.

type MapEventSoundEvent

type MapEventSoundEvent struct {
	ObjectID string
	Cue      string
	Path     string
	Volume   float64
}

MapEventSoundEvent is emitted with "map_event.sound" when a sound command runs.

type MapEventStartedEvent

type MapEventStartedEvent struct {
	ObjectID string
	Page     int
	Trigger  string
}

MapEventStartedEvent is emitted with "map_event.started" when a page begins running.

type MapEventTransferEvent

type MapEventTransferEvent struct {
	ObjectID string
	Map      string
	Scene    string
	X, Y     int
	HasAt    bool
	Facing   string
}

MapEventTransferEvent is emitted with "map_event.transfer" when a transfer command runs.

type MaterialResolver

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

type MergeConflict struct {
	// Kind is ConflictField, ConflictDeleteModify, ConflictAddAdd, ConflictMove or ConflictValidation.
	Kind ConflictKind `yaml:"kind"`
	// Scope is "scene", "layer", "object", "connection", "tilemap", "override", "layerOverride", "document", "entry", or "item".
	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 (MergeConflict) Summary

func (c MergeConflict) Summary() string

formatConflictSummary returns a single-line human-readable description of c for CLI diagnostics.

type MergeResult

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

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 schema version merges monotonically to the highest version across base, ours and theirs (never below base) rather than conflicting when two branches upgrade independently. The combined result is validated with Validate; a merged document that fails validation is reported as a ConflictValidation conflict.

func (*MergeResult) ConflictDoc

func (r *MergeResult) ConflictDoc(scenePath string) *ConflictDoc

ConflictDoc returns a versioned ConflictDoc for scenePath when r has conflicts, or nil when the merge is clean.

func (*MergeResult) HasConflicts

func (r *MergeResult) HasConflicts() bool

HasConflicts reports whether the merge encountered any conflicts.

type MergedItem

type MergedItem struct {
	// Scope is "scene", "layer", "object", "connection", "tilemap", "override", "layerOverride", "document", "entry", or "item".
	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

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 MoveRouteSnapshot

type MoveRouteSnapshot struct {
	TargetID      string   `yaml:"targetId" json:"targetId"`
	Route         []string `yaml:"route" json:"route"`
	Index         int      `yaml:"index" json:"index"`
	StartedStep   bool     `yaml:"startedStep,omitempty" json:"startedStep,omitempty"`
	WaitRemaining float64  `yaml:"waitRemaining,omitempty" json:"waitRemaining,omitempty"`
}

MoveRouteSnapshot saves the active position of a tile_movement route started by a move command.

type MoveToArrivedEvent

type MoveToArrivedEvent struct {
	ObjectID string
	X, Y     float32
}

MoveToArrivedEvent is the payload emitted with an object's "move_to.arrived" event.

type NavRegion2DDebug struct {
	Mode                  string
	Points                [][2]float64
	OffsetX               float32
	OffsetY               float32
	SubtractTileCollision bool
	TileLayer             string
	TileLayers            []string
	AgentRadius           float32
	Enabled               bool
	// WorldVertices are the transformed closed polygon vertices in world space.
	WorldVertices []core.Point
}

NavRegion2DDebug describes a resolved navregion2d component in local and world space for editor overlays and polygon handles.

func ExtractNavRegion2D

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

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

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 ObjectChange

type ObjectChange struct {
	// ID is the object's stable ID.
	ID string
	// Kind says whether the object was added, removed or changed.
	Kind ObjectChangeKind
	// Before is a copy of the object in the first scene, or nil when it was added.
	Before *ObjectDoc
	// After is a copy of the object in the second scene, or nil when it was removed.
	After *ObjectDoc
}

ObjectChange is a stable object-level scene diff entry.

func DiffObjects

func DiffObjects(before, after *SceneDoc) []ObjectChange

DiffObjects compares the objects of two scenes by ID, nested children included, without modifying either. It returns the removed and changed objects in the first scene's document order, followed by the added objects in the second scene's document order, so the same two scenes always give the same list. A parent whose children changed is reported as changed too, because its Children differ. A nil scene has no objects.

type ObjectChangeKind

type ObjectChangeKind uint8

ObjectChangeKind identifies how an object changed between two scenes.

const (
	// ObjectAdded is an object only the second scene has.
	ObjectAdded ObjectChangeKind = iota
	// ObjectRemoved is an object only the first scene has.
	ObjectRemoved
	// ObjectChanged is an object both scenes have with different contents, its children included.
	ObjectChanged
)

type ObjectControllerSnapshot

type ObjectControllerSnapshot struct {
	ID             string                            `yaml:"id" json:"id"`
	X              float32                           `yaml:"x,omitempty" json:"x,omitempty"`
	Y              float32                           `yaml:"y,omitempty" json:"y,omitempty"`
	Rotation       float32                           `yaml:"rotation,omitempty" json:"rotation,omitempty"`
	Platform       *PlatformControllerSnapshot       `yaml:"platform,omitempty" json:"platform,omitempty"`
	EightDirection *EightDirectionControllerSnapshot `yaml:"eightDirection,omitempty" json:"eightDirection,omitempty"`
	TileMovement   *TileMovementControllerSnapshot   `yaml:"tileMovement,omitempty" json:"tileMovement,omitempty"`
	Car            *CarControllerSnapshot            `yaml:"car,omitempty" json:"car,omitempty"`
	DragDrop       *DragDropControllerSnapshot       `yaml:"dragDrop,omitempty" json:"dragDrop,omitempty"`
	Turret         *TurretControllerSnapshot         `yaml:"turret,omitempty" json:"turret,omitempty"`
	LineOfSight    *LineOfSightControllerSnapshot    `yaml:"lineOfSight,omitempty" json:"lineOfSight,omitempty"`
	PathAgent      *PathAgentControllerSnapshot      `yaml:"pathAgent,omitempty" json:"pathAgent,omitempty"`
}

ObjectControllerSnapshot holds one object's transform and attached controller runtime snapshots.

type ObjectDetail

type ObjectDetail struct {
	// ID is the object's stable ID.
	ID string
	// Kind says whether the object was added, removed or changed.
	Kind ObjectChangeKind
	// Name is the object's display name, its Name when it has one and its ID otherwise.
	Name string
	// Layer is the name of the layer the object is in in the second scene, or in the first scene when the object was removed.
	Layer string
	// OldLayer is the name of the layer the object was in in the first scene, or "" when the object was added.
	OldLayer string
	// Parent is the ID of the object's parent in the second scene, or "" when it is a top-level object or was removed.
	Parent string
	// OldParent is the ID of the object's parent in the first scene, or "" when it was a top-level object or was added.
	OldParent string
	// Fields are the object's changed fields in FieldChange order: the "layer" and "parent" moves first, then the object's YAML fields. It is nil for added and removed objects, whose contents appear in Before and After.
	Fields []FieldChange
	// Before is a copy of the object in the first scene, or nil when it was added.
	Before *ObjectDoc
	// After is a copy of the object in the second scene, or nil when it was removed.
	After *ObjectDoc
}

ObjectDetail is one object a scene added, removed or changed, with the fields that changed and where it sits.

func DiffObjectDetails

func DiffObjectDetails(before, after *SceneDoc) []ObjectDetail

DiffObjectDetails compares two scenes object by object by stable ID, nested children included, and describes every change with its layer, parent and changed fields. It returns the removed and changed objects in the first scene's document order, followed by the added objects in the second scene's document order, so the same two scenes always give the same list. A child's own change is reported on the child, not on its parent. Two scenes that differ only in the order of objects within a layer report no change, since objects are compared by ID. A nil scene has no objects.

type ObjectDoc

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"`
	// Groups optionally tags the object with one or more group names for runtime queries (BuiltScene.InGroup, World.InGroup, scene3d.Node.FindByTag). Group names start with an ASCII letter or underscore and contain only ASCII letters, digits, underscores, or hyphens. Encode sorts and deduplicates them.
	Groups []string `yaml:"groups,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"`
	// Terrain optionally names a terrain height and material file (*.terrain.yaml or *.terrain.yml). It cannot be combined with Mesh, Model or GridMap. Version 4.
	Terrain string `yaml:"terrain,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"`
	// CastShadow selects how this 3D object participates in shadow and main passes: "on" (default), "off", "doubleSided" or "only". Version 4.
	CastShadow CastShadowMode `yaml:"castShadow,omitempty" schema:"enum=on|off|doubleSided|only"`
	// Layers is the 32-bit bitmask of 3D render layers this object belongs to (matching scene3d.Node.Layer); 0 defaults to layer 1 (scene3d.LayerDefault). Version 4.
	Layers uint32 `yaml:"layers,omitempty"`
	// VisibilityRange optionally configures camera-distance culling and screen-door dither fading for this 3D object. Version 4.
	VisibilityRange *VisibilityRangeDoc `yaml:"visibilityRange,omitempty"`
	// SkipOcclusion skips software occlusion culling for this 3D object when true. Version 4.
	SkipOcclusion bool `yaml:"skipOcclusion,omitempty"`
	// ExtraCullMargin expands this 3D object's world bounding box on all axes for frustum and occlusion culling; must be finite and non-negative. Version 4.
	ExtraCullMargin float32 `yaml:"extraCullMargin,omitempty" schema:"minimum=0"`
	// 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"`
	// Modulate is an optional hex color ("#rrggbb" or "#rrggbbaa") multiplying this object and its children; empty defaults to opaque white.
	Modulate string `yaml:"modulate,omitempty"`
	// SelfModulate is an optional hex color ("#rrggbb" or "#rrggbbaa") multiplying only this object's own drawables (not inherited by children); empty defaults to opaque white.
	SelfModulate string `yaml:"selfModulate,omitempty"`
	// Visible controls whether this object and its entire subtree are drawn and hit-tested; nil defaults to true.
	Visible *bool `yaml:"visible,omitempty"`
	// VisibilityLayers lists named visibility layers (from game.yaml) matched against viewport cull masks; empty draws in every viewport.
	VisibilityLayers []string `yaml:"visibilityLayers,omitempty,flow"`
	// Tint is an optional CSS color string parsed with core.ParseColor (such as "#ff4040" or "rgba(255, 64, 64, 1)") that multiplies the object's sprite channels; empty leaves the sprite untinted.
	Tint string `yaml:"tint,omitempty"`
	// LightMask is an optional 32-bit 2D light mask bitmask matched against Light.ItemMask; nil inherits the containing layer's LightMask and 0 marks an unlit object, drawn right after its layer's light pass. Version 4.
	LightMask *uint32 `yaml:"lightMask,omitempty"`

	// 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"`
	// LocalMaterial gives this object its own copy of Material (resource.Clone) when Build runs, so changing fields on BuiltObject.Material does not affect other objects using the same file. Hot reload updates any fields on the local copy that the object has not changed. Requires Material.
	LocalMaterial bool `yaml:"localMaterial,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"`
	// FogVolume optionally attaches an analytic local 3D fog volume (box, ellipsoid or cylinder) sized by this object's 3D transform and scale. Version 4.
	FogVolume *FogVolumeDoc `yaml:"fogVolume,omitempty"`
	// CSG optionally makes this object a constructive-solid-geometry primitive, or a combiner of its CSG children.
	CSG *CSGDoc `yaml:"csg,omitempty"`
	// Sound optionally attaches a looping or one-shot sound emitter to this object.
	Sound *SoundEmitterDoc `yaml:"sound,omitempty"`
	// SoundZone optionally makes this object's region switch the active audio bus while the listener is inside it.
	SoundZone *SoundZoneDoc `yaml:"soundZone,omitempty"`
	// Lightmap optionally marks this object's static geometry for baked lightmap sampling.
	Lightmap *LightmapDoc `yaml:"lightmap,omitempty"`
	// Decal optionally projects a texture from this object onto nearby geometry.
	Decal *DecalDoc `yaml:"decal,omitempty"`
	// Particles3D optionally attaches a 3D particle emitter resource to this object.
	Particles3D *Particles3DRef `yaml:"particles3d,omitempty"`
	// Label3D optionally draws world-space text at this object.
	Label3D *Label3DDoc `yaml:"label3d,omitempty"`
	// Sprite3D optionally draws a billboard sprite sheet at this object.
	Sprite3D *Sprite3DDoc `yaml:"sprite3d,omitempty"`
	// Path3D optionally attaches a deterministic 3D curve path to this object.
	Path3D *Path3DDoc `yaml:"path3d,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"`
	// Parameters supplies values for the reusable scene's declarations.
	Parameters map[string]any `yaml:"parameters,omitempty"`
	// AlwaysLoaded keeps this object loaded regardless of streaming source positions when the scene is partitioned. Cannot be combined with Grid.
	AlwaysLoaded bool `yaml:"alwaysLoaded,omitempty"`
	// Grid optionally pins this object to a named extra grid in SceneDoc.Partition.Grids (for example "far"). Cannot be combined with AlwaysLoaded.
	Grid string `yaml:"grid,omitempty"`
	// DataLayers optionally lists the SceneDoc.DataLayers this object belongs to; the object exists only when its cell and all of its layers allow.
	DataLayers []string `yaml:"dataLayers,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 (*ObjectDoc) Clone

func (o *ObjectDoc) Clone() ObjectDoc

Clone 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 (*ObjectDoc) EffectiveAlpha

func (o *ObjectDoc) EffectiveAlpha() float32

EffectiveAlpha returns Alpha, defaulting to 1 when nil.

func (*ObjectDoc) EffectiveCastShadow

func (o *ObjectDoc) EffectiveCastShadow() CastShadowMode

EffectiveCastShadow returns CastShadow, defaulting empty to CastShadowOn.

func (*ObjectDoc) EffectiveScaleX

func (o *ObjectDoc) EffectiveScaleX() float32

EffectiveScaleX returns ScaleX, defaulting to 1 when nil.

func (*ObjectDoc) EffectiveScaleY

func (o *ObjectDoc) EffectiveScaleY() float32

EffectiveScaleY returns ScaleY, defaulting to 1 when nil.

func (*ObjectDoc) EffectiveScaleZ

func (o *ObjectDoc) EffectiveScaleZ() float32

EffectiveScaleZ returns ScaleZ, defaulting to 1 when nil.

func (*ObjectDoc) EffectiveTint

func (o *ObjectDoc) EffectiveTint() core.Color

EffectiveTint returns Tint parsed as a core.Color, or 0 (untinted) when empty or invalid.

func (*ObjectDoc) IsVisible

func (o *ObjectDoc) IsVisible() bool

IsVisible reports whether the object is visible, defaulting to true when Visible is nil.

func (*ObjectDoc) LocalTransform

func (o *ObjectDoc) LocalTransform() math2d.Affine

LocalTransform 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

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"`
	// Groups replaces the object's group list; set to an empty slice to clear inherited groups.
	Groups *[]string `yaml:"groups,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"`
	// Terrain replaces the terrain file the object draws.
	Terrain *string `yaml:"terrain,omitempty"`
	// Occluder replaces the object's 3D occluder definition.
	Occluder *OccluderDoc `yaml:"occluder,omitempty"`
	// CastShadow replaces the object's 3D shadow casting mode; "" restores the default ("on"). Version 4.
	CastShadow *CastShadowMode `yaml:"castShadow,omitempty" schema:"enum=|on|off|doubleSided|only"`
	// Layers replaces the object's 32-bit 3D render layer bitmask. Version 4.
	Layers *uint32 `yaml:"layers,omitempty"`
	// VisibilityRange replaces the object's 3D visibility range configuration. Version 4.
	VisibilityRange *VisibilityRangeDoc `yaml:"visibilityRange,omitempty"`
	// SkipOcclusion replaces whether the object skips software occlusion culling. Version 4.
	SkipOcclusion *bool `yaml:"skipOcclusion,omitempty"`
	// ExtraCullMargin replaces the object's extra frustum/occlusion cull margin. Version 4.
	ExtraCullMargin *float32 `yaml:"extraCullMargin,omitempty" schema:"minimum=0"`
	// 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"`
	// Modulate replaces the object's modulate hex color ("#rrggbb" or "#rrggbbaa"); "" clears it.
	Modulate *string `yaml:"modulate,omitempty"`
	// SelfModulate replaces the object's self-modulate hex color ("#rrggbb" or "#rrggbbaa"); "" clears it.
	SelfModulate *string `yaml:"selfModulate,omitempty"`
	// Visible replaces whether the object and its subtree are visible.
	Visible *bool `yaml:"visible,omitempty"`
	// VisibilityLayers replaces the object's named visibility layers (from game.yaml); an empty slice clears them to all viewports.
	VisibilityLayers *[]string `yaml:"visibilityLayers,omitempty,flow"`
	// Tint replaces the object's sprite tint color.
	Tint *string `yaml:"tint,omitempty"`
	// LightMask replaces the object's 32-bit 2D light mask; 0 marks an unlit object. Version 4.
	LightMask *uint32 `yaml:"lightMask,omitempty"`

	// 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"`
	// LocalMaterial replaces whether the object clones its material file on Build.
	LocalMaterial *bool `yaml:"localMaterial,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"`
	// FogVolume replaces the local 3D fog volume attached to the object. Version 4.
	FogVolume *FogVolumeDoc `yaml:"fogVolume,omitempty"`
	// CSG replaces the object's constructive-solid-geometry node.
	CSG *CSGDoc `yaml:"csg,omitempty"`
	// Sound replaces the sound emitter attached to the object.
	Sound *SoundEmitterDoc `yaml:"sound,omitempty"`
	// SoundZone replaces the audio bus zone attached to the object.
	SoundZone *SoundZoneDoc `yaml:"soundZone,omitempty"`
	// Lightmap replaces the object's baked lightmap settings.
	Lightmap *LightmapDoc `yaml:"lightmap,omitempty"`
	// Decal replaces the decal the object projects.
	Decal *DecalDoc `yaml:"decal,omitempty"`
	// Particles3D replaces the 3D particle emitter attached to the object.
	Particles3D *Particles3DRef `yaml:"particles3d,omitempty"`
	// Label3D replaces the world-space text the object draws.
	Label3D *Label3DDoc `yaml:"label3d,omitempty"`
	// Sprite3D replaces the billboard sprite the object draws.
	Sprite3D *Sprite3DDoc `yaml:"sprite3d,omitempty"`
	// Path3D replaces the 3D curve path attached to the object.
	Path3D *Path3DDoc `yaml:"path3d,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"`
	// Parameters replaces per-instance values for an object's nested scene.
	Parameters map[string]any `yaml:"parameters,omitempty"`
	// AlwaysLoaded replaces whether the object stays always loaded in a partitioned scene.
	AlwaysLoaded *bool `yaml:"alwaysLoaded,omitempty"`
	// Grid replaces the named partition grid the object belongs to.
	Grid *string `yaml:"grid,omitempty"`
	// DataLayers replaces the data layers the object belongs to when non-nil.
	DataLayers []string `yaml:"dataLayers,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

type ObjectRef struct {
	// ID is the object's unique scene ID.
	ID string
	// Layer is the name of the layer the object belongs to (empty for unresolved FieldObject references).
	Layer string
	// Entity is the spawned entity for ID when resolved during SpawnEntitiesWith or BuiltScene.Instantiate, or entities.Zero otherwise.
	Entity entities.Entity `json:"-"`
}

ObjectRef identifies a scene object: SpawnEntities attaches it as an ECS component naming the scene object an entity came from, and ComponentRegistry.Resolve / ComponentType.Spawn pass it for FieldObject component fields (with Entity and Layer populated during SpawnEntitiesWith and BuiltScene.Instantiate).

type Occluder2DDebug

type Occluder2DDebug struct {
	Version    int
	Shape      string
	Width      float32
	Height     float32
	OffsetX    float32
	OffsetY    float32
	Points     [][2]float64
	Layer      string
	TileLayers []string
	LightMask  uint32
	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

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

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 (*OccluderDoc) EffectiveCenter

func (o *OccluderDoc) EffectiveCenter() [3]float32

EffectiveCenter returns Center, defaulting to [0, 0, 0] when nil.

func (*OccluderDoc) EffectiveSize

func (o *OccluderDoc) EffectiveSize() [3]float32

EffectiveSize returns Size, defaulting to [1, 1, 1] when nil or all zero.

func (*OccluderDoc) LocalBounds

func (o *OccluderDoc) LocalBounds() (lo, hi [3]float32)

LocalBounds returns the local-space min and max corners of a "box" occluder.

type OccluderMode

type OccluderMode string

OccluderMode 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 OverBudgetCell

type OverBudgetCell struct {
	Grid        string
	Coord       CellCoord
	ObjectCount int
	Budget      int
}

OverBudgetCell reports a cell whose object count exceeds its grid's configured MaxObjectsPerCell budget.

type ParameterBinding

type ParameterBinding struct {
	// Object is the ID of an object in the same scene.
	Object string `yaml:"object" schema:"required,minLength=1"`
	// Component optionally names the object's component that holds Field.
	Component string `yaml:"component,omitempty"`
	// Property optionally names the object's property that holds Field.
	Property string `yaml:"property,omitempty"`
	// Field is the name of the field the parameter supplies.
	Field string `yaml:"field" schema:"required,minLength=1"`
}

ParameterBinding identifies a field supplied by a scene parameter.

type ParameterType

type ParameterType string

ParameterType is the declared type of a reusable scene parameter.

const (
	// ParameterFloat is a finite number.
	ParameterFloat ParameterType = "float"
	// ParameterInt is a whole number.
	ParameterInt ParameterType = "int"
	// ParameterBool is true or false.
	ParameterBool ParameterType = "bool"
	// ParameterString is a non-empty string.
	ParameterString ParameterType = "string"
	// ParameterColor is a CSS color string parsed with core.ParseColor.
	ParameterColor ParameterType = "color"
	// ParameterVec2 is a sequence of two numbers.
	ParameterVec2 ParameterType = "vec2"
	// ParameterVec3 is a sequence of three numbers.
	ParameterVec3 ParameterType = "vec3"
	// ParameterAsset is a slash-separated path from the project root to an asset file.
	ParameterAsset ParameterType = "asset"
)

type ParseOptions

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
	// VisibilityLayers, when non-nil, validates every named visibility layer in layers, layerOverrides, objects, and overrides against the table. An unknown or misspelled layer name fails the load with a *loaderr.Error carrying File and 1-based Line and Column.
	VisibilityLayers *VisibilityLayerTable
	// Vars, when non-nil, type-checks connection When conditions, expression-valued Args, and built-in game vars.set/vars.add handlers against the declared variables in Vars, reporting unknown names or type mismatches as a *ConnectionError carrying File, Line and Column.
	Vars *flow.VarsDoc
	// Funcs supplies optional custom function signatures (such as has_item) accepted when type-checking connection When conditions and expression-valued Args against Vars.
	Funcs map[string]expr.Func
}

ParseOptions configures ParseWith.

type Particles3DRef

type Particles3DRef struct {
	// File is the slash-separated path from the project root to the particle emitter resource. Required.
	File string `yaml:"file" schema:"required,minLength=1"`
	// Autostart starts emitting as soon as the object is built.
	Autostart bool `yaml:"autostart,omitempty"`
}

Particles3DRef places a 3D particle emitter resource (ObjectDoc.Particles3D). The scene format records it; Build does not create an emitter from it yet.

type ParticlesRef

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". Exactly one of File and Effect is set.
	File string `yaml:"file,omitempty"`
	// Effect is the slash-separated path from the project root to a particle effect YAML file, such as "fx/explosion.effect.yaml". Exactly one of File and Effect is set.
	Effect string `yaml:"effect,omitempty"`
	// Atlas optionally names the sprite.Atlas an AssetResolver looks up to resolve the emitter's or effect's frameNames.
	Atlas string `yaml:"atlas,omitempty"`
	// Params sets the effect's declared parameters for this object, keyed by parameter name; a value is a number, a quoted color such as "#rrggbb" or "#rrggbbaa", or a list of two numbers. It is only valid with Effect.
	Params map[string]any `yaml:"params,omitempty"`
}

ParticlesRef binds an object to a versioned 2D particle emitter YAML file (particles.Config) or a versioned effect file (particles.Effect), with an optional sprite atlas for its frameNames and, for an effect, parameter values set per object.

type ParticlesResolver

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 Partition

type Partition struct {
	// CellSize is the width and height of each square default-grid cell in world units; must be a positive finite number.
	CellSize float64 `yaml:"cellSize" schema:"required,exclusiveMinimum=0"`
	// LoadRadius is the Chebyshev cell radius around a streaming source to load; must be positive.
	LoadRadius int `yaml:"loadRadius" schema:"required,minimum=1"`
	// UnloadRadius is the Chebyshev cell radius beyond which loaded cells unload; must be at least LoadRadius.
	UnloadRadius int `yaml:"unloadRadius" schema:"required,minimum=1"`
	// Plane optionally selects the partitioning plane: "xy" (default for 2D scenes) or "xz" (3D ground plane).
	Plane string `yaml:"plane,omitempty" schema:"enum=xy|xz"`
	// Grids optionally defines extra named grid levels (for example a coarse "far" grid for landmarks). Objects whose bounds exceed a grid's CellSize automatically promote to the finest coarser grid that fits them, or stay alwaysLoaded.
	Grids []PartitionGrid `yaml:"grids,omitempty"`
	// MaxObjectsPerCell optionally sets the per-cell object budget reported by `game check`; 0 disables the budget check.
	MaxObjectsPerCell int `yaml:"maxObjectsPerCell,omitempty" schema:"minimum=0"`
}

Partition describes the deterministic grid used to stream a large scene: square cells of CellSize world units, loaded within LoadRadius cells of a streaming source and kept until a source is more than UnloadRadius cells away.

func (Partition) AllGrids

func (p Partition) AllGrids() []PartitionGrid

AllGrids returns the primary grid (Name == "") followed by all extra grids, sorted by ascending CellSize (ties break with "" first, then ascending Name).

func (Partition) Cells

func (p Partition) Cells(o CellObject) []CellCoord

Cells assigns an object to every cell its bounds touch, in row-major order (Y, then X), so an object larger than one cell is never attached only by its origin. A bounds edge lying exactly on a cell boundary does not touch the next cell; a zero-size object belongs to the cell containing its position. It returns nil for an AlwaysLoaded object, for an invalid partition, and for non-finite or negative bounds.

func (*Partition) Clone

func (p *Partition) Clone() *Partition

Clone returns a deep copy of p, or nil when p is nil.

func (Partition) Coord

func (p Partition) Coord(x, y float64) CellCoord

Coord returns the cell containing the point (x, y).

func (Partition) EffectivePlane

func (p Partition) EffectivePlane() string

EffectivePlane returns Plane, defaulting to PartitionPlaneXY ("xy") when empty.

func (Partition) Grid

func (p Partition) Grid(name string) (PartitionGrid, bool)

Grid returns the grid definition for name ("" returns the primary default grid).

func (Partition) Needed

func (p Partition) Needed(sources []StreamingSource) []CellCoord

Needed returns the cells within LoadRadius cells (scaled per source) of any source, in row-major order (Y, then X). Sources with a non-finite position are skipped, and an invalid partition returns nil.

func (Partition) NeededOrdered

func (p Partition) NeededOrdered(sources []StreamingSource) []CellCoord

NeededOrdered returns the cells within LoadRadius of any source in deterministic streaming load order: highest source Priority first, then shortest Euclidean distance from cell center to nearest covering source (breaking exact boundary ties in favor of the source's own cell), then cell coordinate (Y, then X).

func (Partition) Retained

func (p Partition) Retained(sources []StreamingSource) []CellCoord

Retained returns the cells within UnloadRadius cells (scaled per source) of any source, in the same order as Needed. A loaded cell missing from Retained can be unloaded; because UnloadRadius is at least LoadRadius, every cell in Needed is also in Retained.

func (Partition) Validate

func (p Partition) Validate() error

Validate reports whether the cell size is a positive finite number, the radii satisfy 0 < LoadRadius <= UnloadRadius (so a source on a cell boundary does not load and unload the same cell every frame), Plane is empty/"xy"/"xz", MaxObjectsPerCell is non-negative, and every extra grid in Grids is valid with a unique non-empty name.

type PartitionCellEntry

type PartitionCellEntry struct {
	// Grid is "" for the primary grid or the PartitionGrid.Name for an extra grid.
	Grid string `yaml:"grid,omitempty"`
	// X and Y are the cell's integer grid coordinates.
	X int `yaml:"x"`
	Y int `yaml:"y"`
	// File is the slash-separated path of the cell fragment relative to the manifest directory.
	File string `yaml:"file"`
	// ObjectCount is the total number of objects (children included) stored in this cell fragment.
	ObjectCount int `yaml:"objectCount"`
	// ObjectIDs lists the object IDs stored in this cell fragment in document order.
	ObjectIDs []string `yaml:"objectIDs,omitempty"`
	// DataLayers lists the sorted unique data layers referenced by objects in this cell fragment.
	DataLayers []string `yaml:"dataLayers,omitempty"`
}

PartitionCellEntry describes one generated cell scene fragment in PartitionManifest.

func (PartitionCellEntry) Key

func (e PartitionCellEntry) Key() CellKey

Key returns the CellKey identifying e.

type PartitionCheckReport

type PartitionCheckReport struct {
	OverBudgetCells      []OverBudgetCell
	CrossCellConnections []CrossCellConnection
}

PartitionCheckReport is returned by CheckPartition for diagnostics in `game check`.

func CheckPartition

func CheckPartition(doc *SceneDoc, opts PartitionOptions) (*PartitionCheckReport, error)

CheckPartition analyzes a partitioned SceneDoc for cells exceeding their configured MaxObjectsPerCell budget and connections crossing cells unless their target is AlwaysLoaded.

type PartitionGrid

type PartitionGrid struct {
	// Name uniquely identifies this extra grid within the partition (for example "far"). Cannot be empty or "default".
	Name string `yaml:"name" schema:"required,minLength=1"`
	// CellSize is the width and height of each square cell in world units; must be a positive finite number.
	CellSize float64 `yaml:"cellSize" schema:"required,exclusiveMinimum=0"`
	// LoadRadius is the Chebyshev cell radius around each streaming source to load; must be positive.
	LoadRadius int `yaml:"loadRadius" schema:"required,minimum=1"`
	// UnloadRadius is the Chebyshev cell radius beyond which cells unload; must be at least LoadRadius.
	UnloadRadius int `yaml:"unloadRadius" schema:"required,minimum=1"`
	// MaxObjectsPerCell optionally caps the recommended number of objects per cell in this grid; 0 falls back to Partition.MaxObjectsPerCell.
	MaxObjectsPerCell int `yaml:"maxObjectsPerCell,omitempty" schema:"minimum=0"`
}

PartitionGrid describes an extra spatial grid level in a Partition, such as a coarse "far" grid for landmarks or large bridges with a larger cell size and streaming radius.

func (PartitionGrid) Partition

func (g PartitionGrid) Partition(plane string) Partition

Partition returns a single-grid Partition representing g.

type PartitionManifest

type PartitionManifest struct {
	// Version is PartitionManifestVersion (1).
	Version int `yaml:"version"`
	// Source is the slash-separated project path of the source scene, when provided.
	Source string `yaml:"source,omitempty"`
	// SceneVersion is the schema version of the partitioned SceneDoc fragments.
	SceneVersion int `yaml:"sceneVersion"`
	// Partition is the scene's partition grid configuration.
	Partition Partition `yaml:"partition"`
	// DataLayers lists the non-editor-only data layers declared by the source scene.
	DataLayers []DataLayerDoc `yaml:"dataLayers,omitempty"`
	// AlwaysLoaded is the relative path to the always-loaded scene fragment.
	AlwaysLoaded string `yaml:"alwaysLoaded,omitempty"`
	// Cells lists every generated non-empty cell fragment in deterministic (Grid, Y, X) order.
	Cells []PartitionCellEntry `yaml:"cells,omitempty"`
	// ExternalConnections lists connections whose endpoints live in different cells (or between a cell and alwaysLoaded).
	ExternalConnections []ConnectionDoc `yaml:"externalConnections,omitempty"`
}

PartitionManifest describes the generated output of PartitionScene: the partition configuration, non-editor-only data layers, always-loaded scene fragment, per-cell scene fragments, and any cross-cell connections.

func ParsePartitionManifest

func ParsePartitionManifest(data []byte) (*PartitionManifest, error)

ParsePartitionManifest decodes and validates a PartitionManifest YAML document, refusing unknown fields and trailing documents.

type PartitionOptions

type PartitionOptions struct {
	// Source optionally records the source scene's project-relative path in the generated manifest.
	Source string
	// ObjectBounds optionally supplies explicit local width and height (in world
	// units along the partition plane axes) for an object when not derivable
	// from built-in components (for example, from sprite atlas frame sizes).
	ObjectBounds func(o *ObjectDoc) (width, height float64, ok bool)
}

PartitionOptions configures PartitionScene and CheckPartition.

type PartitionResult

type PartitionResult struct {
	Manifest     *PartitionManifest
	AlwaysLoaded *SceneDoc
	Cells        map[CellKey]*SceneDoc
	Assignments  map[string]CellAssignment
}

PartitionResult is the deterministic in-memory output of PartitionScene.

func PartitionScene

func PartitionScene(doc *SceneDoc, opts PartitionOptions) (*PartitionResult, error)

PartitionScene deterministically partitions a validated, resolved SceneDoc with a non-nil Partition section into an always-loaded base scene, per-cell scene fragments, and a PartitionManifest.

Rules enforced:

  • Objects belonging to editorOnly data layers (or child layers of editorOnly layers) are omitted from build output.
  • Children stay in their parent's cell; assignment uses the combined world bounds of each top-level object and its descendants.
  • Objects whose bounds exceed their grid's CellSize promote to the finest coarser grid that fits them, or to AlwaysLoaded if larger than every grid.
  • Intra-cell connections remain in their cell fragment; always-loaded connections remain in AlwaysLoaded; cross-cell connections are recorded in Manifest.ExternalConnections.

type Path3DDoc

type Path3DDoc struct {
	// Closed joins the last point back to the first.
	Closed bool `yaml:"closed,omitempty"`
	// Points are the curve's points in order; at least two.
	Points []Path3DPoint `yaml:"points" schema:"required,minItems=2"`
}

Path3DDoc describes a deterministic 3D curve path (ObjectDoc.Path3D).

type Path3DPoint

type Path3DPoint struct {
	// P is the point's position in the object's local space.
	P [3]float32 `yaml:"p"`
	// In is the incoming Bezier handle, relative to P.
	In [3]float32 `yaml:"in,omitempty"`
	// Out is the outgoing Bezier handle, relative to P.
	Out [3]float32 `yaml:"out,omitempty"`
	// Tilt rolls the path about its tangent at this point, in degrees.
	Tilt float32 `yaml:"tilt,omitempty"`
}

Path3DPoint is one curve point with handles and tilt.

type PathAgentArrivedEvent

type PathAgentArrivedEvent struct {
	ObjectID string
	X, Y     float32
	TargetX  float32
	TargetY  float32
}

PathAgentArrivedEvent is emitted with "path_agent.arrived" when a path_agent reaches its navigation target.

type PathAgentControllerSnapshot

type PathAgentControllerSnapshot struct {
	Enabled   bool    `yaml:"enabled" json:"enabled"`
	HasTarget bool    `yaml:"hasTarget,omitempty" json:"hasTarget,omitempty"`
	TargetX   float32 `yaml:"targetX,omitempty" json:"targetX,omitempty"`
	TargetY   float32 `yaml:"targetY,omitempty" json:"targetY,omitempty"`
	VelocityX float32 `yaml:"velocityX,omitempty" json:"velocityX,omitempty"`
	VelocityY float32 `yaml:"velocityY,omitempty" json:"velocityY,omitempty"`
	State     string  `yaml:"state,omitempty" json:"state,omitempty"`
}

PathAgentControllerSnapshot is the serializable state of a "path_agent" controller.

type PathAgentRuntimeState

type PathAgentRuntimeState struct {
	Enabled   bool
	State     pathfind.NavAgentState
	IsMoving  bool
	HasTarget bool
	TargetX   float32
	TargetY   float32
	VelocityX float32
	VelocityY float32
}

PathAgentRuntimeState is the readable runtime state of an object's "path_agent" controller.

type PathPoint2D

type PathPoint2D struct {
	// X is the anchor horizontal coordinate in object-local space.
	X float64 `yaml:"x" json:"x"`
	// Y is the anchor vertical coordinate in object-local space.
	Y float64 `yaml:"y" json:"y"`
	// InX is the incoming control handle horizontal offset relative to X.
	InX float64 `yaml:"inX" json:"inX"`
	// InY is the incoming control handle vertical offset relative to Y.
	InY float64 `yaml:"inY" json:"inY"`
	// OutX is the outgoing control handle horizontal offset relative to X.
	OutX float64 `yaml:"outX" json:"outX"`
	// OutY is the outgoing control handle vertical offset relative to Y.
	OutY float64 `yaml:"outY" json:"outY"`
}

PathPoint2D is one control point of a 2D cubic Bézier path in an object's local coordinate space, used by FieldBezierPoints component fields (such as the built-in "path2d" component). InX/InY and OutX/OutY are cubic handle offsets relative to (X, Y).

func ParseBezierPoints

func ParseBezierPoints(v any) ([]PathPoint2D, error)

ParseBezierPoints converts a component field value ([]PathPoint2D or decoded YAML sequence of maps) into a validated []PathPoint2D.

func (PathPoint2D) MarshalYAML

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

MarshalYAML encodes PathPoint2D as a compact deterministic flow mapping with fixed key order {x, y, inX, inY, outX, outY}.

type PhysicsDebugShape2D

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

func ExtractPhysicsDebug2D(o *ObjectDoc, world *math2d.Affine) []PhysicsDebugShape2D

ExtractPhysicsDebug2D extracts any 2D collider and trigger shapes from o at its current transform for debug drawing.

type PhysicsDebugShape3D

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

func ExtractPhysicsDebug3D(o *ObjectDoc) []PhysicsDebugShape3D

ExtractPhysicsDebug3D extracts any 3D collider and trigger shapes from o using its local transform.

func ExtractPhysicsDebug3DAt

func ExtractPhysicsDebug3DAt(o *ObjectDoc, world math3d.Transform) []PhysicsDebugShape3D

ExtractPhysicsDebug3DAt extracts any 3D collider and trigger shapes from o at the given composed world transform.

func ExtractPhysicsDebug3DAtWithResolver

func ExtractPhysicsDebug3DAtWithResolver(o *ObjectDoc, world math3d.Transform, resolver AssetResolver) []PhysicsDebugShape3D

ExtractPhysicsDebug3DAtWithResolver 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

type PhysicsLayerDef struct {
	Name string
	Bit  int
}

PhysicsLayerDef maps one human-readable collision layer name to a bit index in [0, 31].

type PhysicsLayerTable

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

func MustPhysicsLayerTable(defs []PhysicsLayerDef) *PhysicsLayerTable

MustPhysicsLayerTable is NewPhysicsLayerTable for tests and setup code; it panics on error.

func NewPhysicsLayerTable

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 (*PhysicsLayerTable) Bit

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 (*PhysicsLayerTable) Mask2D

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 (*PhysicsLayerTable) Mask3D

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 (*PhysicsLayerTable) Names

func (t *PhysicsLayerTable) Names() []string

Names returns all declared layer names in ascending order.

type PhysicsMaterialResolver

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

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
	// CharacterBodies2D maps object IDs carrying the built-in "platform" component to their 2D CharacterBody.
	CharacterBodies2D map[string]*physics.CharacterBody
	// 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

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 (*PhysicsScene) HasPhysics

func (ps *PhysicsScene) HasPhysics() bool

HasPhysics reports whether ps contains at least one 2D or 3D body, collider, or trigger.

func (*PhysicsScene) Step

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 (*PhysicsScene) SyncSpriteColliders

func (ps *PhysicsScene) SyncSpriteColliders()

SyncSpriteColliders refreshes every 2D collider2d and trigger2d configured with shape: "sprite" whenever its sprite's frame, flips, scale, rotation, or position changed. Step calls this automatically before stepping physics; games querying World2D directly between steps can call it after swapping a sprite's frame or flip flags.

func (*PhysicsScene) TriggerEvents

func (ps *PhysicsScene) TriggerEvents() []PhysicsTriggerEvent

TriggerEvents returns the trigger events produced by the most recent Step call.

type PhysicsSettings

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

type PhysicsTriggerEvent struct {
	Kind      PhysicsTriggerEventKind
	TriggerID string
	BodyID    string
	Is3D      bool
}

PhysicsTriggerEvent records one trigger overlap transition emitted during PhysicsScene.Step.

type PhysicsTriggerEventKind

type PhysicsTriggerEventKind int

PhysicsTriggerEventKind 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 (PhysicsTriggerEventKind) String

func (k PhysicsTriggerEventKind) String() string

String returns "enter", "stay", or "exit".

type PlatformControllerSnapshot

type PlatformControllerSnapshot struct {
	Enabled      bool                          `yaml:"enabled" json:"enabled"`
	VX           float32                       `yaml:"vx,omitempty" json:"vx,omitempty"`
	VY           float32                       `yaml:"vy,omitempty" json:"vy,omitempty"`
	Grounded     bool                          `yaml:"grounded,omitempty" json:"grounded,omitempty"`
	BodyGrounded bool                          `yaml:"bodyGrounded,omitempty" json:"bodyGrounded,omitempty"`
	OnCeiling    bool                          `yaml:"onCeiling,omitempty" json:"onCeiling,omitempty"`
	OnLeftWall   bool                          `yaml:"onLeftWall,omitempty" json:"onLeftWall,omitempty"`
	OnRightWall  bool                          `yaml:"onRightWall,omitempty" json:"onRightWall,omitempty"`
	WasGrounded  bool                          `yaml:"wasGrounded,omitempty" json:"wasGrounded,omitempty"`
	SimPrevJump  bool                          `yaml:"simPrevJump,omitempty" json:"simPrevJump,omitempty"`
	Controller   platformer.ControllerSnapshot `yaml:"controller" json:"controller"`
}

PlatformControllerSnapshot is the serializable state of a "platform" controller.

type PlatformJumpedEvent

type PlatformJumpedEvent struct {
	ObjectID string
	Kind     platformer.JumpKind
	X, Y     float32
	VX, VY   float32
}

PlatformJumpedEvent is emitted with "platform.jumped" when a platform object starts a ground or wall jump.

type PlatformLandedEvent

type PlatformLandedEvent struct {
	ObjectID string
	X, Y     float32
}

PlatformLandedEvent is emitted with "platform.landed" when a platform object transitions from airborne to grounded.

type PlatformRuntimeState

type PlatformRuntimeState struct {
	Enabled     bool
	IsOnFloor   bool
	Grounded    bool
	IsMoving    bool
	VX, VY      float32
	WallSide    int
	WallSliding bool
	InputLocked bool
	LastJump    platformer.JumpKind
	JumpCut     bool
}

PlatformRuntimeState is the readable runtime state of an object's "platform" controller.

type PlatformerConfigResolver

type PlatformerConfigResolver interface {
	PlatformerConfig(path string) (platformer.Config, error)
}

PlatformerConfigResolver may optionally be implemented by an AssetResolver to load .platformer.yaml files named by platform.config. When not implemented, Build reads the file through FileResolver (such as FSAssets) and decodes it with platformer.ParseConfig.

type Point

type Point struct {
	// X is the horizontal coordinate in object-local space.
	X float64 `yaml:"x" json:"x"`
	// Y is the vertical coordinate in object-local space.
	Y float64 `yaml:"y" json:"y"`
}

Point is a 2D point in an object's local coordinate space, used by FieldPoint and FieldPolygon component fields.

func ParsePoint

func ParsePoint(v any) (Point, error)

ParsePoint converts a component field value (Point or decoded YAML map) to a validated Point.

func ParsePolygon

func ParsePolygon(v any) ([]Point, error)

ParsePolygon converts a component field value ([]Point or decoded YAML sequence of maps) to a validated []Point.

func (Point) MarshalYAML

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

MarshalYAML encodes Point with deterministic key order matching YAML map decoding ("x", "y").

type PointerInput

type PointerInput struct {
	X, Y         float32
	Pressed      bool
	JustPressed  bool
	JustReleased bool
}

PointerInput describes the world-space pointer state read by drag_drop components during BuiltScene.Step.

type ProjectionKind

type ProjectionKind string

ProjectionKind 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

type Rect struct {
	// X is the left edge coordinate in object-local space.
	X float64 `yaml:"x" json:"x"`
	// Y is the top edge coordinate in object-local space.
	Y float64 `yaml:"y" json:"y"`
	// Width is the horizontal extent in object-local space (non-negative).
	Width float64 `yaml:"width" json:"width" schema:"minimum=0"`
	// Height is the vertical extent in object-local space (non-negative).
	Height float64 `yaml:"height" json:"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

func ParseRect(v any) (Rect, error)

ParseRect converts a component field value (Rect or decoded YAML map) to a validated Rect.

func (Rect) MarshalYAML

func (r Rect) MarshalYAML() (any, error)

MarshalYAML encodes Rect with deterministic alphabetical key order matching YAML map decoding ("height", "width", "x", "y").

type ReflectionProbeDoc

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 (*ReflectionProbeDoc) Clone

Clone returns a deep copy of p, or nil when p is nil.

func (*ReflectionProbeDoc) EffectiveBoxProjection

func (p *ReflectionProbeDoc) EffectiveBoxProjection() bool

EffectiveBoxProjection reports whether parallax-corrected box projection is enabled, defaulting to true when nil.

func (*ReflectionProbeDoc) EffectiveCenter

func (p *ReflectionProbeDoc) EffectiveCenter() [3]float32

EffectiveCenter returns p.Center, defaulting to [0, 0, 0] when nil.

func (*ReflectionProbeDoc) EffectiveIntensity

func (p *ReflectionProbeDoc) EffectiveIntensity() float32

EffectiveIntensity returns p.Intensity, defaulting to 1 when nil.

func (*ReflectionProbeDoc) EffectiveResolution

func (p *ReflectionProbeDoc) EffectiveResolution() int

EffectiveResolution returns p.Resolution, defaulting to DefaultReflectionProbeResolution (64) when 0.

func (*ReflectionProbeDoc) EffectiveSize

func (p *ReflectionProbeDoc) EffectiveSize() [3]float32

EffectiveSize returns p.Size, defaulting to [10, 10, 10] when nil or all zero.

func (*ReflectionProbeDoc) LocalBounds

func (p *ReflectionProbeDoc) LocalBounds() (lo, hi [3]float32)

LocalBounds returns the local-space min and max corners of the probe's influence box.

type ResolveOptions

type ResolveOptions struct {
	// Components, when non-nil, identifies FieldObject fields so that relative object IDs inside instanced scenes are rewritten with the instance's ID prefix (before any instance overrides are applied), and validates every component of the resolved scene (including checking that every non-empty FieldObject names an object of the resolved scene).
	Components *ComponentRegistry
}

ResolveOptions configures ResolveWith.

type RuleContext

type RuleContext struct {
	// Numbers are numeric values readable by expressions such as "score >= 10".
	Numbers map[string]float64
	// Strings are string values readable by expressions such as `mode == "combat"`.
	Strings map[string]string
	// Bools are boolean values readable by expressions such as "has_key".
	Bools map[string]bool
	// Vars is an optional flow.Vars store whose declared global variables (and per-object self.*
	// variables) are readable by expressions and writable by the game target's vars.set and vars.add handlers.
	Vars *flow.Vars
	// Funcs supplies optional custom functions callable from expressions (such as has_item("key")).
	Funcs map[string]expr.Func
}

RuleContext supplies the values and functions that connection When expressions (ConnectionDoc.When) and expression-valued connection arguments read, plus the optional flow.Vars store mutated by the built-in game target's vars.set and vars.add handlers.

A game hands it to Signals.SetRuleContext (or ConnectWith) and may mutate the maps or Vars store between events: Signals reads them each time an event fires.

type SSAODoc

type SSAODoc struct {
	// Radius is the world-space sampling radius; must be finite and non-negative.
	Radius float32 `yaml:"radius,omitempty" schema:"minimum=0"`
	// Intensity scales the occlusion; must be finite and non-negative.
	Intensity float32 `yaml:"intensity,omitempty" schema:"minimum=0"`
	// Samples is the number of samples per pixel; must be non-negative, and 0 leaves it to the renderer.
	Samples int `yaml:"samples,omitempty" schema:"minimum=0"`
}

SSAODoc configures screen-space ambient occlusion (EnvironmentDoc.SSAO). The scene format records it for the renderer, which does not read it yet.

type SSRDoc

type SSRDoc struct {
	// Enabled turns screen-space reflections on or off; nil defaults to true when SSR is present.
	Enabled *bool `yaml:"enabled,omitempty"`
	// MaxSteps is the most ray-march steps per pixel; must be 0 or in [4, 128], and 0 leaves it to the renderer (default 32).
	MaxSteps int `yaml:"maxSteps,omitempty" schema:"minimum=0,maximum=128"`
	// FadeIn fades reflections in near the ray origin; must be finite and non-negative.
	FadeIn float32 `yaml:"fadeIn,omitempty" schema:"minimum=0"`
	// FadeOut fades reflections out toward the ray's end and screen edges; must be finite and non-negative.
	FadeOut float32 `yaml:"fadeOut,omitempty" schema:"minimum=0"`
	// DepthTolerance is how far behind a surface a ray may pass and still hit it; must be finite and non-negative.
	DepthTolerance float32 `yaml:"depthTolerance,omitempty" schema:"minimum=0"`
	// RoughnessCutoff is the maximum surface roughness in [0, 1] that receives SSR; nil defaults to 0.5.
	RoughnessCutoff *float32 `yaml:"roughnessCutoff,omitempty" schema:"minimum=0,maximum=1"`
}

SSRDoc configures screen-space reflection ray marching (EnvironmentDoc.SSR).

func (*SSRDoc) Clone

func (s *SSRDoc) Clone() *SSRDoc

Clone returns a deep copy of s, or nil when s is nil.

func (*SSRDoc) EffectiveDepthTolerance

func (s *SSRDoc) EffectiveDepthTolerance() float32

EffectiveDepthTolerance returns s.DepthTolerance, defaulting to 0.15 when zero or nil.

func (*SSRDoc) EffectiveEnabled

func (s *SSRDoc) EffectiveEnabled() bool

EffectiveEnabled reports whether SSR is active (true when s is non-nil and Enabled is nil or true).

func (*SSRDoc) EffectiveMaxSteps

func (s *SSRDoc) EffectiveMaxSteps() int

EffectiveMaxSteps returns s.MaxSteps, defaulting to 32 when zero or nil.

func (*SSRDoc) EffectiveRoughnessCutoff

func (s *SSRDoc) EffectiveRoughnessCutoff() float32

EffectiveRoughnessCutoff returns s.RoughnessCutoff, defaulting to 0.5 when nil.

type SceneDiff

type SceneDiff struct {
	// Added lists the objects only the new scene has, in its document order.
	Added []ObjectChange
	// Removed lists the objects only the old scene has, in its document order.
	Removed []ObjectChange
	// Changed lists the objects whose contents differ, in the old scene's document order.
	Changed []ObjectChange
}

SceneDiff groups scene changes by kind for callers that prefer categorized results.

func DiffScenes

func DiffScenes(oldDoc, newDoc *SceneDoc) SceneDiff

DiffScenes compares two scenes as DiffObjects does and groups the changes by kind, for hot-reload integrations that inspect a saved scene before applying it.

type SceneDoc

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.
	NavMesh string `yaml:"navMesh,omitempty"`
	// Lightmaps optionally names the scene's baked lightmap sidecar file by its slash-separated path from the project root, such as "levels/level1.lightmaps.yaml", written by `game bake lightmaps`. In a scene that inherits another, a Lightmaps set replaces the base's.
	Lightmaps string `yaml:"lightmaps,omitempty"`
	// 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"`
	// Modulate is an optional hex color ("#rrggbb" or "#rrggbbaa") multiplying every layer of the scene; empty leaves the scene untinted.
	Modulate string `yaml:"modulate,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"`
	// ParameterValues supplies values for parameters declared by the base scene named in Inherits; it requires Inherits. Resolve applies them before Overrides. Version 2.
	ParameterValues map[string]any `yaml:"parameterValues,omitempty"`
	// Parameters declares the typed values exposed by this reusable scene.
	Parameters []SceneParameter `yaml:"parameters,omitempty"`
	// Partition optionally declares how a large scene is split into streamed spatial cells.
	Partition *Partition `yaml:"partition,omitempty"`
	// DataLayers optionally declares named data layers that group objects to load, pause, and activate at run time, or marks editor-only layers stripped from build output.
	DataLayers []DataLayerDoc `yaml:"dataLayers,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, 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 ApplyPersistence

func ApplyPersistence(doc *SceneDoc, p *save.Persistence, scenePath string) *SceneDoc

ApplyPersistence returns a copy of doc with persisted object state for scenePath applied from p. Objects marked Destroyed in p are omitted along with their descendants and any connections referencing them; moved objects receive their persisted X, Y, PosZ and Rotation overrides; and persisted component field overrides are merged into each object's Components map.

The input doc is never mutated, so a game can keep one parsed SceneDoc and rebuild it on every scene re-entry with current Persistence state.

func Parse

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.

Example

Parse reads a scene file and refuses unknown fields; Encode writes it back in a fixed form, so loading and saving a scene leaves it unchanged.

package main

import (
	"bytes"
	"fmt"

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

const room = `# yaml-language-server: $schema=https://nsgo.games/schemas/scene.v1.json
version: 1
name: cave
layers:
  - name: props
    objects:
      - id: chest
        x: 120
        "y": 64
        sprite:
          atlas: props
          frame: chest
      - id: door
        x: 200
        "y": 64
        sprite:
          atlas: props
          frame: door
`

func main() {
	doc, err := sceneformat.Parse([]byte(room))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(doc.Name, len(doc.Layers[0].Objects))
	out, err := sceneformat.Encode(doc)
	fmt.Println(err, bytes.Equal(out, []byte(room)))

	_, err = sceneformat.Parse([]byte("version: 1\nname: cave\ncolour: red\n"))
	fmt.Println(err != nil)
}
Output:
cave 2
<nil> true
true

func ParseWith

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

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 ResolveWith

func ResolveWith(doc *SceneDoc, scenes SceneResolver, opts ResolveOptions) (*SceneDoc, error)

ResolveWith is Resolve with options. When opts.Components is non-nil, every non-empty FieldObject field on an instanced scene's objects is rewritten with the instance's ID prefix before instance overrides are applied, and the resolved scene's components are validated with ValidateComponents.

func (*SceneDoc) Clone

func (doc *SceneDoc) Clone() *SceneDoc

Clone 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 (*SceneDoc) RefersToScenes

func (doc *SceneDoc) RefersToScenes() bool

RefersToScenes 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 SceneParameter

type SceneParameter struct {
	// Name identifies the parameter; unique within the scene and not blank.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Type is the parameter's type, one of the Parameter constants.
	Type ParameterType `yaml:"type" schema:"required,enum=float|int|bool|string|color|vec2|vec3|asset"`
	// Default is the value an instance gets when it supplies none; it must have Type.
	Default any `yaml:"default" schema:"required"`
	// Description tells an author what the parameter changes.
	Description string `yaml:"description,omitempty"`
	// Bind lists the fields the parameter supplies; at least one.
	Bind []ParameterBinding `yaml:"bind" schema:"required,minItems=1"`
}

SceneParameter declares a value exposed by a reusable scene (SceneDoc.Parameters).

type SceneResolver

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 ScreenNotifier

type ScreenNotifier struct {
	scene.ScreenNotifier
	// Object is the built object carrying the "on_screen" component.
	Object *BuiltObject
	// PauseParticles stops the object's particle emitter updates while off-screen.
	PauseParticles bool
	// PauseSkeleton stops the object's skeletal rig updates while off-screen.
	PauseSkeleton bool
	// contains filtered or unexported fields
}

ScreenNotifier is the runtime state of one built-in "on_screen" component on a built object. BuiltScene.Update steps it against the camera views (its own camera's plus any extra views passed to UpdateWithViews), fires the component's entered and exited events through ScreenSignals, and pauses the object's particle emitter or skeletal rig while the notifier is off-screen.

type ShadowSettings

type ShadowSettings struct {
	// Bias is the depth bias that keeps a surface from shadowing itself; must be finite and non-negative, and 0 leaves it to the renderer.
	Bias float32 `yaml:"bias,omitempty" schema:"minimum=0"`
	// NormalBias offsets the shadow lookup along the surface normal; must be finite and non-negative, and 0 leaves it to the renderer.
	NormalBias float32 `yaml:"normalBias,omitempty" schema:"minimum=0"`
	// Opacity is how dark the shadow is, in [0, 1]; 0 leaves it to the renderer.
	Opacity float32 `yaml:"opacity,omitempty" schema:"minimum=0,maximum=1"`
	// Softness blurs the shadow's edge; must be finite and non-negative. Not read by the renderer yet.
	Softness float32 `yaml:"softness,omitempty" schema:"minimum=0"`
	// Cascades is the number of shadow cascades of a directional light, in [0, 4]; 0 leaves it to the renderer. Not read by the renderer yet.
	Cascades int `yaml:"cascades,omitempty" schema:"minimum=0,maximum=4"`
	// MaxDistance is the distance from the camera beyond which a directional light casts no shadow; the renderer fits the light's shadow map to the scene within it. Must be finite and non-negative, and 0 shadows the whole visible scene.
	MaxDistance float32 `yaml:"maxDistance,omitempty" schema:"minimum=0"`
}

ShadowSettings configures per-light shadow quality and bias (LightDoc.Shadow). scenemodel.Renderer reads Bias, NormalBias, Opacity and MaxDistance; it does not read Softness and Cascades yet. A zero value leaves the field to the renderer.

type Signals

type Signals struct {
	// contains filtered or unexported fields
}

Signals dispatches the events a scene's objects emit to the handlers its connections name and to the listeners Listen adds. Connect makes one, and SpawnConnected makes one whose events also address the entities the objects were spawned as. Emit runs the handlers and listeners 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. Update advances the scene's built-in timer components on the same clock. It is not safe for concurrent use: emit from the goroutine that runs the game's update.

func Connect

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. Use Add (or BuiltScene.Instantiate) and Remove (or BuiltScene.Free) to add or remove objects and connections in place without dropping pending enqueued events or once-connection state for the rest of the scene.

Example

A scene file connects a button's pressed event to a door's open handler; the game registers what the components do once, and Connect wires every connection the file declares.

package main

import (
	"fmt"

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

func main() {
	reg := sceneformat.NewComponentRegistry()
	reg.MustRegister(sceneformat.ComponentType{
		Name:   "button",
		Events: []sceneformat.Event{{Name: "pressed", Doc: "The player pressed the button."}},
	})
	reg.MustRegister(sceneformat.ComponentType{
		Name: "door",
		Handlers: []sceneformat.Handler{{
			Name:   "open",
			Params: []sceneformat.Field{{Name: "speed", Kind: sceneformat.FieldFloat, Default: 1.0}},
			Func: func(c sceneformat.Call) {
				fmt.Printf("%s opens %s at speed %v\n", c.Source.ID, c.Target.ID, c.Args["speed"])
			},
		}},
	})

	doc, err := sceneformat.ParseWith([]byte(`version: 1
layers:
  - name: props
    objects:
      - {id: button, components: {button: {}}}
      - {id: door, components: {door: {}}}
connections:
  - {from: button, event: pressed, to: door, handler: open, args: {speed: 2}}
`), sceneformat.ParseOptions{File: "hall.scene.yaml", Components: reg})
	if err != nil {
		fmt.Println(err)
		return
	}
	signals, err := sceneformat.Connect(doc, reg, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	// The game's input code emits the event when the player presses the button.
	fmt.Println(signals.Emit("button", "pressed", nil))

	_, err = sceneformat.ParseWith([]byte(`version: 1
layers:
  - name: props
    objects:
      - {id: button, components: {button: {}}}
      - {id: door, components: {door: {}}}
connections:
  - {from: button, event: pressed, to: door, handler: opne}
`), sceneformat.ParseOptions{File: "hall.scene.yaml", Components: reg})
	fmt.Println(err)
}
Output:
button opens door at speed 2
<nil>
hall.scene.yaml:8:55: sceneformat: connection 0 ("button" pressed -> "door" opne): no registered component of object "door" declares handler "opne" (it has: door.open)

func ConnectWith

func ConnectWith(doc *SceneDoc, reg *ComponentRegistry, ctx any, opts ConnectOptions) (*Signals, error)

ConnectWith is Connect with optional variable declarations, custom functions, and built-in game action hooks (ConnectOptions). When opts.Vars or opts.VarsDoc is provided, every When condition, expression-valued argument, and game vars.set/vars.add connection is type-checked before ConnectWith returns.

func SpawnConnected

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 via SpawnEntitiesWith with reg (so every registered ComponentType.Spawn runs on its entity and rolls back on error), 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.

Example

SpawnConnected spawns a scene's objects as entities and connects them; events enqueued during an update step run when the step flushes them, in order, and the handlers see the entities at both ends.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/entities"
	"github.com/nsgo-dev/game/pkg/sceneformat"
)

func main() {
	reg := sceneformat.NewComponentRegistry()
	reg.MustRegister(sceneformat.ComponentType{
		Name:   "button",
		Events: []sceneformat.Event{{Name: "pressed"}},
	})
	reg.MustRegister(sceneformat.ComponentType{
		Name: "door",
		Handlers: []sceneformat.Handler{{
			Name: "open",
			Func: func(c sceneformat.Call) {
				fmt.Printf("%s opens %s (entity %v), press %v\n", c.Source.ID, c.Target.ID, c.TargetEntity.Index(), c.Payload)
			},
		}},
	})
	doc, err := sceneformat.ParseWith([]byte(`version: 1
layers:
  - name: props
    objects:
      - {id: button, components: {button: {}}}
      - {id: door, components: {door: {}}}
connections:
  - {from: button, event: pressed, to: door, handler: open}
`), sceneformat.ParseOptions{Components: reg})
	if err != nil {
		fmt.Println(err)
		return
	}
	world := entities.NewWorld()
	spawned, signals, err := sceneformat.SpawnConnected(doc, world, reg, nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	// During the step, the game's input code enqueues the presses instead of running the handlers at once.
	_ = signals.EnqueueEntity(spawned["button"], "pressed", 1)
	_ = signals.EnqueueEntity(spawned["button"], "pressed", 2)
	fmt.Println("pending:", signals.Pending())
	// At the end of the step, such as at the end of game.Loop's Update, the queue runs.
	fmt.Println(signals.Flush())
}
Output:
pending: 2
button opens door (entity 1), press 1
button opens door (entity 1), press 2
<nil>

func (*Signals) Add

func (s *Signals) Add(objects []*ObjectDoc, conns []ConnectionDoc) error

Add registers objects (and all of their descendants) and connects conns in place, keeping every pending enqueued event, once-connection state, timer, and listener of existing objects intact.

Add validates every added object's components and every connection in conns (which may connect added objects to each other or to objects already in s) against the registry passed to Connect before mutating s; on error s is left unchanged.

func (*Signals) AddEntities

func (s *Signals) AddEntities(objects []*ObjectDoc, conns []ConnectionDoc, spawned map[string]entities.Entity) error

AddEntities is Add with entity mappings for a Signals made by SpawnConnected. Each added object's entity is recorded so EmitEntity, EnqueueEntity, and Call.SourceEntity/TargetEntity resolve it. When s was created with SpawnConnected (s.world != nil), every added object with an entry in spawned is mapped; passing nil behaves like Add.

func (*Signals) Animator

func (s *Signals) Animator(objectID string) AnimatorController

Animator returns the AnimatorController bound to objectID on s, or nil when none is bound.

func (*Signals) BindAnimator

func (s *Signals) BindAnimator(objectID string, ctrl AnimatorController) error

BindAnimator attaches ctrl as the runtime AnimatorController for objectID so the built-in "animator" component's setState and trigger handlers drive it. Passing a nil ctrl unbinds objectID. It returns an error when s is nil or the scene has no object with ID objectID.

func (*Signals) Emit

func (s *Signals) Emit(from, event string, payload any) error

Emit 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, and then the listeners Listen added for it, in the order they were added. 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 or listener runs the first time only. An event no connection or listener 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. It also returns the errors of the connections' When expressions it could not evaluate (Signals.SetRuleContext), after running the rest: each such connection is skipped, as one whose condition is false is.

func (*Signals) EmitEntity

func (s *Signals) EmitEntity(e entities.Entity, event string, payload any) error

EmitEntity 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 (*Signals) Enqueue

func (s *Signals) Enqueue(from, event string, payload any) error

Enqueue 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 (*Signals) EnqueueEntity

func (s *Signals) EnqueueEntity(e entities.Entity, event string, payload any) error

EnqueueEntity 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 (*Signals) Entity

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 (*Signals) Flush

func (s *Signals) Flush() error

Flush runs the events enqueued before it began, in enqueue order, each as Emit would run it, with the runs of deferred listeners in their place in the order. Events their handlers enqueue, and the runs deferred listeners schedule, 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. Otherwise it runs every event and returns the When expression errors Emit would have returned for them, joined.

func (*Signals) IsHidden

func (s *Signals) IsHidden(objectID string) bool

IsHidden reports whether objectID is currently hidden via scene.hide (or scene.set visible=false).

func (*Signals) Listen

func (s *Signals) Listen(from, event string, fn func(Call), opts ListenOptions) (stop func(), err error)

Listen calls fn when the object with ID from emits event, written as Emit takes it: a bare name such as "pressed", or "button.pressed" to say which component when several of the object's components declare it. An empty from listens to every object of the scene that declares the event, so game systems that no scene file should name, such as audio, analytics and achievements, hear every object without a connection per scene. The listener runs after the scene's connections for the same event, in the order Listen added it among the event's listeners. Its Call carries the Signals, the context given to Connect, the source object, the event's component and name, the payload and, when SpawnConnected made the Signals, the source's entity; Target, Component, Handler, Args and TargetEntity stay unset, a listener not being a connection.

Listen checks from and event as Emit does and refuses an unknown object or event at the call, so a misspelt name fails at once; an empty from refuses an event no object of the scene declares. The returned stop ends the subscription: it is idempotent, and safe to call from inside a handler or listener. A listener added while an event runs takes effect from the next one, and a listener on an object never runs for it once its entity has been destroyed (SpawnConnected), as connections do.

func (*Signals) Pending

func (s *Signals) Pending() int

Pending returns how many events Enqueue holds for the next Flush.

func (*Signals) Remove

func (s *Signals) Remove(ids ...string)

Remove removes every object named by ids from s in place, unwiring all connections from or to them, dropping their listeners, timers, animators, entity mappings, and any pending queued events they raised, while keeping pending events and once-connection state for all remaining objects intact. Removing an unknown or already-removed ID is a safe no-op.

func (*Signals) SetBuiltScene

func (s *Signals) SetBuiltScene(built *BuiltScene, resolver AssetResolver)

SetBuiltScene attaches built (and an optional resolver override) for built-in scene.* handlers (scene.destroy, scene.spawn, scene.set, scene.show, scene.hide). Passing a *BuiltScene as Call.Context to Connect/ConnectWith also enables them automatically.

func (*Signals) SetGameActions

func (s *Signals) SetGameActions(actions GameActions)

SetGameActions configures the host callbacks for the built-in "game" target (sound.play, scene.change, save.slot) and optional BuiltScene/Resolver overrides for built-in scene.* handlers.

func (*Signals) SetRuleContext

func (s *Signals) SetRuleContext(ctx RuleContext)

SetRuleContext sets the values, flow.Vars store, and custom functions that connections' When expressions and expression-valued Args read (ConnectionDoc.When). Signals keeps ctx's maps and Vars pointer, not copies, so a game changes a value by mutating them, and each event's conditions read the values as they are when it fires.

func (*Signals) SetVars

func (s *Signals) SetVars(v *flow.Vars)

SetVars attaches a flow.Vars store to s so When conditions and expression-valued Args can read its declared global and per-object self variables, and the built-in game target's vars.set and vars.add handlers can mutate it.

func (*Signals) Update

func (s *Signals) Update(dt time.Duration) error

Update advances the scene's built-in timer components (RegisterTimerComponent) by dt of game time and enqueues the timeout event of each that reaches zero, in document order, for the next Flush to dispatch: a one-shot timer fires once and stops, a repeating one carries the overshoot into the next period so it does not drift, and one with seconds 0 fires once per Update. The timer of an object whose entity has been destroyed (SpawnConnected) stops. Call it once per update step, before Flush, such as in game.Loop's Update; the queued timeouts run at that Flush, so timer events stay in step with the events the step raised.

Update returns an error, and advances nothing, when a handler or listener calls it: timers then advance only from the game's update, never inside an event's handlers.

type SkeletonResolver

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

type SkyDoc struct {
	// Kind selects SkyColor ("color"), SkyGradient ("gradient"), SkyHDR ("hdr"), SkyProcedural ("procedural") or SkyPhysical ("physical").
	Kind SkyKind `yaml:"kind" schema:"required,enum=color|gradient|hdr|procedural|physical"`
	// 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"`
	// Top is the CSS color at the top of a procedural or physical sky. The scene format records it for sky bakers; the renderer does not read it yet.
	Top string `yaml:"top,omitempty"`
	// HorizonCurve shapes how a procedural or physical sky blends toward the horizon; must be non-negative. Recorded for sky bakers; the renderer does not read it yet.
	HorizonCurve float32 `yaml:"horizonCurve,omitempty" schema:"minimum=0"`
	// Rotation rotates the sky about the X, Y and Z axes, for example to turn a day-night cycle. Recorded for sky bakers; the renderer does not read it yet.
	Rotation [3]float32 `yaml:"rotation,omitempty"`
	// Update selects when the sky's radiance is recomputed: "automatic", "incremental" or "everyFrame"; empty leaves it to the renderer.
	Update string `yaml:"update,omitempty" schema:"enum=automatic|incremental|everyFrame"`
	// RadianceSize is the edge length in pixels of the sky's radiance cubemap, in [16, 2048]; 0 leaves it to the renderer.
	RadianceSize uint32 `yaml:"radianceSize,omitempty" schema:"maximum=2048"`
	// SunDiskScale scales the sun disk drawn in a procedural or physical sky; must be non-negative.
	SunDiskScale float32 `yaml:"sunDiskScale,omitempty" schema:"minimum=0"`
}

SkyDoc configures the 3D scene sky and IBL source (EnvironmentDoc.Sky). Version 4.

func (*SkyDoc) Clone

func (s *SkyDoc) Clone() *SkyDoc

Clone returns a deep copy of s, or nil when s is nil.

func (*SkyDoc) EffectiveColor

func (s *SkyDoc) EffectiveColor() string

EffectiveColor returns s.Color, defaulting to "#141824" when empty.

func (*SkyDoc) EffectiveGround

func (s *SkyDoc) EffectiveGround() string

EffectiveGround returns s.Ground, defaulting to "#2b2b2e" when empty.

func (*SkyDoc) EffectiveHorizon

func (s *SkyDoc) EffectiveHorizon() string

EffectiveHorizon returns s.Horizon, defaulting to "#a8b8c7" when empty.

func (*SkyDoc) EffectiveZenith

func (s *SkyDoc) EffectiveZenith() string

EffectiveZenith returns s.Zenith, defaulting to "#3d6194" when empty.

type SkyKind

type SkyKind string

SkyKind 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"
	// SkyProcedural describes an artist-tuned procedural sky (SkyDoc.Top, HorizonCurve, SunDiskScale). The scene format records it for sky bakers; the renderer draws no sky for it yet.
	SkyProcedural SkyKind = "procedural"
	// SkyPhysical describes a physically based atmospheric sky. The scene format records it for sky bakers; the renderer draws no sky for it yet.
	SkyPhysical SkyKind = "physical"
)

type SmartObjectDebug

type SmartObjectDebug struct {
	ObjectID      string
	Enabled       bool
	Tags          []string
	WorldOrigin   core.Point
	WorldRotation float64
	Slots         []SmartSlotDebug
}

SmartObjectDebug describes a resolved smart_object component in local and world space for editor overlays and handles.

func ExtractSmartObject

func ExtractSmartObject(o *ObjectDoc, world *math2d.Affine) (SmartObjectDebug, bool, error)

ExtractSmartObject resolves a "smart_object" component from o at world (or o's local transform when world is nil).

type SmartSlotDebug

type SmartSlotDebug struct {
	ID          string
	LocalOffset [2]float64
	LocalFacing float64
	Tags        []string
	Behavior    string
	Params      map[string]any
	WorldPos    core.Point
	WorldFacing float64
}

SmartSlotDebug describes one resolved smart-object slot in local and world space for editor overlays and handles.

type SmartSlotDoc

type SmartSlotDoc struct {
	// ID uniquely identifies this slot within its owning smart object.
	ID string `yaml:"id"`
	// Offset is the slot's local [x, y] position relative to the object origin.
	Offset [2]float64 `yaml:"offset,omitempty"`
	// OffsetZ is an optional local Z offset for 3D smart objects.
	OffsetZ float64 `yaml:"offsetZ,omitempty"`
	// Facing is the slot's local facing angle in radians (0 = +X, pi/2 = +Y), added to the object's rotation.
	Facing float64 `yaml:"facing,omitempty"`
	// Tags are optional slot-level gameplay activity tags.
	Tags []string `yaml:"tags,omitempty"`
	// Behavior names the interaction behavior interpreted by the game or a behavior-tree action.
	Behavior string `yaml:"behavior,omitempty"`
	// Params holds optional behavior parameters passed to the game or behavior-tree action.
	Params map[string]any `yaml:"params,omitempty"`
}

SmartSlotDoc is one authored interaction slot inside a "smart_object" scene component.

func ParseSmartSlots

func ParseSmartSlots(v any) ([]SmartSlotDoc, error)

ParseSmartSlots validates and decodes a raw component field value into a []SmartSlotDoc.

type SoundAsset

type SoundAsset struct {
	Effect   *sound.Effect
	Cue      *sound.Cue
	Resource *resource.Sound
}

SoundAsset is a resolved playable sound returned by SoundResolver for a scene emitter. Supply either Effect or Cue (if both are set, Cue takes precedence). Resource optionally provides defaults from the parsed .sound.yaml file (spatial attenuation, cone, cutoff, doppler).

func (SoundAsset) Valid

func (a SoundAsset) Valid() bool

Valid reports whether a holds at least one playable Effect or Cue.

type SoundEmitter2D

type SoundEmitter2D struct {
	Object *BuiltObject
	ID     string
	Spec   SoundEmitterSpec
	Asset  SoundAsset
	// contains filtered or unexported fields
}

SoundEmitter2D is a live 2D scene sound emitter built from ObjectDoc.Sound or components.sound. Update tracks the object's world position and velocity, culls playback outside Far so culled emitters hold no voice, and automatically restarts looping emitters when the listener returns.

func (*SoundEmitter2D) Culled

func (e *SoundEmitter2D) Culled() bool

Culled reports whether the emitter was outside its Far range on the most recent Update.

func (*SoundEmitter2D) CutoffHz

func (e *SoundEmitter2D) CutoffHz() float32

CutoffHz returns the emitter's latest computed distance low-pass cutoff in hertz (0 when bypassed).

func (*SoundEmitter2D) Play

func (e *SoundEmitter2D) Play()

Play activates the emitter so it starts on the next Update while within range.

func (*SoundEmitter2D) Playback

func (e *SoundEmitter2D) Playback() *sound.Playback2D

Playback returns the active *sound.Playback2D handle, or nil when stopped or culled outside Far.

func (*SoundEmitter2D) Playing

func (e *SoundEmitter2D) Playing() bool

Playing reports whether the emitter currently holds an active playing voice.

func (*SoundEmitter2D) Position

func (e *SoundEmitter2D) Position() math2d.Vec2

Position returns the emitter's latest world-space 2D position.

func (*SoundEmitter2D) Stop

func (e *SoundEmitter2D) Stop()

Stop stops any active playback immediately and deactivates the emitter so it holds no voice.

func (*SoundEmitter2D) Update

func (e *SoundEmitter2D) Update(listener sound.Listener2D, dt time.Duration)

Update refreshes e against listener over elapsed time dt: updates world position and velocity, stops and releases playback outside Far, restarts looping emitters on re-entry, and updates live pan, volume, Doppler pitch, and distance low-pass cutoff.

func (*SoundEmitter2D) Velocity

func (e *SoundEmitter2D) Velocity() math2d.Vec2

Velocity returns the emitter's latest estimated world-space 2D velocity.

type SoundEmitter3D

type SoundEmitter3D struct {
	Node  *scene3d.Node
	ID    string
	Spec  SoundEmitterSpec
	Asset SoundAsset
	// contains filtered or unexported fields
}

SoundEmitter3D is a live 3D scene sound emitter attached to a scene3d.Node (under scene3d.AttachmentSoundEmitter). Update follows the node's world transform, culls playback beyond Far so culled emitters hold no voice, and restarts looping emitters on re-entry.

func (*SoundEmitter3D) Culled

func (e *SoundEmitter3D) Culled() bool

Culled reports whether the emitter was outside its Far range on the most recent Update.

func (*SoundEmitter3D) CutoffHz

func (e *SoundEmitter3D) CutoffHz() float32

CutoffHz returns the emitter's latest computed distance low-pass cutoff in hertz (0 when bypassed).

func (*SoundEmitter3D) Play

func (e *SoundEmitter3D) Play()

Play activates the 3D emitter so it starts on the next Update while within range.

func (*SoundEmitter3D) Playback

func (e *SoundEmitter3D) Playback() *sound.Playback3D

Playback returns the active *sound.Playback3D handle, or nil when stopped or culled outside Far.

func (*SoundEmitter3D) Playing

func (e *SoundEmitter3D) Playing() bool

Playing reports whether the emitter currently holds an active playing voice.

func (*SoundEmitter3D) Position

func (e *SoundEmitter3D) Position() sound.Vec3

Position returns the emitter's latest world-space 3D position.

func (*SoundEmitter3D) Stop

func (e *SoundEmitter3D) Stop()

Stop stops any active playback immediately and deactivates the emitter so it holds no voice.

func (*SoundEmitter3D) Update

func (e *SoundEmitter3D) Update(listener sound.Listener3D, dt time.Duration)

Update refreshes e against listener over elapsed time dt: reads Node.WorldTransform, estimates velocity for Doppler, stops and releases playback outside Far, restarts looping emitters on re-entry, and updates live volume, pan, Doppler pitch, and distance cutoff. Call Mixer.SetListener3D(listener) before or via SoundScene3D.Update so the mixer shares listener.

func (*SoundEmitter3D) Velocity

func (e *SoundEmitter3D) Velocity() sound.Vec3

Velocity returns the emitter's latest estimated world-space 3D velocity.

type SoundEmitterDoc

type SoundEmitterDoc struct {
	// Sound is the sound resource the emitter plays, a slash-separated path relative to the project root.
	Sound string `yaml:"sound"`
	// Autoplay starts the emitter when the scene loads.
	Autoplay bool `yaml:"autoplay,omitempty"`
	// Loop repeats the sound until the emitter stops.
	Loop bool `yaml:"loop,omitempty"`
	// Near is the distance in world units up to which the emitter plays at full volume; 0 uses the sound resource or listener default.
	Near float32 `yaml:"near,omitempty" schema:"minimum=0"`
	// Far is the listener distance in world units beyond which the emitter is culled; 0 sets no limit.
	Far float32 `yaml:"far,omitempty" schema:"minimum=0"`
	// FarCutoffHz is the low-pass cutoff in hertz the emitter reaches at Far; 0 applies no distance filter.
	FarCutoffHz float32 `yaml:"farCutoffHz,omitempty" schema:"minimum=0"`
	// Doppler shifts the pitch with the emitter's velocity relative to the listener.
	Doppler bool `yaml:"doppler,omitempty"`
	// Bus optionally overrides the mixer bus the emitter plays on.
	Bus string `yaml:"bus,omitempty"`
	// Volume scales the emitter's playback volume in [0, 1]; 0 uses 1.
	Volume float32 `yaml:"volume,omitempty" schema:"minimum=0,maximum=1"`
}

SoundEmitterDoc places a looping or one-shot sound resource in a scene.

type SoundEmitterSpec

type SoundEmitterSpec struct {
	Sound       string
	Autoplay    bool
	Loop        bool
	Near        float32
	Far         float32
	FarCutoffHz float32
	Doppler     bool
	Bus         string
	Volume      float32
}

SoundEmitterSpec is the validated, resolved configuration of an object's sound emitter, whether authored via ObjectDoc.Sound or via the registered "sound" component.

func ExtractSoundEmitter

func ExtractSoundEmitter(o *ObjectDoc) (SoundEmitterSpec, bool, error)

ExtractSoundEmitter extracts and validates the sound emitter configured on o (either via ObjectDoc.Sound or via o.Components["sound"]). It returns ok=false when o has neither.

type SoundMap

type SoundMap map[string]SoundAsset

SoundMap is a SoundResolver backed by a map of project-relative sound paths to SoundAsset values.

func (SoundMap) Sound

func (m SoundMap) Sound(path string) (SoundAsset, error)

Sound returns the resolved SoundAsset for path, or an error when absent or empty.

type SoundResolver

type SoundResolver interface {
	Sound(path string) (SoundAsset, error)
}

SoundResolver may optionally be implemented by an AssetResolver to load sound emitters referenced by ObjectDoc.Sound or the built-in "sound" component.

type SoundScene3D

type SoundScene3D struct {
	Emitters []*SoundEmitter3D
	ByID     map[string]*SoundEmitter3D
	Zones    *sound.ZoneRouter
	Mixer    *sound.Mixer
	Software *sound.SoftwareMixer
}

SoundScene3D holds the 3D sound emitters and sound zones built from a SceneDoc and its Nodes3D.

func BuildSoundEmitters3D

func BuildSoundEmitters3D(doc *SceneDoc, nodes *Nodes3D, resolver SoundResolver) (*SoundScene3D, error)

BuildSoundEmitters3D builds all 3D sound emitters (from ObjectDoc.Sound and components.sound) and sound zones (from ObjectDoc.SoundZone) from doc against the node tree nodes built by BuildNodes3D, attaching each *SoundEmitter3D to its *scene3d.Node under scene3d.AttachmentSoundEmitter and each sound.Zone under scene3d.AttachmentSoundZone.

func (*SoundScene3D) StopAll

func (s *SoundScene3D) StopAll()

StopAll stops every 3D sound emitter in s so no active playbacks remain.

func (*SoundScene3D) Update

func (s *SoundScene3D) Update(listener sound.Listener3D, dt time.Duration)

Update refreshes Mixer's 3D listener (when Mixer is set), updates every 3D sound emitter, and steps SoundZones against listener.Position (applying fades to Mixer and Software when set).

type SoundZoneDoc

type SoundZoneDoc struct {
	// Bus is the audio bus sounds play through while the listener is inside the zone.
	Bus string `yaml:"bus"`
	// Fade is the crossfade time in seconds when the listener enters or leaves the zone; 0 switches at once.
	Fade float32 `yaml:"fade,omitempty" schema:"minimum=0"`
	// ReverbSend is the reverb send amount from 0 to 1 while the listener is inside the zone.
	ReverbSend float32 `yaml:"reverbSend,omitempty" schema:"minimum=0,maximum=1"`
	// SendBus optionally names the auxiliary send bus driven by ReverbSend; empty defaults to "reverb".
	SendBus string `yaml:"sendBus,omitempty"`
	// Priority resolves overlapping sound zones; higher values win.
	Priority int `yaml:"priority,omitempty"`
	// Size is the optional local box extent [width, height, depth] centered on the object; zero uses the object's scale.
	Size [3]float32 `yaml:"size,omitempty"`
	// Radius, when positive, shapes the zone as a circle (2D) or sphere (3D) centered on the object instead of a box.
	Radius float32 `yaml:"radius,omitempty" schema:"minimum=0"`
}

SoundZoneDoc changes the active bus while the listener is inside an object region.

type Space

type Space string

Space 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 SpawnOptions

type SpawnOptions struct {
	// Components validates every object's components, resolves defaults, and invokes each registered ComponentType.Spawn factory on its spawned entity. When nil, SpawnEntitiesWith behaves like SpawnEntities and ignores object components.
	Components *ComponentRegistry
	// Persistence, when non-nil alongside ScenePath, applies persisted per-scene object state
	// (omitting destroyed objects and applying moved transforms and component field overrides)
	// to a copy of the SceneDoc before spawning entities.
	Persistence *save.Persistence
	// ScenePath identifies the scene inside Persistence (such as "scenes/cave.scene.yaml").
	ScenePath string
}

SpawnOptions configures SpawnEntitiesWith.

type Sprite3DDoc

type Sprite3DDoc struct {
	// Texture is the slash-separated path from the project root to the sprite sheet. Required.
	Texture string `yaml:"texture" schema:"required,minLength=1"`
	// Frames is the sheet's grid as columns and rows; both are 0 for a single image, or both positive.
	Frames [2]int `yaml:"frames,omitempty"`
	// FPS is the animation rate in frames per second; must be finite and non-negative.
	FPS float32 `yaml:"fps,omitempty" schema:"minimum=0"`
	// PixelSize is the world size of one texture pixel; must be finite and non-negative, and 0 leaves it to the renderer.
	PixelSize float32 `yaml:"pixelSize,omitempty" schema:"minimum=0"`
	// Billboard selects "enabled" (faces the camera), "axial" (turns about its Y axis) or "fixed" (keeps the object's rotation); empty leaves it to the renderer.
	Billboard string `yaml:"billboard,omitempty" schema:"enum=enabled|axial|fixed"`
}

Sprite3DDoc places a billboard sprite sheet (ObjectDoc.Sprite3D). The scene format records it; Build does not create a sprite from it yet.

type SpriteRef

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 StreamStateSnapshot

type StreamStateSnapshot struct {
	// Version is StreamStateVersion (1).
	Version int `yaml:"version" json:"version"`
	// DataLayers records each declared data layer's runtime state.
	DataLayers map[string]DataLayerState `yaml:"dataLayers,omitempty" json:"dataLayers,omitempty"`
	// Objects records per-object overrides (destroyed, moved, component fields, switches, vars) keyed by stable object ID.
	Objects map[string]save.ObjectState `yaml:"objects,omitempty" json:"objects,omitempty"`
}

StreamStateSnapshot is the plain-text YAML/JSON save state for a streamed scene: current data layer states plus per-object persistent state overrides keyed by stable object ID.

func ParseStreamStateJSON

func ParseStreamStateJSON(data []byte) (StreamStateSnapshot, error)

ParseStreamStateJSON decodes and validates a StreamStateSnapshot JSON document, refusing unknown fields.

func ParseStreamStateYAML

func ParseStreamStateYAML(data []byte) (StreamStateSnapshot, error)

ParseStreamStateYAML decodes and validates a StreamStateSnapshot YAML document, refusing unknown fields and trailing documents.

type Streamer

type Streamer struct {
	// contains filtered or unexported fields
}

Streamer streams partitioned scene cells around any number of StreamingSources, loading cell fragments in the background via world3d.ChunkStreamer, instancing them across frames within per-frame read and instance budgets, committing each cell atomically when ready, managing data layers, persisting changed object state across unload/reload, and safely skipping cross-cell connections whose target is unloaded with a warning.

func NewStreamer

func NewStreamer(cfg StreamerConfig) (*Streamer, error)

NewStreamer constructs a Streamer from cfg, builds the always-loaded scene fragment (applying any persisted overrides and initial data-layer states), and starts background ChunkStreamer workers when cfg.Workers > 0. Call Close when finished to capture state, stop workers, and unload remaining cells.

func (*Streamer) CaptureState

func (s *Streamer) CaptureState()

CaptureState captures any runtime changes (moved transforms, modified component fields, freed/destroyed objects) from all currently loaded objects into the persistence store.

func (*Streamer) Close

func (s *Streamer) Close()

Close captures current state, cancels all background loads, waits for worker goroutines to exit, and unloads all remaining streamed cells cleanly.

func (*Streamer) LoadedCells

func (s *Streamer) LoadedCells() []CellKey

LoadedCells returns the sorted list of cells currently committed into BuiltScene.

func (*Streamer) Manifest

func (s *Streamer) Manifest() *PartitionManifest

Manifest returns the PartitionManifest driving s.

func (*Streamer) MarkDestroyed

func (s *Streamer) MarkDestroyed(id string)

MarkDestroyed records object id as destroyed so it does not respawn when its cell reloads, and frees it from BuiltScene if currently loaded.

func (*Streamer) ObjectState

func (s *Streamer) ObjectState(id string) (save.ObjectState, bool)

ObjectState returns the persisted state override for object id.

func (*Streamer) PendingWaitCells

func (s *Streamer) PendingWaitCells() []CellKey

PendingWaitCells returns the sorted list of manifest cells containing a Wait: true source that are still loading or staging.

func (*Streamer) Restore

func (s *Streamer) Restore(snap StreamStateSnapshot) error

Restore applies snap's data layer states and per-object state overrides onto s, updating currently loaded objects and any cells loaded subsequently.

func (*Streamer) Scene

func (s *Streamer) Scene() *BuiltScene

Scene returns the live BuiltScene managed by s.

func (*Streamer) SetComponentField

func (s *Streamer) SetComponentField(id, component, field string, value any)

SetComponentField records a persistent component field override for object id and updates the live BuiltObject if currently loaded.

func (*Streamer) SetDataLayer

func (s *Streamer) SetDataLayer(name string, state DataLayerState) error

SetDataLayer sets the runtime state of declared data layer name on s.Scene() and updates both always-loaded objects and all currently loaded cells.

func (*Streamer) SetObjectState

func (s *Streamer) SetObjectState(id string, st save.ObjectState)

SetObjectState records a persistent state override for object id.

func (*Streamer) SetSwitch

func (s *Streamer) SetSwitch(id, key string, value bool)

SetSwitch records a per-object boolean self switch for object id.

func (*Streamer) Signals

func (s *Streamer) Signals() *Signals

Signals returns the Signals bound to s, if any.

func (*Streamer) Snapshot

func (s *Streamer) Snapshot() StreamStateSnapshot

Snapshot captures all current runtime changes and returns a deterministic StreamStateSnapshot suitable for saving to YAML or JSON.

func (*Streamer) StagingCells

func (s *Streamer) StagingCells() []CellKey

StagingCells returns the sorted list of cells currently being instanced across frames.

func (*Streamer) Switch

func (s *Streamer) Switch(id, key string) bool

Switch returns the boolean self switch value for object id.

func (*Streamer) Update

func (s *Streamer) Update(sources []StreamingSource)

Update advances cell streaming around sources:

  1. Advances each grid's background ChunkStreamer in priority/distance/coord order, unloading cells outside UnloadRadius of every source and capping new background reads to MaxReadsPerFrame across all grids.
  2. Stages up to MaxInstancesPerFrame objects on the game thread across completed cells in deterministic priority/distance/grid/coord order, committing each cell atomically into BuiltScene once all of its eligible objects finish staging.
  3. Updates PendingWaitCells for any Wait: true source whose cell is still loading.

func (*Streamer) Waiting

func (s *Streamer) Waiting() bool

Waiting reports whether any StreamingSource with Wait: true is currently positioned in a manifest cell that has not yet finished loading and committing. A cell that failed to load or instance (see StreamerConfig.OnError) does not count, so a broken cell cannot stall a game that waits on it.

type StreamerConfig

type StreamerConfig struct {
	// FS holds the generated partition manifest, always-loaded scene, and cell
	// fragments (as written by WritePartition). Either FS or Result is required.
	FS fs.FS
	// ManifestPath is the slash-separated path to the PartitionManifest inside FS.
	// Defaults to DefaultPartitionManifestFile ("partition.manifest.yaml").
	ManifestPath string
	// Result optionally provides an in-memory PartitionResult directly instead
	// of reading files from FS (handy for tests and runtime partitioning).
	Result *PartitionResult
	// Resolver resolves atlases, materials, tilemaps, particles, and skeletons
	// for the base scene and streamed cells.
	Resolver AssetResolver
	// World optionally spawns ECS entities for always-loaded and streamed objects.
	World *entities.World
	// Signals optionally wires scene connections and receives runtime events.
	// When nil and Components is non-nil, NewStreamer creates a Signals bound
	// to BuiltScene (or World when non-nil).
	Signals *Signals
	// Components optionally validates components and runs ComponentType.Spawn
	// factories for streamed objects.
	Components *ComponentRegistry
	// Persistence optionally provides an external save.Persistence store for
	// per-object state overrides surviving unload/reload. When nil, Streamer
	// maintains an internal store accessible via Snapshot/Restore and helper methods.
	Persistence *save.Persistence
	// ScenePath identifies this scene inside Persistence. Defaults to
	// Manifest.Source, or "partitioned" when empty.
	ScenePath string
	// Workers sets the number of background reader goroutines per grid via
	// world3d.ChunkStreamer. When 0, cell reads run synchronously inside Update
	// (deterministic for tests).
	Workers int
	// MaxReadsPerFrame caps how many background cell reads are started per
	// Update call across all grids. Values <= 0 allow unlimited reads per frame.
	MaxReadsPerFrame int
	// MaxInstancesPerFrame caps how many objects are instanced on the game
	// thread per Update call. A large cell exceeding this budget stages across
	// multiple frames and appears atomically when all of its objects are ready.
	// Values <= 0 allow unlimited instances per frame.
	MaxInstancesPerFrame int
	// OnCellLoaded is called on the Update goroutine after a cell commits atomically into BuiltScene.
	OnCellLoaded func(key CellKey, objectIDs []string)
	// OnCellUnloaded is called on the Update/Close goroutine after a cell unloads from BuiltScene.
	OnCellUnloaded func(key CellKey, objectIDs []string)
	// OnWarning is called on the game goroutine for non-fatal runtime warnings
	// (such as a cross-cell connection firing while its target object is unloaded).
	OnWarning func(msg string)
	// OnError is called on the Update goroutine when reading or instancing a cell fails. A cell whose read fails is read again on the next Update; a cell whose instancing fails stays out of BuiltScene until it unloads and loads again. Neither keeps Waiting true.
	OnError func(key CellKey, err error)
}

StreamerConfig configures a runtime Streamer for a partitioned scene.

type StreamingSource

type StreamingSource struct {
	X, Y        float64
	Z           float64
	RadiusScale float64
	Priority    int
	Wait        bool
}

StreamingSource is a position cells stream around, such as the player or a teleport destination. RadiusScale multiplies the partition's radii; zero or less means 1. Higher Priority loads first; Wait marks a source (such as the player) whose cell loading state is reported by Streamer.Waiting.

type TerrainResolver

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

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) and an optional a<alt> suffix naming a positive alternative tile ID declared in the tileset: "3", "3h", "3hvd", "12a1", and "12hva1". Encode writes the cells separated by single spaces with flip letters in the order h, v, d followed by any a<alt> suffix.
	Rows []string `yaml:"rows,omitempty"`
}

TileLayerDoc is one named layer of tiles of a layered grid (TilemapDoc.TileLayers).

func (*TileLayerDoc) Cell

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 (*TileLayerDoc) Cells

func (l *TileLayerDoc) Cells() ([]uint32, error)

Cells returns the layer's cells row by row from the top, as Cell returns each.

func (*TileLayerDoc) EffectiveOpacity

func (l *TileLayerDoc) EffectiveOpacity() float32

EffectiveOpacity returns Opacity, defaulting to 1 when nil.

func (*TileLayerDoc) IsVisible

func (l *TileLayerDoc) IsVisible() bool

IsVisible reports whether the tile layer is visible, defaulting to true when Visible is nil.

func (*TileLayerDoc) SetCell

func (l *TileLayerDoc) SetCell(col, row int, cell uint32) error

SetCell sets the cell at (col, row) of the layer to the tile value cell, as Cell returns it (with alternative ID 0), and writes that row in the form Encode does, preserving alternative suffixes on all other cells in the row.

func (*TileLayerDoc) SetTileCell

func (l *TileLayerDoc) SetTileCell(col, row int, cell tilemap.TileCell) error

SetTileCell sets the cell at (col, row) of the layer to cell (GID with flip bits and optional positive alternative ID) and writes that row in canonical form.

func (*TileLayerDoc) TileCell

func (l *TileLayerDoc) TileCell(col, row int) (tilemap.TileCell, error)

TileCell returns the cell at (col, row) of the layer as a tilemap.TileCell (GID with flip bits plus optional alternative ID).

func (*TileLayerDoc) TileCells

func (l *TileLayerDoc) TileCells() ([]tilemap.TileCell, error)

TileCells returns the layer's cells row by row from the top, including any alternative tile IDs.

type TileMovementArrivedEvent

type TileMovementArrivedEvent struct {
	ObjectID string
	Col, Row int
	X, Y     float32
}

TileMovementArrivedEvent is emitted with "tile_movement.arrived" when a tile_movement object finishes stepping into a cell.

type TileMovementControllerSnapshot

type TileMovementControllerSnapshot struct {
	Enabled  bool    `yaml:"enabled" json:"enabled"`
	Moving   bool    `yaml:"moving,omitempty" json:"moving,omitempty"`
	StartX   float64 `yaml:"startX,omitempty" json:"startX,omitempty"`
	StartY   float64 `yaml:"startY,omitempty" json:"startY,omitempty"`
	TargetX  float64 `yaml:"targetX,omitempty" json:"targetX,omitempty"`
	TargetY  float64 `yaml:"targetY,omitempty" json:"targetY,omitempty"`
	Progress float64 `yaml:"progress,omitempty" json:"progress,omitempty"`
	Col      int     `yaml:"col,omitempty" json:"col,omitempty"`
	Row      int     `yaml:"row,omitempty" json:"row,omitempty"`
	FacingX  int     `yaml:"facingX,omitempty" json:"facingX,omitempty"`
	FacingY  int     `yaml:"facingY,omitempty" json:"facingY,omitempty"`
	StepDirX int     `yaml:"stepDirX,omitempty" json:"stepDirX,omitempty"`
	StepDirY int     `yaml:"stepDirY,omitempty" json:"stepDirY,omitempty"`
}

TileMovementControllerSnapshot is the serializable state of a "tile_movement" controller.

type TileMovementRuntimeState

type TileMovementRuntimeState struct {
	Enabled  bool
	IsMoving bool
	Col, Row int
	FacingX  int
	FacingY  int
	TargetX  float32
	TargetY  float32
	Progress float64
}

TileMovementRuntimeState is the readable runtime state of an object's "tile_movement" controller.

type TilemapDoc

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 (*TilemapDoc) HasTilesetFile

func (t *TilemapDoc) HasTilesetFile() bool

HasTilesetFile 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 (*TilemapDoc) IsExternal

func (t *TilemapDoc) IsExternal() bool

IsExternal reports whether t references an external tilemap source file.

func (*TilemapDoc) IsInline

func (t *TilemapDoc) IsInline() bool

IsInline reports whether t carries an inline tile grid, single or layered.

func (*TilemapDoc) IsLayered

func (t *TilemapDoc) IsLayered() bool

IsLayered reports whether t is a layered grid, one that holds tile layers (TileLayers) or names a YAML tileset (TilesetFile) without flat Data.

func (*TilemapDoc) IsRef

func (t *TilemapDoc) IsRef() bool

IsRef reports whether t references a top-level tilemap by name.

func (*TilemapDoc) TileLayer

func (t *TilemapDoc) TileLayer(name string) *TileLayerDoc

TileLayer returns the tile layer of a layered grid named name, or nil.

type TilemapResolver

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

type TonemapMode string

TonemapMode 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"
)

type TurretControllerSnapshot

type TurretControllerSnapshot struct {
	Enabled  bool    `yaml:"enabled" json:"enabled"`
	TargetID string  `yaml:"targetID,omitempty" json:"targetID,omitempty"`
	TargetX  float32 `yaml:"targetX,omitempty" json:"targetX,omitempty"`
	TargetY  float32 `yaml:"targetY,omitempty" json:"targetY,omitempty"`
	Aimed    bool    `yaml:"aimed,omitempty" json:"aimed,omitempty"`
	Cooldown float64 `yaml:"cooldown,omitempty" json:"cooldown,omitempty"`
}

TurretControllerSnapshot is the serializable state of a "turret" controller.

type TurretRuntimeState

type TurretRuntimeState struct {
	Enabled   bool
	HasTarget bool
	TargetID  string
	TargetX   float32
	TargetY   float32
	Aimed     bool
	Cooldown  float64
	Angle     float64
}

TurretRuntimeState is the readable runtime state of an object's "turret" controller.

type TurretShootEvent

type TurretShootEvent struct {
	ObjectID string
	TargetID string
	X, Y     float32
	TargetX  float32
	TargetY  float32
	Angle    float64
}

TurretShootEvent is emitted with "turret.shoot" when a turret fires at its acquired target.

type VCamBuildOptions

type VCamBuildOptions struct {
	// Doc is the source SceneDoc (defaults to Built2D.Doc when Built2D is provided).
	Doc *SceneDoc
	// Built2D supplies live 2D BuiltObjects, Paths2D, Camera settings, Physics, and Signals.
	Built2D *BuiltScene
	// Nodes3D supplies live 3D scene nodes (e.g. from BuildNodes3D or scenemodel.Built.Nodes3D).
	Nodes3D *Nodes3D
	// Node3D resolves a 3D scene node by object ID when Nodes3D is nil or omits it.
	Node3D func(id string) *scene3d.Node
	// Physics optionally supplies trigger events for vcam_trigger zones. Defaults to Built2D.Physics when nil.
	Physics *PhysicsScene
	// Camera2D is the real 2D camera driven by the Director.
	Camera2D *tilemap.Camera
	// Camera3D is the real 3D camera driven by the Director.
	Camera3D *scene3d.Camera
	// Signals optionally receives vcam/vcam_trigger events. Defaults to Built2D.Signals when nil.
	Signals *Signals
	// Assist and Scope configure reduced-motion impulse scaling on the Director.
	Assist *a11y.Assist
	Scope  *core.Scope
	// FileResolver optionally loads .curve.yaml resources referenced by vcam.blendCurve.
	FileResolver FileResolver
	// ViewWidth and ViewHeight set default 2D viewport dimensions when Camera2D is nil.
	ViewWidth  float32
	ViewHeight float32
}

VCamBuildOptions configures BuildVCamDirector.

type VCamGroupTargetSpec

type VCamGroupTargetSpec struct {
	ObjectID string
	Weight   float32
}

VCamGroupTargetSpec is one parsed entry of vcam.targets ("id" or "id:weight").

type VCamSpec

type VCamSpec struct {
	Dimension         string
	Kind              string
	Priority          int
	Enabled           bool
	Target            string
	Targets           []VCamGroupTargetSpec
	Path              string
	FOV               float32
	OrthoHeight       float32
	Zoom              float32
	Distance          float32
	Height            float32
	Yaw               float32
	Pitch             float32
	OffsetX           float32
	OffsetY           float32
	OffsetZ           float32
	LookAhead         float32
	Damping           float32
	DeadZoneLeft      float32
	DeadZoneRight     float32
	DeadZoneTop       float32
	DeadZoneBottom    float32
	Padding           float32
	MinDistance       float32
	MaxDistance       float32
	MinZoom           float32
	MaxZoom           float32
	GroupMode         string
	MinFOV            float32
	MaxFOV            float32
	DollySpeed        float32
	DollyLoop         bool
	DollyOrient       string
	Confiner          string
	ConfinerSmoothing float32
	BlendDuration     float32
	BlendCurve        string
}

VCamSpec is the validated, resolved settings of a "vcam" component on an object.

func ExtractVCam

func ExtractVCam(o *ObjectDoc) (VCamSpec, bool, error)

ExtractVCam decodes and validates an object's "vcam" component. Returns ok == false when o has no "vcam" component.

type VCamSystem

type VCamSystem struct {
	Director *camera.Director
	VCams    map[string]*camera.VirtualCamera
	Triggers map[string]*VCamTriggerBinding
	// contains filtered or unexported fields
}

VCamSystem wires scene-authored "vcam" and "vcam_trigger" components into a live camera.Director.

func BuildVCamDirector

func BuildVCamDirector(opts VCamBuildOptions) (*VCamSystem, error)

BuildVCamDirector constructs a live VCamSystem from all "vcam" and "vcam_trigger" components in opts.Doc (or opts.Built2D.Doc).

func (*VCamSystem) HandleTrigger

func (s *VCamSystem) HandleTrigger(ev PhysicsTriggerEvent)

HandleTrigger updates vcam_trigger occupancy from a PhysicsTriggerEvent.

func (*VCamSystem) NotifyEnter

func (s *VCamSystem) NotifyEnter(triggerID, bodyID string, tags ...string)

NotifyEnter records that bodyID (with optional extra tags) entered triggerID. If triggerID has a matching vcam_trigger, the target vcam's priority is raised.

func (*VCamSystem) NotifyExit

func (s *VCamSystem) NotifyExit(triggerID, bodyID string)

NotifyExit records that bodyID exited triggerID, restoring the target vcam's priority when no matching occupants remain.

func (*VCamSystem) Step

func (s *VCamSystem) Step(dt time.Duration)

Step processes any trigger events emitted by PhysicsScene since the last step, updates vcam priorities, and advances Director.Step(dt).

func (*VCamSystem) VCamSystem

func (s *VCamSystem) VCamSystem() *VCamSystem

VCamSystem returns s so *VCamSystem satisfies VCamSystemProvider when passed as Connect context.

type VCamSystemProvider

type VCamSystemProvider interface {
	VCamSystem() *VCamSystem
}

VCamSystemProvider exposes a *VCamSystem from a signal Call.Context (implemented by *VCamSystem itself).

type VCamTriggerBinding

type VCamTriggerBinding struct {
	ObjectID string
	Spec     VCamTriggerSpec
	// contains filtered or unexported fields
}

VCamTriggerBinding tracks runtime occupancy of one "vcam_trigger" zone and adjusts its target vcam's priority.

func (*VCamTriggerBinding) Active

func (b *VCamTriggerBinding) Active() bool

Active reports whether at least one matching tagged body is currently inside this trigger zone.

type VCamTriggerSpec

type VCamTriggerSpec struct {
	VCam     string
	Priority int
	Boost    int
	Tag      string
	Enabled  bool
}

VCamTriggerSpec is the validated, resolved settings of a "vcam_trigger" component on an object.

func ExtractVCamTrigger

func ExtractVCamTrigger(o *ObjectDoc) (VCamTriggerSpec, bool, error)

ExtractVCamTrigger decodes and validates an object's "vcam_trigger" component. Returns ok == false when o has no "vcam_trigger" component.

type VectorInput

type VectorInput interface {
	Vector(name string) math2d.Vec2
}

VectorInput may optionally be implemented by ActionInput (as *input.Actions does) to supply named 2D vectors.

type VisibilityFadeMode

type VisibilityFadeMode string

VisibilityFadeMode selects how a 3D object transitions across its visibility range margins (VisibilityRangeDoc.Fade).

const (
	// VisibilityFadeDisabled hard-culls at Begin and End using BeginMargin and EndMargin as hysteresis deadbands.
	VisibilityFadeDisabled VisibilityFadeMode = "disabled"
	// VisibilityFadeSelf fades the object smoothly via screen-door dithering across its margins.
	VisibilityFadeSelf VisibilityFadeMode = "self"
	// VisibilityFadeDependencies fades the object smoothly across its margins for HLOD parent/child handoffs.
	VisibilityFadeDependencies VisibilityFadeMode = "dependencies"
)

type VisibilityLayerDef

type VisibilityLayerDef struct {
	Name string
	Bit  int
}

VisibilityLayerDef assigns a human-readable visibility layer name to a bit index in [0, 31].

type VisibilityLayerResolver

type VisibilityLayerResolver interface {
	VisibilityLayers() *VisibilityLayerTable
}

VisibilityLayerResolver may optionally be implemented by an AssetResolver to resolve named visibility layers (LayerDoc.VisibilityLayers, ObjectDoc.VisibilityLayers) into 32-bit bitmasks when Build builds a BuiltScene.

type VisibilityLayerTable

type VisibilityLayerTable struct {
	// contains filtered or unexported fields
}

VisibilityLayerTable resolves human-readable visibility layer names (such as "p1", "p2", or "minimap") to 32-bit visibility bitmasks matched against viewport cull masks.

func MustVisibilityLayerTable

func MustVisibilityLayerTable(defs []VisibilityLayerDef) *VisibilityLayerTable

MustVisibilityLayerTable is NewVisibilityLayerTable for tests and setup code; it panics on error.

func NewVisibilityLayerTable

func NewVisibilityLayerTable(defs []VisibilityLayerDef) (*VisibilityLayerTable, error)

NewVisibilityLayerTable builds a validated visibility layer table from defs. It refuses empty/whitespace names, duplicate names, bits outside [0, 31], and duplicate bit indices.

func (*VisibilityLayerTable) Bit

func (t *VisibilityLayerTable) Bit(name string) (uint, bool)

Bit returns the bit index in [0, 31] assigned to name and whether name is declared.

func (*VisibilityLayerTable) Mask

func (t *VisibilityLayerTable) Mask(names ...string) (uint32, error)

Mask resolves names into a 32-bit visibility bitmask. Empty names returns 0 (visible in all viewports).

func (*VisibilityLayerTable) Names

func (t *VisibilityLayerTable) Names() []string

Names returns all declared visibility layer names in ascending order.

type VisibilityRangeDoc

type VisibilityRangeDoc struct {
	// Begin is the minimum camera distance in world units at which the object becomes visible; 0 disables the near cutoff.
	Begin float32 `yaml:"begin,omitempty" schema:"minimum=0"`
	// End is the maximum camera distance in world units beyond which the object is culled; 0 disables the far cutoff.
	End float32 `yaml:"end,omitempty" schema:"minimum=0"`
	// BeginMargin is the hysteresis deadband (for fade "disabled") or fade-in width (for "self"/"dependencies") around Begin.
	BeginMargin float32 `yaml:"beginMargin,omitempty" schema:"minimum=0"`
	// EndMargin is the hysteresis deadband (for fade "disabled") or fade-out width (for "self"/"dependencies") around End.
	EndMargin float32 `yaml:"endMargin,omitempty" schema:"minimum=0"`
	// Fade selects "disabled" (default, hard cull with hysteresis), "self" (dithered fade), or "dependencies" (HLOD dithered fade).
	Fade VisibilityFadeMode `yaml:"fade,omitempty" schema:"enum=disabled|self|dependencies"`
}

VisibilityRangeDoc configures camera-distance culling and screen-door dither fading for a 3D object (ObjectDoc.VisibilityRange). Version 4.

func (*VisibilityRangeDoc) Clone

Clone returns a deep copy of v, or nil when v is nil.

func (*VisibilityRangeDoc) EffectiveFade

func (v *VisibilityRangeDoc) EffectiveFade() VisibilityFadeMode

EffectiveFade returns v.Fade, defaulting empty to VisibilityFadeDisabled.

type WrapEvent

type WrapEvent struct {
	ObjectID string
	X, Y     float32
}

WrapEvent is the payload emitted with an object's "wrap.wrapped" event.

Jump to

Keyboard shortcuts

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