Documentation
¶
Overview ¶
Package tilemap draws tiled worlds, queries tile flags and rays against them, loads Tiled maps, and moves a 2D camera over the world.
Index ¶
- Constants
- func ComputeMask4(match func(col, row int) bool, col, row int) uint8
- func ComputeMask8(match func(col, row int) bool, col, row int) uint8
- func DragMargins(left, right, top, bottom float32) core.Bounds
- func EncodeChunk(c *Chunk, format ChunkFormat) ([]byte, error)
- func EncodeChunkJSON(doc *ChunkDoc) ([]byte, error)
- func EncodeChunkYAML(doc *ChunkDoc) ([]byte, error)
- func EncodeTiled(m *Tilemap) ([]byte, error)
- func EncodeTileset(doc *TilesetDoc) ([]byte, error)
- func LoadLDtkAll(data []byte, resolveImage func(relPath string) core.ImageSource) (map[string]*Tilemap, error)
- func LoadLDtkAllWith(data []byte, opts LDtkOptions) (map[string]*Tilemap, error)
- func SortYSortTiles(tiles []YSortTile)
- func TerrainMaskNeighbors(mask uint8) []string
- func TerrainNeighborsMask(neighbors []string) (uint8, error)
- func TilesetFrame(doc *TilesetDoc, atlas *sprite.Atlas, id int) (sprite.Frame, bool)
- func TilesetSchemaCommentFor(version int) string
- func ToggleTerrainMask(mode AutotileMode, mask, bit uint8) uint8
- func ValidChunkSize(n int) bool
- func ValidTerrainMask(mode AutotileMode, mask uint8) bool
- func ValidateChunkDoc(doc *ChunkDoc) error
- func ValidateTileset(doc *TilesetDoc) error
- type AutotileMode
- type AutotileSet
- type Camera
- func (c *Camera) AddTrauma(amount float32)
- func (c *Camera) Apply(d *core.Drawing)
- func (c *Camera) ApplyPinchPan(g TwoFingerGesture) bool
- func (c *Camera) BeginStep()
- func (c *Camera) Clamp()
- func (c *Camera) Follow(target core.Point, smoothing float32, dt time.Duration)
- func (c *Camera) InterpolatedPose(a float32) (float32, float32, float32)
- func (c *Camera) Parallax(factorX, factorY float32) Camera
- func (c *Camera) ResetInterpolation()
- func (c *Camera) SetTrauma(amount float32)
- func (c *Camera) Shake(intensity float32, duration time.Duration)
- func (c *Camera) ShakeOffset() core.Point
- func (c *Camera) ShakeRoll() float32
- func (c *Camera) Trauma() float32
- func (c *Camera) Update(dt time.Duration)
- func (c *Camera) ViewToWorld(p core.Point) core.Point
- func (c *Camera) VisibleBounds() core.Bounds
- func (c *Camera) WorldToView(p core.Point) core.Point
- type CameraRig
- type Chunk
- type ChunkCoord
- type ChunkDoc
- type ChunkFormat
- type ChunkStore
- type ChunkStream
- func (s *ChunkStream) CenterChunk(worldPos core.Point) ChunkCoord
- func (s *ChunkStream) Close() error
- func (s *ChunkStream) LoadOrGenerateChunk(coord ChunkCoord) (*Chunk, error)
- func (s *ChunkStream) LoadedCount() int
- func (s *ChunkStream) SaveChunk(ch *Chunk) error
- func (s *ChunkStream) SaveModified() error
- func (s *ChunkStream) Update(worldPos core.Point)
- type ChunkStreamConfig
- type CustomDataLayer
- type CustomDataLayerDoc
- type DirChunkStore
- type ImageLayer
- type LDtkOptions
- type LayerCache
- type LevelNeighbour
- type LevelWorld
- func (w *LevelWorld) Level(id string) *WorldLevel
- func (w *LevelWorld) LevelAt(p core.Point) *WorldLevel
- func (w *LevelWorld) LevelsInRect(r core.Bounds) []*WorldLevel
- func (w *LevelWorld) LoadAll() (map[string]*Tilemap, error)
- func (w *LevelWorld) LoadLevel(id string) (*Tilemap, error)
- func (w *LevelWorld) WorldBounds() core.Bounds
- type MemoryChunkStore
- func (s *MemoryChunkStore) Bytes(coord ChunkCoord) []byte
- func (s *MemoryChunkStore) Count() int
- func (s *MemoryChunkStore) Delete(coord ChunkCoord)
- func (s *MemoryChunkStore) Has(coord ChunkCoord) bool
- func (s *MemoryChunkStore) LoadChunk(coord ChunkCoord) ([]byte, bool, error)
- func (s *MemoryChunkStore) SaveChunk(coord ChunkCoord, data []byte) error
- type Object
- type ObjectAlignment
- type ObjectLayer
- type ObjectShape
- type Orientation
- type Properties
- func (p Properties) Bool(name string) (bool, bool)
- func (p Properties) Color(name string) (core.Color, bool)
- func (p Properties) File(name string) (string, bool)
- func (p Properties) Float(name string) (float64, bool)
- func (p Properties) Has(name string) bool
- func (p Properties) Int(name string) (int, bool)
- func (p Properties) ObjectID(name string) (int, bool)
- func (p Properties) String(name string) (string, bool)
- type Property
- type RaycastHit
- type SceneTile
- type SceneTileDoc
- type ShakeProfile
- type StaggerAxis
- type StaggerIndex
- type Terrain
- type TerrainDoc
- type TerrainRand
- type TextObject
- type TileAlternative
- type TileAlternativeDoc
- type TileAnimFrame
- type TileAnimation
- type TileCell
- type TileChangeFunc
- type TileDoc
- type TileFlags
- type TileFrameDoc
- type TileHit
- type TileImage
- type TileLayer
- func (l *TileLayer) AltAt(col, row int) int
- func (l *TileLayer) Chunk(coord ChunkCoord) *Chunk
- func (l *TileLayer) ChunkCoords() []ChunkCoord
- func (l *TileLayer) ChunkCount() int
- func (l *TileLayer) ChunkTileBounds() (minCol, minRow, maxCol, maxRow int, ok bool)
- func (l *TileLayer) DirtyChunks() []ChunkCoord
- func (l *TileLayer) EffectiveChunkSize() int
- func (l *TileLayer) IsChunked() bool
- func (l *TileLayer) ModifiedChunks() []ChunkCoord
- type TileMaterial
- type TileNavigation
- type TileNavigationDoc
- type TilePhysics
- type TilePhysicsDoc
- type TileShape
- type TileShapeDoc
- type TiledWorld
- type TiledWorldLoader
- type TiledWorldMap
- type TiledWorldPattern
- type Tilemap
- func LoadLDtk(data []byte, levelIdentifier string, ...) (*Tilemap, error)
- func LoadLDtkWith(data []byte, levelIdentifier string, opts LDtkOptions) (*Tilemap, error)
- func LoadTiled(data []byte, resolve TilesetLoader) (*Tilemap, error)
- func New(width, height int, tileWidth, tileHeight float32, tilesets ...*Tileset) *Tilemap
- func NewInfinite(tileWidth, tileHeight float32, tilesets ...*Tileset) *Tilemap
- func (m *Tilemap) AddTilesetDoc(doc *TilesetDoc, firstGID uint32, assets TilesetAssets) (*Tileset, error)
- func (m *Tilemap) AppendYSortTiles(dst []YSortTile, layer *TileLayer, cam *Camera) []YSortTile
- func (m *Tilemap) ApplyAutotile(layerIndex int, set AutotileSet, terrainID func(gid uint32) bool)
- func (m *Tilemap) ApplyTerrain(layerIndex int, terrainName string) bool
- func (m *Tilemap) AtlasBatching() bool
- func (m *Tilemap) CacheDirtyChunks(layerIndex int, images map[string]image.Image) (int, error)
- func (m *Tilemap) CacheStaticChunk(layerIndex int, coord ChunkCoord, images map[string]image.Image) (*LayerCache, error)
- func (m *Tilemap) CacheStaticLayer(layerIndex int, images map[string]image.Image) (*image.RGBA, core.ImageSource, error)
- func (m *Tilemap) CellFlags(col, row int) (TileFlags, bool)
- func (m *Tilemap) ChunkAt(layerIndex int, coord ChunkCoord) *Chunk
- func (m *Tilemap) ChunkCache(layerIndex int, coord ChunkCoord) *LayerCache
- func (m *Tilemap) ChunkCoordForTile(layerIndex, col, row int) (ChunkCoord, bool)
- func (m *Tilemap) ClearCellFlags(col, row int)
- func (m *Tilemap) ClearChunkCache(layerIndex int, coord ChunkCoord)
- func (m *Tilemap) ClearLayerCache(layerIndex int)
- func (m *Tilemap) CustomDataLayer(name string) (CustomDataLayer, bool)
- func (m *Tilemap) CustomDataLayers() []CustomDataLayer
- func (m *Tilemap) DistinctZs() []int
- func (m *Tilemap) Draw(d *core.Drawing, cam *Camera)
- func (m *Tilemap) DrawImageLayer(d *core.Drawing, layer *ImageLayer, cam *Camera)
- func (m *Tilemap) DrawLayer(d *core.Drawing, layer *TileLayer, cam *Camera)
- func (m *Tilemap) DrawObjectLayer(d *core.Drawing, layer *ObjectLayer, cam *Camera)
- func (m *Tilemap) DrawZ(d *core.Drawing, cam *Camera, z int)
- func (m *Tilemap) FillRect(layerIndex, col, row, w, h int, gid uint32)
- func (m *Tilemap) Flags(tileID uint32) TileFlags
- func (m *Tilemap) FlagsAt(col, row int) TileFlags
- func (m *Tilemap) GridOrigin() (x, y float32)
- func (m *Tilemap) GridSize() (cols, rows int)
- func (m *Tilemap) HasAltZ() bool
- func (m *Tilemap) HasSceneTiles() bool
- func (m *Tilemap) HasYSortLayers() bool
- func (m *Tilemap) HexDistance(c1, r1, c2, r2 int) int
- func (m *Tilemap) HexNeighbors(col, row int) [6][2]int
- func (m *Tilemap) ImageLayer(name string) *ImageLayer
- func (m *Tilemap) InvalidateChunkCache(layerIndex int, coord ChunkCoord)
- func (m *Tilemap) InvalidateLayerCache(layerIndex int)
- func (m *Tilemap) Layer(name string) *TileLayer
- func (m *Tilemap) LayerCache(layerIndex int) *LayerCache
- func (m *Tilemap) NavigationLayer(name string) (TilesetNavigationLayer, bool)
- func (m *Tilemap) NavigationLayers() []TilesetNavigationLayer
- func (m *Tilemap) ObjectLayer(name string) *ObjectLayer
- func (m *Tilemap) OnTileChange(fn TileChangeFunc)
- func (m *Tilemap) PhysicsLayer(name string) (TilesetPhysicsLayer, bool)
- func (m *Tilemap) PhysicsLayers() []TilesetPhysicsLayer
- func (m *Tilemap) PutChunk(layerIndex int, chunk *Chunk) error
- func (m *Tilemap) Raycast(from, to core.Point, mask TileFlags) (RaycastHit, bool)
- func (m *Tilemap) RemoveChunk(layerIndex int, coord ChunkCoord) *Chunk
- func (m *Tilemap) SceneTile(gid uint32) (SceneTile, bool)
- func (m *Tilemap) SetAtlasBatching(enabled bool)
- func (m *Tilemap) SetAutotile(layerIndex, col, row int, placed bool, set AutotileSet, ...)
- func (m *Tilemap) SetCellFlags(col, row int, flags TileFlags)
- func (m *Tilemap) SetFlags(tileID uint32, flags TileFlags)
- func (m *Tilemap) SetLayerYSort(layerIndex int, enabled bool)
- func (m *Tilemap) SetTerrain(layerIndex, col, row int, set *WangSet, terrain uint8, rng TerrainRand)
- func (m *Tilemap) SetTerrainRect(layerIndex, col, row, w, h int, set *WangSet, terrain uint8, rng TerrainRand)
- func (m *Tilemap) SetTerrainTile(layerIndex, col, row int, terrainName string, placed bool) bool
- func (m *Tilemap) SetTile(layerIndex, col, row int, gid uint32)
- func (m *Tilemap) SetTileAlt(layerIndex, col, row int, gid uint32, alt int)
- func (m *Tilemap) SetTileCell(layerIndex, col, row int, cell TileCell)
- func (m *Tilemap) SetTileSortOriginY(gid uint32, offsetY float32)
- func (m *Tilemap) Terrain(name string) *Terrain
- func (m *Tilemap) TileAltAt(layerIndex, col, row int) int
- func (m *Tilemap) TileAlternative(gid uint32, alt int) (TileAlternative, bool)
- func (m *Tilemap) TileAt(layerIndex, col, row int) uint32
- func (m *Tilemap) TileBox(gid uint32) (width, height float32)
- func (m *Tilemap) TileCellAt(layerIndex, col, row int) TileCell
- func (m *Tilemap) TileCellData(cell TileCell, name string) (any, bool)
- func (m *Tilemap) TileCellShapes(cell TileCell) []TileShape
- func (m *Tilemap) TileCellSortOriginY(cell TileCell) float32
- func (m *Tilemap) TileChangesSince(rev uint64, fn func(col, row int)) (current uint64, ok bool)
- func (m *Tilemap) TileCollisionGroup(gid uint32) (ObjectLayer, bool)
- func (m *Tilemap) TileData(gid uint32, name string) (any, bool)
- func (m *Tilemap) TileDataAt(layerIndex, col, row int, name string) (any, bool)
- func (m *Tilemap) TileDataBool(gid uint32, name string) (bool, bool)
- func (m *Tilemap) TileDataFloat(gid uint32, name string) (float64, bool)
- func (m *Tilemap) TileDataInt(gid uint32, name string) (int, bool)
- func (m *Tilemap) TileDataString(gid uint32, name string) (string, bool)
- func (m *Tilemap) TileFlagsAt(col, row int) physics.TileFlags
- func (m *Tilemap) TileNavigation(gid uint32, layerName string) (TileNavigation, bool)
- func (m *Tilemap) TileOrigin(col, row int) core.Point
- func (m *Tilemap) TilePhysics(gid uint32, layerName string) (TilePhysics, bool)
- func (m *Tilemap) TileProperties(gid uint32) Properties
- func (m *Tilemap) TileRevision() uint64
- func (m *Tilemap) TileShapes(gid uint32) []TileShape
- func (m *Tilemap) TileSize() (width, height float32)
- func (m *Tilemap) TileSortOriginY(gid uint32) float32
- func (m *Tilemap) TileToWorld(col, row int) core.Point
- func (m *Tilemap) TilesInRect(r core.Bounds, mask TileFlags) []TileHit
- func (m *Tilemap) TilesetForGID(gid uint32) (*Tileset, uint32)
- func (m *Tilemap) Update(dt time.Duration)
- func (m *Tilemap) VisitLayers(fn func(tile *TileLayer, img *ImageLayer))
- func (m *Tilemap) WangSet(name string) *WangSet
- func (m *Tilemap) WorldBounds() core.Bounds
- func (m *Tilemap) WorldToTile(p core.Point) (col, row int)
- type Tileset
- type TilesetAssets
- type TilesetDoc
- func (doc *TilesetDoc) Clone() *TilesetDoc
- func (doc *TilesetDoc) Count() int
- func (doc *TilesetDoc) HasAlternative(tileID, alt int) bool
- func (doc *TilesetDoc) HasTile(id int) bool
- func (doc *TilesetDoc) SceneTile(id int) *SceneTileDoc
- func (doc *TilesetDoc) Terrain(name string, firstGID uint32) *Terrain
- type TilesetLoader
- type TilesetNavigationLayer
- type TilesetNavigationLayerDoc
- type TilesetPhysicsLayer
- type TilesetPhysicsLayerDoc
- type TwoFingerGesture
- type WangColor
- type WangID
- type WangSet
- type WangSetType
- type WangTile
- type WorldLevel
- type WorldStream
- func (s *WorldStream) Close() []WorldStreamEvent
- func (s *WorldStream) Draw(d *core.Drawing, cam *Camera)
- func (s *WorldStream) FlagsAtWorld(p core.Point) TileFlags
- func (s *WorldStream) GridFlagsAt(col, row int) TileFlags
- func (s *WorldStream) GridOrigin() (x, y float32)
- func (s *WorldStream) GridSize() (cols, rows int)
- func (s *WorldStream) LevelAt(p core.Point) (*WorldLevel, *Tilemap)
- func (s *WorldStream) Loaded() []*Tilemap
- func (s *WorldStream) LoadedCount() int
- func (s *WorldStream) LoadedLevels() []*WorldLevel
- func (s *WorldStream) Map(id string) *Tilemap
- func (s *WorldStream) Raycast(from, to core.Point, mask TileFlags) (RaycastHit, bool)
- func (s *WorldStream) TileFlagsAt(col, row int) physics.TileFlags
- func (s *WorldStream) TileSize() (width, height float32)
- func (s *WorldStream) TilesInRect(r core.Bounds, mask TileFlags) []TileHit
- func (s *WorldStream) Update(region core.Bounds) []WorldStreamEvent
- func (s *WorldStream) UpdateAnimations(dt time.Duration)
- func (s *WorldStream) UpdateCamera(cam *Camera) []WorldStreamEvent
- type WorldStreamConfig
- type WorldStreamEvent
- type WorldStreamEventKind
- type YSortDrawer
- type YSortTile
Examples ¶
Constants ¶
const ( MaskNorth uint8 = 1 << 0 MaskEast uint8 = 1 << 1 MaskSouth uint8 = 1 << 2 MaskWest uint8 = 1 << 3 MaskNorthEast uint8 = 1 << 4 MaskSouthEast uint8 = 1 << 5 MaskSouthWest uint8 = 1 << 6 MaskNorthWest uint8 = 1 << 7 )
Bitmask constants for 4-bit cardinal and 8-bit corner-gated autotiling.
const ( // DefaultChunkSize is the default power-of-two edge length (in tiles) for sparse chunked tile layers. DefaultChunkSize = 16 // MinChunkSize is the smallest supported power-of-two edge length (in tiles) for a chunked tile layer. MinChunkSize = 2 // MaxChunkSize is the largest supported power-of-two edge length (in tiles) for a chunked tile layer. MaxChunkSize = 256 )
const ( // FlipHorizontal mirrors a tile left to right (Tiled GID bit 31). FlipHorizontal uint32 = 0x80000000 // FlipVertical mirrors a tile top to bottom (Tiled GID bit 30). FlipVertical uint32 = 0x40000000 // FlipDiagonal swaps a tile's X and Y axes before horizontal and vertical flips (Tiled GID bit 29). FlipDiagonal uint32 = 0x20000000 // FlipMask masks the three orthogonal Tiled flip bits from a raw GID. FlipMask uint32 = FlipHorizontal | FlipVertical | FlipDiagonal // TileIDMask masks the global tile ID from a raw GID, stripping flip and rotation bits. TileIDMask uint32 = 0x0FFFFFFF )
const ( WangTop = 0 WangTopRight = 1 WangRight = 2 WangBottomRight = 3 WangBottom = 4 WangBottomLeft = 5 WangLeft = 6 WangTopLeft = 7 )
Clockwise indices into WangID, matching Tiled's wangid JSON array order.
const ChunkFormatVersion = 1
ChunkFormatVersion is the current schema version of the plain-text chunk YAML and JSON format.
const EllipseShapeSegments = 16
EllipseShapeSegments is the number of straight edges LoadTiled uses to approximate an ellipse a tileset draws on a tile as its collision shape.
const MaxTilesetTiles = 1 << 24
MaxTilesetTiles is the most tiles one YAML tileset may define, its TileCount or the length of its Frames.
const PropSortOriginY = "sort_origin_y"
PropSortOriginY is the tile custom property name for an explicit vertical Y-sort origin offset (in points) added to a tile's default bottom-edge sort line.
Negative values move the sort line upward (for example into a tall tree's trunk); positive values move it downward. Lookup also accepts "y_sort_origin" and "ysort_origin" as aliases.
const TilesetCurrentVersion = 2
TilesetCurrentVersion is the newest schema version (2) of the YAML tileset format (*.tileset.yaml), adding physicsLayers, navigationLayers, customData, scenes, per-tile physics layers, per-tile navigation polygons, typed custom data, Y-sort origin, and tile alternatives.
const TilesetFormatVersion = 1
TilesetFormatVersion is the original schema version (1) of the YAML tileset format (*.tileset.yaml). ParseTileset and EncodeTileset read and write versions TilesetFormatVersion through TilesetCurrentVersion.
const TilesetSchemaComment = "# yaml-language-server: $schema=" + TilesetSchemaURL
TilesetSchemaComment is the first line EncodeTileset writes for version 1 tileset documents: a YAML comment that points a YAML language server at TilesetSchemaURL. ParseTileset ignores it like any other comment.
const TilesetSchemaCommentV2 = "# yaml-language-server: $schema=" + TilesetSchemaURLV2
TilesetSchemaCommentV2 is the first line EncodeTileset writes for version 2 tileset documents, pointing a YAML language server at TilesetSchemaURLV2.
const TilesetSchemaURL = "https://nsgo.games/schemas/tileset.v1.json"
TilesetSchemaURL is where the JSON Schema of version 1 tileset documents is published. EncodeTileset names it in TilesetSchemaComment on the first line of version 1 files.
const TilesetSchemaURLV2 = "https://nsgo.games/schemas/tileset.v2.json"
TilesetSchemaURLV2 is where the JSON Schema of version 2 tileset documents is published. EncodeTileset names it in TilesetSchemaCommentV2 on the first line of version 2 files.
Variables ¶
This section is empty.
Functions ¶
func ComputeMask4 ¶
ComputeMask4 computes the 4-bit cardinal neighbor mask (N=1, E=2, S=4, W=8) at (col, row).
func ComputeMask8 ¶
ComputeMask8 computes the 8-bit corner-gated Wang/blob neighbor mask (47-tile blob) at (col, row).
Diagonal bits (NE, SE, SW, NW) are only set when both adjacent cardinal neighbors also match.
func DragMargins ¶
DragMargins returns a DeadZone bounds value for asymmetric drag margins given as fractions of the view size from the view center in each direction (left, right, top, bottom). Non-finite or negative values clamp to 0; if opposite margins sum above 1 they are scaled down proportionally so their sum is 1.
func EncodeChunk ¶
func EncodeChunk(c *Chunk, format ChunkFormat) ([]byte, error)
EncodeChunk encodes c in format (ChunkFormatYAML or ChunkFormatJSON).
func EncodeChunkJSON ¶
EncodeChunkJSON validates doc and encodes it as deterministic indented JSON with a trailing newline.
func EncodeChunkYAML ¶
EncodeChunkYAML validates doc and encodes it as deterministic 2-space YAML.
func EncodeTiled ¶
EncodeTiled encodes m as a deterministic, indented Tiled JSON (.tmj) document.
All tilesets (embedded inline), tile layers (dense or chunked), image layers, object layers, custom properties, tile animations, Wang sets, and per-tile collision object groups (from Tileset.TileCollisions, or synthesized from Tileset.Shapes when no TileCollisions entry exists) are written in canonical order so round-tripping through LoadTiled and EncodeTiled preserves per-tile collision data and produces byte-identical output.
func EncodeTileset ¶
func EncodeTileset(doc *TilesetDoc) ([]byte, error)
EncodeTileset validates doc and writes it as deterministic 2-space YAML, starting with TilesetSchemaCommentFor(doc.Version). Keys come in a fixed order and maps in sorted key order, so the same tileset always gives the same bytes, and a file in that form parses and encodes back unchanged.
func LoadLDtkAll ¶
func LoadLDtkAll(data []byte, resolveImage func(relPath string) core.ImageSource) (map[string]*Tilemap, error)
LoadLDtkAll parses an LDtk JSON project and builds a Tilemap for every level, keyed by level identifier. For Free and GridVania layouts, each Tilemap carries its world Origin (worldX, worldY) and Neighbours list. Its errors are *loaderr.Error values, as LoadLDtk's are.
func LoadLDtkAllWith ¶
func LoadLDtkAllWith(data []byte, opts LDtkOptions) (map[string]*Tilemap, error)
LoadLDtkAllWith parses an LDtk JSON project with opts and builds a Tilemap for every level, keyed by level identifier.
func SortYSortTiles ¶
func SortYSortTiles(tiles []YSortTile)
SortYSortTiles sorts tiles in stable ascending Z then SortY order without allocating.
func TerrainMaskNeighbors ¶
TerrainMaskNeighbors returns the canonical list of neighbor direction names for mask, or nil when mask is 0.
func TerrainNeighborsMask ¶
TerrainNeighborsMask converts a list of neighbor direction names to a bitmask, returning an error on unknown or duplicate directions.
func TilesetFrame ¶
TilesetFrame returns where local tile id of doc lies in the image it is drawn from: a rectangle of the grid image for an image tileset, or the frame of atlas, the atlas doc names, for an atlas tileset. It reports false for an ID outside the tileset, an atlas tileset with a nil atlas and a frame the atlas lacks. An editor's tile palette uses it to show a tileset's tiles.
func TilesetSchemaCommentFor ¶
TilesetSchemaCommentFor returns the YAML language server schema comment EncodeTileset writes for version: TilesetSchemaComment for version 1 and TilesetSchemaCommentV2 for version 2.
func ToggleTerrainMask ¶
func ToggleTerrainMask(mode AutotileMode, mask, bit uint8) uint8
ToggleTerrainMask toggles bit in mask while keeping the result valid for mode. In Autotile4 diagonal bits are ignored and stripped. In Autotile8 enabling a corner bit also enables its two adjacent cardinal edges, and disabling an edge bit clears any corner bits that depend on it.
func ValidChunkSize ¶
ValidChunkSize reports whether n is a supported power-of-two chunk edge length in [MinChunkSize, MaxChunkSize].
func ValidTerrainMask ¶
func ValidTerrainMask(mode AutotileMode, mask uint8) bool
ValidTerrainMask reports whether mask is a valid neighbor bitmask for mode: for Autotile4 only the four cardinal bits (N, E, S, W) may be set; for Autotile8 each diagonal corner bit may only be set when both adjacent cardinal bits are also set.
func ValidateChunkDoc ¶
ValidateChunkDoc checks that doc conforms to the version 1 chunk schema.
func ValidateTileset ¶
func ValidateTileset(doc *TilesetDoc) error
ValidateTileset checks doc against its schema version (TilesetFormatVersion=1 or TilesetCurrentVersion=2): a positive tile size, exactly one of a grid image (with its columns and tile count) or an atlas (with its frames), tiles in ascending ID order within the tile count, scalar properties, well-formed shapes, animations of positive durations over existing tiles, terrains whose tiles list valid distinct neighbour sets, and (in version 2) valid physicsLayers, navigationLayers, per-tile physics and per-tile navigation. Its errors are *loaderr.Error values naming the field at fault.
Types ¶
type AutotileMode ¶
type AutotileMode int
AutotileMode chooses between 4-bit cardinal (16-tile) and 8-bit corner-gated (47-tile) autotiling.
const ( // Autotile4 uses the 4 cardinal neighbors (N=1, E=2, S=4, W=8; 16 combinations). Autotile4 AutotileMode = iota // Autotile8 uses the 4 cardinal neighbors plus 4 corner-gated diagonal neighbors (47 combinations). Autotile8 )
type AutotileSet ¶
type AutotileSet struct {
Mode AutotileMode
Tiles map[uint8]uint32
Default uint32
}
AutotileSet maps autotile neighbor bitmasks to tile GIDs, falling back to Default when a mask has no entry in Tiles.
func (AutotileSet) ComputeMask ¶
func (s AutotileSet) ComputeMask(match func(col, row int) bool, col, row int) uint8
ComputeMask computes the neighbor bitmask at (col, row) using s.Mode (ComputeMask4 for Autotile4, ComputeMask8 for Autotile8).
func (AutotileSet) Tile ¶
func (s AutotileSet) Tile(mask uint8) uint32
Tile returns the GID mapped to mask, or s.Default when mask is not present in s.Tiles.
type Camera ¶
type Camera struct {
// X and Y are the world point at the center of the view.
X, Y float32
// Zoom scales the world in the view; values <= 0 behave as 1.
Zoom float32
// Rotation turns the camera clockwise in the world, in radians.
Rotation float32
// Width and Height are the view's size in points.
Width, Height float32
// Bounds, when non-nil, limits where Clamp and Follow let the visible view reach.
Bounds *core.Bounds
// ShakeSeed seeds the deterministic shake offset; 0 uses a fixed default seed.
ShakeSeed uint64
// ShakeProfile configures trauma-driven screen shake (AddTrauma); the zero value uses DefaultShakeProfile.
ShakeProfile ShakeProfile
// contains filtered or unexported fields
}
Camera maps world coordinates to a view of size Width by Height centered on (X, Y), zoomed by Zoom and turned clockwise by Rotation.
A zero or negative Zoom behaves as 1. When Bounds is set, Clamp and Follow keep the visible view inside it, centering any axis where the world is smaller than the view.
Example ¶
A Camera follows a target smoothly, stays inside its bounds and converts between world and view points.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/tilemap"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
cam := &tilemap.Camera{Width: 320, Height: 180, Zoom: 1, Bounds: &core.Bounds{Size: core.Size{Width: 640, Height: 360}}}
cam.Follow(core.Point{X: 600, Y: 100}, 0, time.Second/60)
cam.Clamp()
fmt.Println(cam.X, cam.Y, cam.VisibleBounds())
fmt.Println(cam.WorldToView(core.Point{X: 600, Y: 100}))
}
Output: 480 100 {{320 10} {320 180}} {280 90}
func (*Camera) AddTrauma ¶
AddTrauma adds amount to the camera's trauma level, clamped to [0, 1].
Multiple hits accumulate cleanly instead of replacing one another. Trauma decays linearly at ShakeProfile.Decay per second during Update and drives smooth, deterministic translation and roll shake proportional to trauma² seeded by ShakeSeed. Non-positive or non-finite amounts are ignored.
func (*Camera) Apply ¶
Apply multiplies d's transform by the world-to-view transform, including any active shake offset and roll.
func (*Camera) ApplyPinchPan ¶
func (c *Camera) ApplyPinchPan(g TwoFingerGesture) bool
ApplyPinchPan zooms and moves the camera so the world point under the two fingers' midpoint stays under it, combining a two-finger pan and a pinch in one step. It reports whether two fingers were down.
It does not clamp to Bounds or change the shake offset; call Clamp afterwards if the camera is bounded.
func (*Camera) BeginStep ¶
func (c *Camera) BeginStep()
BeginStep records the camera's X, Y and Rotation as the previous pose; call it before each fixed-step update that moves the camera.
func (*Camera) Clamp ¶
func (c *Camera) Clamp()
Clamp keeps the camera's visible view inside Bounds when Bounds is non-nil. On any axis where Bounds is smaller than the view, it centers the camera on Bounds.
func (*Camera) Follow ¶
Follow moves the camera toward target with exponential smoothing over a fixed Loop step dt, then clamps to Bounds if set.
A smoothing <= 0 snaps directly to target. Higher positive values converge faster (factor 1 - exp(-smoothing*dt)).
func (*Camera) InterpolatedPose ¶
InterpolatedPose returns the X, Y and Rotation to draw at alpha (clamped to [0, 1]) between the pose recorded by the last BeginStep and the current one, turning along the shortest arc. Before the first BeginStep it returns the current pose. It does not change the camera; Zoom is not interpolated.
func (*Camera) Parallax ¶
Parallax returns a Camera with c's zoom, effective rotation (including trauma roll), and viewport size whose position (including any active shake offset) is scaled by factorX and factorY.
func (*Camera) ResetInterpolation ¶
func (c *Camera) ResetInterpolation()
ResetInterpolation makes the current pose the previous one too, so InterpolatedPose returns it at every alpha; call it after a teleport or a cut.
func (*Camera) SetTrauma ¶
SetTrauma sets the camera's trauma level directly, clamped to [0, 1]. Passing 0 (or a non-positive value) clears active trauma shake immediately to exact zero; non-finite values are ignored.
func (*Camera) Shake ¶
Shake starts a deterministic screen shake with maximum displacement intensity in world points that decays to zero over duration.
A non-positive intensity or duration cancels any active shake.
func (*Camera) ShakeOffset ¶
ShakeOffset returns the current screen shake displacement in world points (combining Shake and AddTrauma), or (0, 0) when idle.
func (*Camera) ShakeRoll ¶
ShakeRoll returns the current trauma-driven rotational shake offset in radians, or 0 when idle.
func (*Camera) Trauma ¶
Trauma returns the current trauma level in [0, 1], or 0 when c is nil or idle.
func (*Camera) Update ¶
Update advances any active screen shake (both Shake and AddTrauma) by dt, returning the shake offset and roll to exact zero once elapsed or decayed.
func (*Camera) ViewToWorld ¶
ViewToWorld converts a point in the view to its position in world coordinates.
func (*Camera) VisibleBounds ¶
VisibleBounds returns the axis-aligned world rectangle covering all four corners of the view at the camera's current position, zoom, rotation and shake offset.
type CameraRig ¶
type CameraRig struct {
// Camera is the camera this rig moves. Step and Snap are no-ops when Camera is nil.
Camera *Camera
// Offset shifts the view center relative to the target in world points.
Offset core.Point
// DeadZone defines the drag-margin dead zone as fractions of the view size, centered on Origin (in view-size fractions; zero Origin centers the dead zone on the view). Size width and height are clamped to [0, 1]; zero disables the dead zone. Use DragMargins to build asymmetric left/right/top/bottom margins.
DeadZone core.Bounds
// LookAhead scales target velocity into world-point lead ahead of the target, capped by MaxLookAhead.
LookAhead core.Point
// MaxLookAhead caps the Euclidean length of the look-ahead vector in world points; 0 leaves it uncapped and negative disables look-ahead.
MaxLookAhead float32
// PositionSpeed is the exponential smoothing rate per second for position and look-ahead; <= 0 snaps immediately.
PositionSpeed float32
// RotationSpeed is the exponential smoothing rate per second for rotation when FollowRotation is true; <= 0 snaps immediately.
RotationSpeed float32
// ZoomSpeed is the exponential smoothing rate per second for zoom changes set via SetZoom; <= 0 snaps immediately.
ZoomSpeed float32
// LimitSpeed is the exponential smoothing rate per second for easing into changed Camera.Bounds; <= 0 hard-clamps immediately.
LimitSpeed float32
// FollowRotation rotates the camera toward targetRot along the shortest arc when true; false ignores targetRot.
FollowRotation bool
// contains filtered or unexported fields
}
CameraRig drives a Camera to follow a target with an offset, view-fraction drag margins (dead zone), velocity look-ahead, separate position/rotation/zoom smoothing, and smoothed bounds transitions.
Leave Camera.Follow for simple exponential chasing; use CameraRig when a 2D camera needs dead zones, look-ahead, smoothed limits, or rotation and zoom smoothing. Zero fields disable their feature or snap immediately, and Step performs zero heap allocations.
func (*CameraRig) SetZoom ¶
SetZoom sets the target zoom factor that Step eases Camera.Zoom toward at ZoomSpeed (or snaps to when ZoomSpeed <= 0). Non-positive or non-finite values are ignored.
func (*CameraRig) Snap ¶
Snap immediately moves the camera to target (plus Offset), clears any accumulated look-ahead, applies any pending SetZoom and targetRot (when FollowRotation is true), snaps smoothed limits to the current Camera.Bounds, clamps to Bounds, and calls Camera.ResetInterpolation. Use it on spawns, teleports, or camera cuts.
func (*CameraRig) Step ¶
func (r *CameraRig) Step(target core.Point, targetVel core.Point, targetRot float32, dt time.Duration)
Step advances the camera rig over fixed step dt toward target with velocity targetVel and rotation targetRot (in radians).
Step is frame-rate independent, deterministic, zero-allocation, and safe on dt <= 0, huge dt, or non-finite inputs.
type Chunk ¶
type Chunk struct {
Coord ChunkCoord
Size int
Tiles []uint32
// Dirty reports whether this chunk's tiles changed since its static cache was last baked.
Dirty bool
// Modified reports whether this chunk's tiles were edited after it was generated or loaded.
Modified bool
// contains filtered or unexported fields
}
Chunk holds one fixed power-of-two square (Size × Size, row-major) of raw tile GIDs inside a chunked TileLayer.
func ChunkFromDoc ¶
ChunkFromDoc validates doc and decodes it into a clean Chunk (Dirty=true, Modified=false).
func DecodeChunk ¶
func DecodeChunk(data []byte, format ChunkFormat) (*Chunk, error)
DecodeChunk decodes raw YAML or JSON bytes in format into a clean Chunk (Dirty=true, Modified=false).
func NewChunk ¶
func NewChunk(coord ChunkCoord, size int) *Chunk
NewChunk allocates an empty Size × Size chunk at coord. Non-positive or non-power-of-two sizes are normalized into [MinChunkSize, MaxChunkSize] (defaulting to DefaultChunkSize).
func (*Chunk) Cache ¶
func (c *Chunk) Cache() *LayerCache
Cache returns this chunk's static LayerCache, or nil if the chunk has not been baked.
func (*Chunk) Clone ¶
Clone returns a deep copy of c's tile data and metadata without copying its static GPU/RGBA cache.
func (*Chunk) SetTile ¶
SetTile writes gid at chunk-local (lx, ly) and reports whether the cell changed. Changing a cell marks the chunk both Dirty and Modified and invalidates its static cache.
type ChunkCoord ¶
type ChunkCoord struct {
X, Y int
}
ChunkCoord identifies one sparse chunk in chunk-grid coordinates. Both X and Y may be negative.
func TileToChunk ¶
func TileToChunk(col, row, chunkSize int) (coord ChunkCoord, lx, ly int)
TileToChunk converts a world tile coordinate (col, row) into its chunk coordinate and chunk-local (lx, ly) offset for a power-of-two chunkSize (invalid chunkSize falls back to DefaultChunkSize).
Negative tile coordinates floor toward negative infinity, so local coordinates are always in [0, chunkSize).
type ChunkDoc ¶
type ChunkDoc struct {
// Version is the schema version; must be 1.
Version int `yaml:"version" json:"version"`
// X is the chunk's X coordinate in chunk-grid space (may be negative).
X int `yaml:"x" json:"x"`
// Y is the chunk's Y coordinate in chunk-grid space (may be negative).
Y int `yaml:"y" json:"y"`
// Size is the power-of-two chunk edge length in tiles.
Size int `yaml:"size" json:"size"`
// Runs holds row-major run-length encoded raw tile GIDs (including flip bits),
// formatted as "gid" (count 1) or "gid*count" (count > 1), whose counts sum to Size*Size.
Runs []string `yaml:"runs" json:"runs"`
}
ChunkDoc is the versioned plain-text representation of one sparse tilemap chunk, suitable for deterministic YAML or JSON persistence.
func DecodeChunkJSON ¶
DecodeChunkJSON decodes and validates a JSON ChunkDoc, refusing unknown fields and trailing data. Errors are returned as *loaderr.Error values.
func DecodeChunkYAML ¶
DecodeChunkYAML decodes and validates a YAML ChunkDoc, refusing unknown fields and trailing documents. Errors are returned as *loaderr.Error values.
type ChunkFormat ¶
type ChunkFormat int
ChunkFormat selects the plain-text encoding used when persisting modified chunks.
const ( // ChunkFormatYAML encodes persisted chunks as deterministic YAML (default). ChunkFormatYAML ChunkFormat = iota // ChunkFormatJSON encodes persisted chunks as deterministic JSON. ChunkFormatJSON )
type ChunkStore ¶
type ChunkStore interface {
LoadChunk(coord ChunkCoord) (data []byte, found bool, err error)
SaveChunk(coord ChunkCoord, data []byte) error
}
ChunkStore loads and saves serialized plain-text chunk documents keyed by ChunkCoord. Implementations used with concurrent loaders (such as world3d.TilemapStreamer with Workers > 0) must be safe for concurrent use.
type ChunkStream ¶
type ChunkStream struct {
// contains filtered or unexported fields
}
ChunkStream streams sparse chunks around a moving 2D world position with hysteresis unloading, per-update load budgets, procedural generation, and deterministic YAML/JSON persistence of modified chunks.
func NewChunkStream ¶
func NewChunkStream(cfg ChunkStreamConfig) *ChunkStream
NewChunkStream constructs a ChunkStream from cfg.
func (*ChunkStream) CenterChunk ¶
func (s *ChunkStream) CenterChunk(worldPos core.Point) ChunkCoord
CenterChunk returns the ChunkCoord containing worldPos in s's layer.
func (*ChunkStream) Close ¶
func (s *ChunkStream) Close() error
Close saves all loaded modified chunks and unloads every chunk from the layer.
func (*ChunkStream) LoadOrGenerateChunk ¶
func (s *ChunkStream) LoadOrGenerateChunk(coord ChunkCoord) (*Chunk, error)
LoadOrGenerateChunk restores coord from Store if present, or otherwise allocates a new Chunk and runs Generator. The returned Chunk always has Dirty=true and Modified=false.
func (*ChunkStream) LoadedCount ¶
func (s *ChunkStream) LoadedCount() int
LoadedCount returns the number of currently loaded chunks in the streamed layer.
func (*ChunkStream) SaveChunk ¶
func (s *ChunkStream) SaveChunk(ch *Chunk) error
SaveChunk encodes ch in s's configured format and writes it to Store, clearing ch.Modified on success.
func (*ChunkStream) SaveModified ¶
func (s *ChunkStream) SaveModified() error
SaveModified persists every currently loaded modified chunk in deterministic (Y, X) order.
func (*ChunkStream) Update ¶
func (s *ChunkStream) Update(worldPos core.Point)
Update advances streaming for worldPos:
- Unloads loaded chunks beyond UnloadRadius (saving modified chunks to Store first).
- Loads from Store or generates missing chunks within LoadRadius (closest first), up to MaxLoadsPerUpdate.
type ChunkStreamConfig ¶
type ChunkStreamConfig struct {
// Map is the Tilemap owning LayerIndex.
Map *Tilemap
// LayerIndex selects the chunked TileLayer inside Map.Layers.
LayerIndex int
// LoadRadius is the Chebyshev chunk radius around the center chunk to keep loaded.
LoadRadius int
// UnloadRadius is the Chebyshev chunk radius beyond which loaded chunks are unloaded.
// Defaults to LoadRadius + 1 when smaller than LoadRadius.
UnloadRadius int
// MaxLoadsPerUpdate caps how many missing chunks are loaded or generated per Update call (<= 0 means unlimited).
MaxLoadsPerUpdate int
// Format selects ChunkFormatYAML (default) or ChunkFormatJSON when saving and restoring modified chunks.
Format ChunkFormat
// Store persists modified chunks on unload and restores them on reload before invoking Generator.
Store ChunkStore
// Generator populates a freshly allocated chunk when Store has no saved entry for coord.
Generator func(coord ChunkCoord, chunk *Chunk) error
// OnLoad is called after a chunk is loaded or generated and installed into the layer.
OnLoad func(coord ChunkCoord, chunk *Chunk)
// OnUnload is called after a chunk is saved (if modified) and removed from the layer.
OnUnload func(coord ChunkCoord, chunk *Chunk)
// OnError is called when loading, generating, or saving a chunk fails.
OnError func(coord ChunkCoord, err error)
}
ChunkStreamConfig configures a synchronous ChunkStream for one chunked TileLayer. For multi-threaded background chunk loading on top of world3d.ChunkStreamer, see world3d.NewTilemapStreamer.
type CustomDataLayer ¶
type CustomDataLayer struct {
// Name uniquely identifies the custom data layer within its tileset.
Name string
// Type is the declared value kind: "int", "float", "bool", or "string".
Type string
// Enum lists the allowed string values when Type is "string" and restricted; nil otherwise.
Enum []string
// Default holds the fallback value returned when a tile omits this layer, valid when HasDefault is true.
Default any
HasDefault bool
}
CustomDataLayer declares one named, typed custom data layer on a Tileset.
type CustomDataLayerDoc ¶
type CustomDataLayerDoc struct {
// Name uniquely identifies the custom data layer within the tileset; tiles reference it under TileDoc.Data.
Name string `yaml:"name" schema:"required,minLength=1"`
// Type is the declared value kind: "int", "float", "bool", or "string".
Type string `yaml:"type" schema:"required,enum=int|float|bool|string"`
// Enum optionally restricts "string" values (and Default) to this list of allowed non-empty strings.
Enum []string `yaml:"enum,omitempty,flow"`
// Default optionally sets the fallback value returned when a tile omits this custom data layer.
Default *any `yaml:"default,omitempty"`
}
CustomDataLayerDoc declares one named, typed custom data layer in a version 2 TilesetDoc.
type DirChunkStore ¶
type DirChunkStore struct {
Dir string
Format ChunkFormat
// contains filtered or unexported fields
}
DirChunkStore is a directory-backed ChunkStore that saves each chunk as a plain-text file named "chunk_<x>_<y>.yaml" (or ".json" when Format is ChunkFormatJSON).
func NewDirChunkStore ¶
func NewDirChunkStore(dir string, format ChunkFormat) *DirChunkStore
NewDirChunkStore constructs a DirChunkStore rooted at dir with the given plain-text format.
func (*DirChunkStore) LoadChunk ¶
func (s *DirChunkStore) LoadChunk(coord ChunkCoord) ([]byte, bool, error)
LoadChunk reads coord's file from s.Dir, returning found=false if the file does not exist.
func (*DirChunkStore) Path ¶
func (s *DirChunkStore) Path(coord ChunkCoord) string
Path returns the file path for coord inside s.Dir.
func (*DirChunkStore) SaveChunk ¶
func (s *DirChunkStore) SaveChunk(coord ChunkCoord, data []byte) error
SaveChunk atomically writes data to coord's file inside s.Dir, creating s.Dir if needed.
type ImageLayer ¶
type ImageLayer struct {
Name string
Image core.ImageSource
Width float32
Height float32
OffsetX float32
OffsetY float32
ParallaxX float32
ParallaxY float32
HasParallax bool
RepeatX bool
RepeatY bool
Opacity float32
TintColor core.Color
Tinted bool
Visible bool
Properties Properties
}
ImageLayer is an image layer (such as a sky, parallax backdrop, or foreground overlay) drawn in map layer order.
Its zero value is hidden and transparent with unset parallax defaulting to (1, 1); NewImageLayer returns a visible layer at full opacity with parallax (1, 1) and HasParallax set.
func NewImageLayer ¶
func NewImageLayer(name string, image core.ImageSource) ImageLayer
NewImageLayer returns a visible ImageLayer at full opacity with parallax (1, 1).
type LDtkOptions ¶
type LDtkOptions struct {
// ResolveImage maps an LDtk tileset relative path into an ImageSource.
// When nil, core.ImageSource{URI: relPath} is used.
ResolveImage func(relPath string) core.ImageSource
// IntGridFlags maps LDtk IntGrid value identifiers or IntGrid value group identifiers
// (case-insensitive) to TileFlags, overriding the built-in heuristic.
// Mapping a name to 0 explicitly marks matching IntGrid cells non-colliding.
IntGridFlags map[string]TileFlags
// IntGridValueFlags maps positive numeric LDtk IntGrid values (1, 2, ...) directly to TileFlags,
// taking precedence over IntGridFlags and the built-in heuristic.
// Mapping a value to 0 explicitly marks matching IntGrid cells non-colliding.
IntGridValueFlags map[int]TileFlags
}
LDtkOptions configures LoadLDtkWith, LoadLDtkAllWith, and LoadLDtkWorldWith.
type LayerCache ¶
type LayerCache struct {
Pixels *image.RGBA
Source core.ImageSource
OriginX float32
OriginY float32
Width float32
Height float32
Dirty bool
Version uint64
}
LayerCache holds a static tile layer baked into a premultiplied RGBA pixel buffer so DrawLayer can emit a single DrawImageFrom op.
type LevelNeighbour ¶
type LevelNeighbour struct {
// Identifier is the neighbour level's identifier, resolved from the world's level list when available.
Identifier string
// IID is the neighbour level's LDtk instance ID (levelIid), when present.
IID string
// UID is the neighbour level's numeric LDtk UID (levelUid), when present.
UID int
// Dir is the direction from this level to the neighbour:
// "n", "s", "e", "w", "ne", "nw", "se", "sw", "o" (overlapping), "<" (lower depth), or ">" (higher depth).
Dir string
}
LevelNeighbour describes one adjacent or overlapping level in a multi-level world (such as an LDtk project).
type LevelWorld ¶
type LevelWorld struct {
// Name is the world identifier (for multi-world LDtk projects) or empty.
Name string
// Layout is the world layout ("Free", "GridVania", or "Tiled").
Layout string
// Levels lists every level in deterministic world order.
Levels []WorldLevel
}
LevelWorld holds the layout of a multi-level 2D world loaded from an LDtk project or a Tiled .world file.
func LoadLDtkWorld ¶
func LoadLDtkWorld(data []byte, worldIdentifier string, resolveImage func(relPath string) core.ImageSource) (*LevelWorld, error)
LoadLDtkWorld parses an LDtk JSON project (.ldtk) into a LevelWorld whose levels carry their world Origin, pixel Bounds, WorldDepth, and Neighbours list, and load lazily into *Tilemap values on demand.
An empty worldIdentifier selects the project's top-level levels (or the sole world when multi-worlds has one entry); a multi-world project with multiple worlds names the world by its identifier. The world's layout must be Free or GridVania (or omitted, defaulting to Free); LinearHorizontal and LinearVertical layouts are refused because they assign no 2D world coordinates.
Its errors are *loaderr.Error values, as LoadLDtk's are.
func LoadLDtkWorldWith ¶
func LoadLDtkWorldWith(data []byte, worldIdentifier string, opts LDtkOptions) (*LevelWorld, error)
LoadLDtkWorldWith parses an LDtk JSON project (.ldtk) into a LevelWorld using opts (including custom IntGrid-to-TileFlags mappings).
func LoadTiledWorld ¶
func LoadTiledWorld(data []byte, loader TiledWorldLoader) (*LevelWorld, error)
LoadTiledWorld parses a Tiled .world JSON file and builds a LevelWorld whose levels load lazily through loader.
Each loaded *Tilemap has its Origin set to the map's (x, y) placement from the .world file. When an explicit map entry omits width or height, LoadTiledWorld reads the map's header via loader.LoadMap to populate exact world bounds for streaming; entries with explicit dimensions remain completely lazy until loaded.
func (*LevelWorld) Level ¶
func (w *LevelWorld) Level(id string) *WorldLevel
Level returns the first WorldLevel with the given ID, or nil if none matches.
func (*LevelWorld) LevelAt ¶
func (w *LevelWorld) LevelAt(p core.Point) *WorldLevel
LevelAt returns the first WorldLevel whose Bounds contain p (using half-open [Origin, Origin+Size)), or nil if none matches.
func (*LevelWorld) LevelsInRect ¶
func (w *LevelWorld) LevelsInRect(r core.Bounds) []*WorldLevel
LevelsInRect returns every WorldLevel whose Bounds overlap r, in deterministic Levels order.
func (*LevelWorld) LoadAll ¶
func (w *LevelWorld) LoadAll() (map[string]*Tilemap, error)
LoadAll eagerly loads every level in w and returns them keyed by WorldLevel.ID.
func (*LevelWorld) LoadLevel ¶
func (w *LevelWorld) LoadLevel(id string) (*Tilemap, error)
LoadLevel loads and returns the *Tilemap for the level with the given ID.
func (*LevelWorld) WorldBounds ¶
func (w *LevelWorld) WorldBounds() core.Bounds
WorldBounds returns the bounding rectangle spanning every level in w, or a zero Bounds if w has no levels.
type MemoryChunkStore ¶
type MemoryChunkStore struct {
// contains filtered or unexported fields
}
MemoryChunkStore is an in-memory, concurrency-safe ChunkStore storing plain-text chunk bytes.
func NewMemoryChunkStore ¶
func NewMemoryChunkStore() *MemoryChunkStore
NewMemoryChunkStore returns an empty MemoryChunkStore.
func (*MemoryChunkStore) Bytes ¶
func (s *MemoryChunkStore) Bytes(coord ChunkCoord) []byte
Bytes returns a copy of the raw saved bytes for coord, or nil if absent.
func (*MemoryChunkStore) Count ¶
func (s *MemoryChunkStore) Count() int
Count returns the number of saved chunks in s.
func (*MemoryChunkStore) Delete ¶
func (s *MemoryChunkStore) Delete(coord ChunkCoord)
Delete removes any saved entry for coord.
func (*MemoryChunkStore) Has ¶
func (s *MemoryChunkStore) Has(coord ChunkCoord) bool
Has reports whether coord has a saved entry in s.
func (*MemoryChunkStore) LoadChunk ¶
func (s *MemoryChunkStore) LoadChunk(coord ChunkCoord) ([]byte, bool, error)
LoadChunk returns a copy of the saved bytes for coord, or found=false if absent.
func (*MemoryChunkStore) SaveChunk ¶
func (s *MemoryChunkStore) SaveChunk(coord ChunkCoord, data []byte) error
SaveChunk stores a copy of data under coord.
type Object ¶
type Object struct {
ID int
Name string
Type string
Shape ObjectShape
X, Y float32
Width float32
Height float32
// PivotX and PivotY hold the object's normalized anchor within its (Width, Height) box
// relative to the top-left corner (X, Y), populated from LDtk entity __pivot (defaulting to
// (0, 0) for top-left). The original anchor point is (X + PivotX*Width, Y + PivotY*Height).
PivotX float32
PivotY float32
Rotation float32
GID uint32
Visible bool
Points []core.Point
// Text holds the text content and styling when Shape is ObjectText, or nil otherwise.
Text *TextObject
Properties Properties
}
Object is one object from a Tiled objectgroup layer or an LDtk Entities layer.
func (Object) PhysicsShape ¶
PhysicsShape returns o's collision shape in map coordinates for static level geometry:
- a rectangle becomes a physics.Box, or a physics.Polygon when it is rotated;
- an ellipse becomes a physics.Circle when it is round and a physics.Polygon of 8 vertices inscribed in it otherwise;
- a polygon becomes a physics.Polygon when it is convex with at most physics.MaxPolygonVertices vertices, and a closed physics.Chain along its outline otherwise, which keeps concave terrain exact;
- a polyline becomes a physics.Segment when it has two points and an open physics.Chain when it has more.
Rotation turns the object clockwise about (X, Y), as Tiled does. Points, tile objects and objects too small to collide (a rectangle without area, a polygon whose points all lie on one line, a polyline with fewer than two distinct points) report false. The shape ignores the object layer's offset; ObjectLayer.PhysicsBodies applies it.
func (Object) TileID ¶
TileID returns the global tile ID of a tile object with flip bits stripped, or 0 for non-tile objects.
func (Object) WorldPoints ¶
WorldPoints returns the vertices of a polygon or polyline object translated by (X, Y).
type ObjectAlignment ¶
type ObjectAlignment int
ObjectAlignment controls which point of a tile object sits at its (X, Y) position and acts as its rotation pivot.
const ( // ObjectAlignmentUnspecified uses bottom-left in orthogonal/staggered/hexagonal maps and bottom in isometric maps, matching Tiled. ObjectAlignmentUnspecified ObjectAlignment = iota ObjectAlignmentTopLeft ObjectAlignmentTop ObjectAlignmentTopRight ObjectAlignmentLeft ObjectAlignmentCenter ObjectAlignmentRight ObjectAlignmentBottomLeft ObjectAlignmentBottom ObjectAlignmentBottomRight )
type ObjectLayer ¶
type ObjectLayer struct {
Name string
OffsetX float32
OffsetY float32
ParallaxX float32
ParallaxY float32
HasParallax bool
Opacity float32
TintColor core.Color
Tinted bool
Visible bool
Objects []Object
Properties Properties
}
ObjectLayer is a Tiled objectgroup layer.
Its zero value is hidden and transparent with unset parallax defaulting to (1, 1); NewObjectLayer returns a visible layer at full opacity with parallax (1, 1) and HasParallax set.
func NewObjectLayer ¶
func NewObjectLayer(name string, objects ...Object) ObjectLayer
NewObjectLayer returns a visible ObjectLayer at full opacity with parallax (1, 1).
func (*ObjectLayer) PhysicsBodies ¶
func (l *ObjectLayer) PhysicsBodies() []*physics.Body
PhysicsBodies returns a physics.Body for every object of l that has a PhysicsShape, in object order, moved by the layer's offset, for a physics.World's static level geometry. Each body's ID is the object's ID, its Tag the object's Type and its UserData the Object. Hidden objects are included, since collision layers are often hidden in Tiled. Use physics.NewStaticRigidBody(body.Shape) to collide them with a physics.RigidWorld. A nil layer, which Tilemap.ObjectLayer returns for a name the map does not have, has no bodies. Like the objects, the bodies are in the map's local coordinates and ignore Tilemap.Origin; translate their shapes by it for a map placed in a world.
Example ¶
PhysicsBodies turns a Tiled polyline into static terrain: a ball dropped on the map's ground line lands on it and rolls down its slope onto the lower floor.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/physics"
"github.com/nsgo-dev/game/pkg/tilemap"
)
// slopes is a Tiled map whose "collision" object layer holds a polyline drawn as the level's ground: flat, down a slope, and flat again.
const slopes = `{
"type": "map", "orientation": "orthogonal", "renderorder": "right-down",
"width": 20, "height": 10, "tilewidth": 16, "tileheight": 16, "infinite": false,
"layers": [{
"type": "objectgroup", "name": "collision", "x": 0, "y": 0, "opacity": 1, "visible": false,
"objects": [{
"id": 1, "name": "", "type": "ground", "x": 0, "y": 80, "width": 0, "height": 0, "rotation": 0, "visible": true,
"polyline": [{"x": 0, "y": 0}, {"x": 96, "y": 0}, {"x": 224, "y": 64}, {"x": 320, "y": 64}]
}]
}],
"tilesets": []
}`
func main() {
m, err := tilemap.LoadTiled([]byte(slopes), tilemap.TilesetLoader{})
if err != nil {
fmt.Println(err)
return
}
terrain := m.Objects[0].PhysicsBodies()
fmt.Println(len(terrain), terrain[0].Tag, terrain[0].Shape.Kind == physics.ShapeChain)
w := &physics.RigidWorld{GravityY: 600}
for _, b := range terrain {
w.AddBody(physics.NewStaticRigidBody(b.Shape))
}
ball := physics.NewRigidCircle(40, 40, 8, 1)
w.AddBody(ball)
for range 200 {
ball.VX = min(ball.VX+2, 80) // a gentle push to the right
w.Step(time.Second / 60)
}
fmt.Printf("%.0f %v\n", ball.Y, ball.X > 224)
}
Output: 1 ground true 136 true
type ObjectShape ¶
type ObjectShape int
ObjectShape identifies the geometric shape of a Tiled object.
const ( ObjectRect ObjectShape = iota ObjectPoint ObjectEllipse ObjectPolygon ObjectPolyline ObjectTile ObjectText )
type Orientation ¶
type Orientation int
Orientation selects how tiles are arranged and projected into world coordinates.
const ( // OrientationOrthogonal lays tiles out on an axis-aligned rectangular grid. OrientationOrthogonal Orientation = iota // OrientationIsometric lays tiles out on a diamond isometric grid. OrientationIsometric // OrientationStaggered lays isometric diamonds out with alternating rows or columns shifted by half a tile. OrientationStaggered // OrientationHexagonal lays hexagons out with alternating rows (pointy-top) or columns (flat-top) shifted by half a tile. OrientationHexagonal )
type Properties ¶
Properties is a set of named custom properties with typed getters.
func (Properties) Bool ¶
func (p Properties) Bool(name string) (bool, bool)
Bool returns the boolean value of name.
func (Properties) Color ¶
func (p Properties) Color(name string) (core.Color, bool)
Color parses a Tiled color property (#RRGGBB or #AARRGGBB) into a core.Color.
func (Properties) File ¶
func (p Properties) File(name string) (string, bool)
File returns the file path value of a file property (or string property).
func (Properties) Float ¶
func (p Properties) Float(name string) (float64, bool)
Float returns the floating-point value of name (accepting float or int properties).
func (Properties) Has ¶
func (p Properties) Has(name string) bool
Has reports whether a property named name exists.
func (Properties) Int ¶
func (p Properties) Int(name string) (int, bool)
Int returns the integer value of name (matching int and object properties).
type RaycastHit ¶
type RaycastHit struct {
Col, Row int
TileID uint32
Flags TileFlags
Point core.Point
Normal core.Point
// T is the hit's fraction along the segment from -> to, in [0, 1].
T float32
}
RaycastHit is the first tile cell met by Tilemap.Raycast.
type SceneTile ¶
type SceneTile struct {
// LocalID is the tile's 0-based local ID within its tileset.
LocalID uint32
// Scene is the slash-separated path from the project root of the scene file (*.scene.yaml) to instance.
Scene string
// DisplayFrame optionally names an atlas or icon frame shown in tile palettes.
DisplayFrame string
}
SceneTile describes one scene tile declared on a Tileset: a local tile ID that instances a scene file when placed on a tile layer.
type SceneTileDoc ¶
type SceneTileDoc struct {
// ID is the scene tile's local tile ID (>= 0, unique, in ascending order, and not colliding with the tileset's image or atlas tiles).
ID int `yaml:"id" schema:"required,minimum=0"`
// Scene is the slash-separated path from the project root of the scene file (*.scene.yaml) to instance at each cell holding this tile.
Scene string `yaml:"scene" schema:"required,minLength=1"`
// DisplayFrame optionally names an atlas or icon frame shown in tile palettes for this scene tile.
DisplayFrame string `yaml:"displayFrame,omitempty"`
}
SceneTileDoc declares one scene tile in a version 2 TilesetDoc: a local tile ID that places an instance of a scene file when placed on a tile layer.
type ShakeProfile ¶
type ShakeProfile struct {
// MaxOffset is the maximum translation displacement in world points at full trauma (1).
MaxOffset float32
// MaxRoll is the maximum clockwise rotational displacement in radians at full trauma (1).
MaxRoll float32
// Frequency is the smooth noise sampling frequency in cycles per second.
Frequency float32
// Decay is the linear trauma decay rate per second (for example, 1.5 decays trauma from 1 to 0 in 2/3 s).
Decay float32
}
ShakeProfile configures trauma-driven screen shake (Camera.AddTrauma): maximum world-point translation, maximum clockwise roll in radians, smooth noise frequency in cycles per second, and linear trauma decay rate per second.
When a Camera's ShakeProfile is the zero value, AddTrauma uses DefaultShakeProfile. When any field is set, non-positive Frequency or Decay falls back to its default (12 and 1.5), and if both MaxOffset and MaxRoll are zero they fall back to their defaults (16 and 0.08); setting one of MaxOffset or MaxRoll while leaving the other 0 disables the zero axis.
func DefaultShakeProfile ¶
func DefaultShakeProfile() ShakeProfile
DefaultShakeProfile returns the default trauma shake profile: 16 world-point max offset, 0.08 rad max roll, 12 Hz smooth noise, and 1.5/s linear trauma decay.
type StaggerAxis ¶
type StaggerAxis int
StaggerAxis selects which axis is staggered for staggered isometric and hexagonal maps.
const ( // StaggerY staggers alternating rows horizontally (pointy-top hexagons). StaggerY StaggerAxis = iota // StaggerX staggers alternating columns vertically (flat-top hexagons). StaggerX )
type StaggerIndex ¶
type StaggerIndex int
StaggerIndex selects whether odd or even rows/columns are shifted in staggered and hexagonal maps.
const ( // StaggerOdd shifts odd-indexed rows or columns (Tiled default). StaggerOdd StaggerIndex = iota // StaggerEven shifts even-indexed rows or columns. StaggerEven )
type Terrain ¶
type Terrain struct {
// Name is the terrain's name in its tileset.
Name string
// Autotile maps neighbour masks to the terrain's GIDs; its Default is the tile that lists no neighbours, or 0 when none does.
Autotile AutotileSet
}
Terrain is one terrain set of a tileset, from a TilesetDoc's Terrains: the autotile set that maps the neighbour mask of a cell to the terrain's tile, in global tile IDs, ready for Tilemap.ApplyAutotile and Tilemap.SetAutotile with Contains as their terrainID.
type TerrainDoc ¶
type TerrainDoc struct {
// Name identifies the terrain within the tileset; tiles name it in TileDoc.Terrain.
Name string `yaml:"name" schema:"required,minLength=1"`
// Mode is "cardinal", which matches the four edge neighbours (Autotile4, 16 tiles), or "blob", which also matches a corner neighbour when both edges beside it match (Autotile8, 47 tiles).
Mode string `yaml:"mode" schema:"required,enum=cardinal|blob"`
// Default is the optional local tile ID used when a cell's neighbour mask has no tile mapped to it. When omitted, the tile of the terrain that lists no neighbours (mask 0) is the default.
Default *int `yaml:"default,omitempty" schema:"minimum=0"`
}
TerrainDoc is one terrain set of a TilesetDoc: a family of tiles, such as the edges and corners of grass, from which autotiling picks a tile by which neighbouring cells hold the same terrain (Tilemap.ApplyAutotile).
type TerrainRand ¶
type TerrainRand interface {
Float64() float64
}
TerrainRand supplies deterministic uniform [0, 1) floats for weighted tie-breaking in SetTerrain and SetTerrainRect. *random.Stream satisfies TerrainRand.
type TextObject ¶
type TextObject struct {
Text string
FontFamily string
PixelSize int
Wrap bool
Color core.Color
Bold bool
Italic bool
Underline bool
Strikeout bool
Kerning bool
HAlign string
VAlign string
}
TextObject holds the text content and styling of a Tiled text object.
type TileAlternative ¶
type TileAlternative struct {
// Alt is the positive alternative ID (>= 1) for this variant.
Alt int
// FlipFlags combines FlipHorizontal, FlipVertical, and FlipDiagonal applied by this alternative before cell flip flags.
FlipFlags uint32
// Tint is the alternative's RGBA multiply color when Tinted is true (0xRRGGBBAA).
Tint core.Color
// Tinted reports whether Tint is explicitly set on this alternative.
Tinted bool
// Z is the draw order offset relative to the layer (0 draws with the layer, negative beneath, positive above).
Z int
// YSortOriginY overrides the tile's vertical Y-sort origin offset in points when HasYSortOrigin is true.
YSortOriginY float32
HasYSortOrigin bool
// TextureOriginX and TextureOriginY shift where the tile's texture draws in points relative to its cell placement.
TextureOriginX float32
TextureOriginY float32
// Data holds optional per-alternative typed custom data overrides keyed by custom data layer name.
Data map[string]any
// Shapes holds optional collision shapes overriding the base tile's Shapes for this alternative.
Shapes []TileShape
}
TileAlternative holds the runtime overrides of one alternative variant of a tile in a Tileset.
type TileAlternativeDoc ¶
type TileAlternativeDoc struct {
// Alt is the positive alternative ID (>= 1, unique and in ascending order per tile), addressed in cell text as "<id>a<alt>" (such as "12a1").
Alt int `yaml:"alt" schema:"required,minimum=1"`
// FlipH mirrors the tile horizontally.
FlipH bool `yaml:"flipH,omitempty"`
// FlipV mirrors the tile vertically.
FlipV bool `yaml:"flipV,omitempty"`
// FlipD transposes the tile across its diagonal (swapping X and Y axes before FlipH and FlipV, matching tilemap.FlipDiagonal).
FlipD bool `yaml:"flipD,omitempty"`
// Tint is an optional hex color ("#rrggbb" or "#rrggbbaa") multiplying the tile's color (and composing multiplicatively with layer and scene modulate).
Tint string `yaml:"tint,omitempty"`
// Z is the tile's draw order offset relative to the layer (0 draws with the layer, negative beneath, positive above).
Z int `yaml:"z,omitempty"`
// YSortOriginY overrides the tile's vertical Y-sort origin offset in points relative to the cell's bottom edge when Y-sorting is enabled.
YSortOriginY *float32 `yaml:"ySortOriginY,omitempty"`
// TextureOriginX and TextureOriginY shift where the tile's texture draws in points relative to its cell placement.
TextureOriginX float32 `yaml:"textureOriginX,omitempty"`
TextureOriginY float32 `yaml:"textureOriginY,omitempty"`
// Data optionally overrides declared customData layer values for this alternative; omitted keys inherit from the base tile and then the layer's Default.
Data map[string]any `yaml:"data,omitempty"`
// Shapes optionally overrides the base tile's collision shapes for this alternative.
Shapes []TileShapeDoc `yaml:"shapes,omitempty"`
}
TileAlternativeDoc describes one alternative variant of a tile in a version 2 TilesetDoc: sharing the base tile's image/atlas cell while applying its own flip/transpose, color tint, draw Z offset, Y-sort origin offset, texture origin offset, optional collision shapes, and optional typed custom data overrides.
type TileAnimFrame ¶
TileAnimFrame is one frame of an animated tile: its local tile ID in the tileset and how long it shows.
type TileAnimation ¶
type TileAnimation struct {
Frames []TileAnimFrame
// contains filtered or unexported fields
}
TileAnimation advances one animated tile through its frames in a loop on Tilemap.Update.
func (*TileAnimation) CurrentTileID ¶
func (a *TileAnimation) CurrentTileID() uint32
CurrentTileID returns the local tile ID showing now, or 0 for an empty animation.
func (*TileAnimation) Index ¶
func (a *TileAnimation) Index() int
Index returns the index in Frames of the frame showing now.
func (*TileAnimation) Reset ¶
func (a *TileAnimation) Reset()
Reset restarts the animation from its first frame.
func (*TileAnimation) Update ¶
func (a *TileAnimation) Update(dt time.Duration)
Update moves the animation forward by dt, wrapping cleanly across full cycles.
type TileCell ¶
type TileCell struct {
// GID is the raw global tile ID (0 for an empty cell) with optional FlipHorizontal, FlipVertical, and FlipDiagonal bits.
GID uint32
// Alt is the alternative tile ID (0 for the base tile, >= 1 for an alternative declared under TileDoc.Alternatives).
Alt int
}
TileCell pairs a raw tile GID (including Tiled flip bits) with an optional alternative tile ID (0 for the base tile).
type TileChangeFunc ¶
TileChangeFunc is called when a cell changes through SetTile, SetTileAlt, SetTileCell, FillRect, PutChunk, or RemoveChunk. oldCell and newCell carry the cell's previous and updated GID and Alt values.
type TileDoc ¶
type TileDoc struct {
// ID is the tile's local ID, from 0 to the tileset's tile count less 1.
ID int `yaml:"id" schema:"required,minimum=0"`
// Name is an optional human-readable name for the tile, such as "stone" or "moss".
Name string `yaml:"name,omitempty"`
// Solid sets TileSolid on the tile, so collision queries and tileshape treat its cells as blocked.
Solid bool `yaml:"solid,omitempty"`
// OneWay sets TileOneWay on the tile, a platform that blocks only from above.
OneWay bool `yaml:"oneWay,omitempty"`
// Flags are further TileFlags bits the game defines, such as a water or ladder bit, set on the tile beside Solid and OneWay.
Flags TileFlags `yaml:"flags,omitempty"`
// Weight is the tile's optional relative selection weight for random and variant brushes (>= 0; omitted defaults to 1).
Weight *float64 `yaml:"weight,omitempty" schema:"minimum=0"`
// Properties are the tile's custom properties, each a bool, an integer, a number or a string, as Tilemap.TileProperties returns them.
Properties map[string]any `yaml:"properties,omitempty"`
// Data holds typed custom data values keyed by names declared in TilesetDoc.CustomData (version 2).
Data map[string]any `yaml:"data,omitempty"`
// YSortOriginY optionally sets the tile's vertical Y-sort origin offset in points relative to the cell's bottom edge (version 2).
YSortOriginY *float32 `yaml:"ySortOriginY,omitempty"`
// Alternatives lists alternative variants of this tile in ascending Alt order (version 2).
Alternatives []TileAlternativeDoc `yaml:"alternatives,omitempty"`
// Shapes are the tile's collision shapes in its own coordinates, (0, 0) at its top left, as Tileset.Shapes holds them.
Shapes []TileShapeDoc `yaml:"shapes,omitempty"`
// Physics maps declared physics layer names (from TilesetDoc.PhysicsLayers) to this tile's collision shapes, one-way mode, surface velocity and material override (version 2).
Physics map[string]TilePhysicsDoc `yaml:"physics,omitempty"`
Navigation map[string]TileNavigationDoc `yaml:"navigation,omitempty"`
// Animation, when set, makes the tile cycle through these frames in a loop as Tilemap.Update advances time.
Animation []TileFrameDoc `yaml:"animation,omitempty"`
// Terrain names the entry of TilesetDoc.Terrains the tile belongs to.
Terrain string `yaml:"terrain,omitempty"`
// Neighbors lists the directions in which a cell of the same terrain lies next to a cell this tile fills: north, east, south and west, and for a blob terrain also northeast, southeast, southwest and northwest, each only with both edges beside it (northeast with north and east), since a corner matches only when they do. No two tiles of one terrain list the same set, and the tile that lists none is the terrain's default. It requires Terrain.
Neighbors []string `yaml:"neighbors,omitempty,flow"`
}
TileDoc describes one tile of a TilesetDoc.
type TileFlags ¶
type TileFlags uint32
TileFlags is a bitmask of gameplay and collision properties on a tile.
func (TileFlags) PhysicsFlags ¶
PhysicsFlags maps tilemap TileFlags to physics.TileFlags. TileSolid (bit 0) and TileOneWay (bit 1) map directly to physics.TileSolid and physics.TileOneWay, and game-defined bits 2..31 are preserved verbatim.
type TileFrameDoc ¶
type TileFrameDoc struct {
// Tile is the local ID of the tile the frame shows. It is required, so a frame never shows tile 0 by omission.
Tile int `yaml:"tile" schema:"required,minimum=0"`
// Duration is how long the frame shows, positive, written as a Go duration such as 150ms.
Duration time.Duration `yaml:"duration" schema:"required"`
}
TileFrameDoc is one frame of a tile's animation.
type TileLayer ¶
type TileLayer struct {
Name string
Width int
Height int
StartX int
StartY int
Data []uint32
// ChunkSize is the power-of-two edge length (in tiles) for sparse chunked layers; 0 selects a dense Data layer.
ChunkSize int
OffsetX float32
OffsetY float32
ParallaxX float32
ParallaxY float32
// HasParallax distinguishes explicit parallax factors (including 0, which fixes the layer to the screen)
// from an unset zero value on a struct literal, where a 0 factor defaults to 1.
// NewTileLayer, NewChunkedTileLayer, LoadTiled, and LoadLDtk default ParallaxX and ParallaxY to 1 with HasParallax true.
HasParallax bool
Opacity float32
TintColor core.Color
// Tinted distinguishes an explicit TintColor (including transparent black #00000000) from an untinted layer.
// Setting TintColor to a non-zero color also tints the layer when Tinted is false.
Tinted bool
Visible bool
// YSort enables per-tile Y-sorting for this layer. When true, visible tiles sort by
// their bottom edge (plus any per-tile PropSortOriginY property offset) and join a
// Y-sorted scene.Layer's draw list alongside sprites and drawables.
YSort bool
Properties Properties
// contains filtered or unexported fields
}
TileLayer is one row-major grid of tile GIDs drawn in map order, or a sparse chunked layer when ChunkSize > 0.
Its zero value is hidden and transparent with unset parallax defaulting to (1, 1); NewTileLayer and NewChunkedTileLayer return visible layers at full opacity with parallax (1, 1) and HasParallax set.
func NewChunkedTileLayer ¶
NewChunkedTileLayer returns a visible sparse chunked TileLayer at full opacity with parallax (1, 1), using a power-of-two chunkSize (defaulting to DefaultChunkSize when chunkSize <= 0).
func NewTileLayer ¶
NewTileLayer returns a visible TileLayer at full opacity with parallax (1, 1). When data is nil it allocates a width*height slice.
func (*TileLayer) AltAt ¶
AltAt returns the alternative tile ID stored at (col, row) in l, or 0 for the base tile or an unset cell.
func (*TileLayer) Chunk ¶
func (l *TileLayer) Chunk(coord ChunkCoord) *Chunk
Chunk returns the loaded chunk at coord, or nil if coord is not loaded.
func (*TileLayer) ChunkCoords ¶
func (l *TileLayer) ChunkCoords() []ChunkCoord
ChunkCoords returns the coordinates of all currently loaded chunks in deterministic row-major (Y, X) order.
func (*TileLayer) ChunkCount ¶
ChunkCount returns the number of currently loaded chunks in l, or 0 for dense or empty layers.
func (*TileLayer) ChunkTileBounds ¶
ChunkTileBounds returns the inclusive tile-coordinate bounding box [minCol, maxCol] × [minRow, maxRow] spanning all currently loaded chunks in l, or ok=false if no chunks are loaded.
func (*TileLayer) DirtyChunks ¶
func (l *TileLayer) DirtyChunks() []ChunkCoord
DirtyChunks returns the coordinates of all loaded chunks whose Dirty flag is set, sorted in deterministic (Y, X) order.
func (*TileLayer) EffectiveChunkSize ¶
EffectiveChunkSize returns the power-of-two chunk size for a chunked layer, or 0 for a dense layer.
func (*TileLayer) IsChunked ¶
IsChunked reports whether l uses sparse chunked storage rather than a dense Data slice.
func (*TileLayer) ModifiedChunks ¶
func (l *TileLayer) ModifiedChunks() []ChunkCoord
ModifiedChunks returns the coordinates of all loaded chunks whose Modified flag is set, sorted in deterministic (Y, X) order.
type TileMaterial ¶
type TileMaterial struct {
// Friction is the Coulomb friction coefficient when HasFriction is true.
Friction float32
HasFriction bool
// Restitution is the bounce coefficient in [0, 1] when HasRestitution is true.
Restitution float32
HasRestitution bool
}
TileMaterial holds resolved physics surface material properties for a physics layer or tile.
func (TileMaterial) Effective ¶
func (m TileMaterial) Effective(override TileMaterial) TileMaterial
Effective merges override onto m, replacing friction and restitution only where override sets them.
type TileNavigation ¶
TileNavigation holds one tile's walkable navigation polygon, area ID and optional flags on one navigation layer.
func (TileNavigation) Flipped ¶
func (tn TileNavigation) Flipped(flags uint32, tileWidth, tileHeight float32) TileNavigation
Flipped returns tn with its Polygon mirrored and rotated according to the Tiled flip bits in flags for a tile of tileWidth by tileHeight.
type TileNavigationDoc ¶
type TileNavigationDoc struct {
Polygon [][]float32 `yaml:"polygon,flow" schema:"required"`
Area uint8 `yaml:"area,omitempty"`
Flags uint32 `yaml:"flags,omitempty"`
}
TileNavigationDoc describes one tile's walkable navigation polygon, area ID and optional flags on one navigation layer in a version 2 TilesetDoc.
type TilePhysics ¶
type TilePhysics struct {
// Shapes are the tile's collision shapes on this physics layer in tile coordinates. When empty, the tile fills its cell on this layer.
Shapes []TileShape
// OneWay makes this tile's shapes on this physics layer block only from above.
OneWay bool
// VelocityX and VelocityY set the constant linear surface velocity in world units per second (for example a conveyor belt).
VelocityX float32
VelocityY float32
// AngularVelocity sets the constant angular surface velocity in radians per second about the tile center.
AngularVelocity float32
// MaterialPath is the optional physics material file path overriding the layer's MaterialPath.
MaterialPath string
// Material holds resolved per-tile material overrides (fields with HasFriction / HasRestitution override the layer's Material).
Material TileMaterial
}
TilePhysics holds one tile's collision shapes, one-way mode, constant surface velocity and material override on one physics layer.
func (TilePhysics) Flipped ¶
func (tp TilePhysics) Flipped(flags uint32, tileWidth, tileHeight float32) TilePhysics
Flipped returns tp mirrored and rotated according to the Tiled flip bits in flags for a tile of tileWidth by tileHeight. Shapes, linear surface velocity (VelocityX, VelocityY) and angular surface velocity (AngularVelocity) all follow the flip transform.
type TilePhysicsDoc ¶
type TilePhysicsDoc struct {
// Shapes are the tile's collision shapes on this physics layer, in tile coordinates. When omitted, the tile occupies its whole cell on this layer.
Shapes []TileShapeDoc `yaml:"shapes,omitempty"`
// OneWay makes this tile's shapes on this physics layer block only from above.
OneWay bool `yaml:"oneWay,omitempty"`
// VelocityX and VelocityY set the constant linear surface velocity in world units per second (for example a conveyor belt).
VelocityX float32 `yaml:"velocityX,omitempty"`
VelocityY float32 `yaml:"velocityY,omitempty"`
// AngularVelocity sets the constant angular surface velocity in radians per second about the tile center.
AngularVelocity float32 `yaml:"angularVelocity,omitempty"`
// Material optionally overrides the physics layer's material with a slash-separated path from the project root (such as "materials/ice.physics.yaml").
Material string `yaml:"material,omitempty"`
}
TilePhysicsDoc describes one tile's collision shapes, one-way mode, constant surface velocity and material override on one physics layer in a version 2 TilesetDoc.
type TileShape ¶
type TileShape struct {
// Shape is the kind of object the shape came from: ObjectRect, ObjectEllipse, ObjectPolygon or ObjectPolyline.
Shape ObjectShape
// Name and Type are the object's name and type (or class) in the collision editor.
Name string
Type string
// Points are the shape's vertices in the tile's coordinates.
Points []core.Point
// Properties are the object's custom properties.
Properties Properties
}
TileShape is one collision shape a tileset gives a tile, such as the rectangles, polygons and ellipses Tiled's collision editor stores on a tile.
Points are in the tile's own coordinates, with (0, 0) at the top-left of the tileset's tile and (TileWidth, TileHeight) at its bottom-right, already rotated by the object's rotation. A closed shape (every Shape except ObjectPolyline) is the polygon through its points, with an edge from the last point back to the first; an ellipse is approximated by EllipseShapeSegments points on its outline, and a rectangle has its four corners.
func (TileShape) Closed ¶
Closed reports whether s is a closed polygon rather than an open polyline.
func (TileShape) Flipped ¶
Flipped returns s mirrored and rotated as Tiled's flip bits in flags place a tile of tileWidth by tileHeight on a map, the same transform DrawLayer applies to the tile's image.
FlipDiagonal swaps the axes first, then FlipHorizontal mirrors left to right and FlipVertical top to bottom, so the eight combinations give every 90 degree rotation of a tile with and without a mirror. Flipped returns s unchanged when flags holds no flip bit, and a copy with new Points otherwise.
type TileShapeDoc ¶
type TileShapeDoc struct {
// Kind is "rect" or "ellipse", given by X, Y, Width and Height, or "polygon" or "polyline", given by Points. An ellipse becomes a polygon of EllipseShapeSegments edges.
Kind string `yaml:"kind" schema:"required,enum=rect|ellipse|polygon|polyline"`
// Name and Type label the shape for game code, as a Tiled object's name and type do.
Name string `yaml:"name,omitempty"`
Type string `yaml:"type,omitempty"`
// X and Y are the top left of a rect or ellipse's box, and Width and Height its positive size.
X float32 `yaml:"x,omitempty"`
Y float32 `yaml:"y,omitempty"`
Width float32 `yaml:"width,omitempty" schema:"minimum=0"`
Height float32 `yaml:"height,omitempty" schema:"minimum=0"`
// Points are the [x, y] vertices of a polygon (at least 3) or polyline (at least 2).
Points [][]float32 `yaml:"points,omitempty,flow"`
// Properties are the shape's custom properties, each a bool, an integer, a number or a string.
Properties map[string]any `yaml:"properties,omitempty"`
}
TileShapeDoc is one collision shape of a tile, in the tile's coordinates.
type TiledWorld ¶
type TiledWorld struct {
Maps []TiledWorldMap
Patterns []TiledWorldPattern
OnlyShowAdjacentMaps bool
}
TiledWorld is the parsed representation of a Tiled .world JSON file.
func ParseTiledWorld ¶
func ParseTiledWorld(data []byte) (*TiledWorld, error)
ParseTiledWorld parses a Tiled .world JSON file, compiling and validating every pattern regular expression.
Both explicit maps entries (fileName, x, y, optional width and height) and regex patterns (regexp, multiplierX, multiplierY, offsetX, offsetY, mapWidth, mapHeight) are supported.
Its errors are *loaderr.Error values that give the line, column and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
func (*TiledWorld) Resolve ¶
func (w *TiledWorld) Resolve(fileNames []string) []TiledWorldMap
Resolve expands w into every concrete map placement: explicit Maps first (in file order), followed by any candidate file in fileNames matching Patterns (sorted lexicographically, with the first matching pattern winning and files already listed in Maps skipped).
type TiledWorldLoader ¶
type TiledWorldLoader struct {
// LoadMap reads the raw .tmj JSON bytes for fileName (as written in the .world file or returned by ListFiles).
LoadMap func(fileName string) ([]byte, error)
// ListFiles returns candidate map filenames (relative to the .world file) to match against Patterns.
// Optional when the .world file defines no patterns.
ListFiles func() ([]string, error)
// Tilesets resolves external .tsj tilesets and images for each map when ResolveTilesets is nil.
Tilesets TilesetLoader
// ResolveTilesets optionally builds a map-specific TilesetLoader for fileName (for example when maps live in subdirectories).
ResolveTilesets func(fileName string) TilesetLoader
}
TiledWorldLoader configures how LoadTiledWorld reads .tmj map files and discovers pattern-matched filenames.
type TiledWorldMap ¶
TiledWorldMap describes one map placement inside a Tiled .world file.
func (TiledWorldMap) Bounds ¶
func (m TiledWorldMap) Bounds() core.Bounds
Bounds returns the map's world bounding rectangle. Width and Height may be 0 if omitted in the .world file.
func (TiledWorldMap) Origin ¶
func (m TiledWorldMap) Origin() core.Point
Origin returns the map's top-left world position (X, Y) in points.
type TiledWorldPattern ¶
type TiledWorldPattern struct {
Regexp string
MultiplierX int
MultiplierY int
OffsetX int
OffsetY int
MapWidth int
MapHeight int
// contains filtered or unexported fields
}
TiledWorldPattern describes one regex-based map grid pattern inside a Tiled .world file.
Capturing group 1 gives the grid X index and capturing group 2 (when present) gives the grid Y index; the world position is (gx*MultiplierX + OffsetX, gy*MultiplierY + OffsetY). Following Tiled's specification, MultiplierX/MapWidth and MultiplierY/MapHeight default to each other when one is 0.
func (*TiledWorldPattern) Match ¶
func (p *TiledWorldPattern) Match(fileName string) (TiledWorldMap, bool)
Match tests fileName against p's regular expression and returns its resolved TiledWorldMap when it matches. If fileName includes a directory prefix and does not match directly, its base filename is tested as well.
type Tilemap ¶
type Tilemap struct {
Width int
Height int
TileWidth float32
TileHeight float32
// Origin is the world-space position of the map's local (0, 0) point (typically the top-left corner of cell (0, 0)).
// Drawing, WorldBounds, TileOrigin, TileToWorld, WorldToTile, TilesInRect, Raycast, and AppendYSortTiles all honor Origin.
Origin core.Point
Orientation Orientation
StaggerAxis StaggerAxis
StaggerIndex StaggerIndex
HexSideLength float32
Infinite bool
Layers []TileLayer
ImageLayers []ImageLayer
Tilesets []*Tileset
Objects []ObjectLayer
Properties Properties
// Neighbours lists adjacent or overlapping levels in a multi-level world (populated by LDtk loaders).
Neighbours []LevelNeighbour
// Stats, when not nil, counts draw submissions and batch-break reasons for Draw, DrawLayer, DrawImageLayer, and DrawObjectLayer. Draw methods only add to it; call Reset once per frame for per-frame figures. Compiled to nothing under -tags release.
Stats *sprite.DrawCounter
// contains filtered or unexported fields
}
Tilemap is a tiled world of tile layers, image layers, tilesets, object layers, custom properties and per-tile collision flags.
func LoadLDtk ¶
func LoadLDtk(data []byte, levelIdentifier string, resolveImage func(relPath string) core.ImageSource) (*Tilemap, error)
LoadLDtk parses an LDtk JSON project and builds a Tilemap for the level matching levelIdentifier (or the first level when levelIdentifier is empty).
Tiles (gridTiles), AutoLayer (autoLayerTiles), IntGrid (intGridCsv mapped to TileSolid/TileFlags plus optional autoLayerTiles), and Entities (entityInstances mapped to ObjectLayer with fieldInstances properties) are supported, including LDtk flip bits (bit 0 = FlipHorizontal, bit 1 = FlipVertical). When multiple tiles occupy the same cell in a Tiles, AutoLayer, or IntGrid auto-layer, additional TileLayers named "<layer>#2", "<layer>#3", ... are emitted in LDtk's draw order so earlier tiles are preserved beneath later ones. Entity positions convert LDtk's pivot-relative px to top-left (X, Y) using __pivot (falling back to defs.entities pivotX/pivotY, or (0, 0) when omitted) and store the normalized anchor in Object.PivotX and Object.PivotY. For Free and GridVania layouts, the returned Tilemap's Origin is set from the level's (worldX, worldY) and its Neighbours are populated from __neighbours.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
func LoadLDtkWith ¶
func LoadLDtkWith(data []byte, levelIdentifier string, opts LDtkOptions) (*Tilemap, error)
LoadLDtkWith parses an LDtk JSON project with opts (including custom IntGrid-to-TileFlags mappings, such as those produced by project.File.LDtkOptions) and builds a Tilemap for the level matching levelIdentifier (or the first level when levelIdentifier is empty).
func LoadTiled ¶
func LoadTiled(data []byte, resolve TilesetLoader) (*Tilemap, error)
LoadTiled parses a Tiled map — either JSON (.tmj) or XML (.tmx) — into a Tilemap, loading any external .tsx or .tsj tilesets and .tx or .tj object templates and resolving tileset, collection-tile, and image-layer images through resolve.
Orthogonal, isometric, staggered, and hexagonal maps, infinite chunked maps, CSV, XML, and base64 tile data (uncompressed, zlib, and gzip), image layers, nested group layers, layer tint colors, embedded and external grid and image-collection tilesets (with tileoffset, objectalignment, and cross-format TMX/TSJ and TMJ/TSX references), GID flip flags, object layers (including tile objects, text objects, and .tx/.tj templates), custom properties, tile animations and the collision shapes Tiled's collision editor draws on tiles (into Tileset.Shapes) are supported. zstd compression is refused with an actionable fix hint.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it. An error in an external tileset or template names that file's source; for one in the map itself, a caller that read data from a file names it with loaderr.WithFile.
Example ¶
LoadTiled reads a map exported from Tiled, with its layers, tilesets and properties.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/tilemap"
"github.com/nsgo-dev/nsgo/core"
)
// level is a small Tiled JSON map (.tmj) with an embedded tileset whose tile 1 is marked solid by a custom property.
const level = `{
"type": "map", "orientation": "orthogonal", "renderorder": "right-down",
"width": 4, "height": 3, "tilewidth": 16, "tileheight": 16, "infinite": false,
"layers": [{
"type": "tilelayer", "name": "ground", "width": 4, "height": 3, "x": 0, "y": 0,
"opacity": 1, "visible": true,
"data": [0, 0, 0, 0,
0, 0, 0, 2,
2, 2, 2, 2]
}],
"tilesets": [{
"firstgid": 1, "name": "terrain", "image": "terrain.png", "imagewidth": 32, "imageheight": 16,
"tilewidth": 16, "tileheight": 16, "columns": 2, "tilecount": 2,
"tiles": [{"id": 1, "properties": [{"name": "kind", "type": "string", "value": "stone"}]}]
}]
}`
func main() {
m, err := tilemap.LoadTiled([]byte(level), tilemap.TilesetLoader{
LoadImage: func(path string) (core.ImageSource, error) { return core.ImageSource{URI: "asset:" + path}, nil },
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m.Width, m.Height, m.Layers[0].Name, m.TileAt(0, 3, 1))
fmt.Println(m.TileProperties(2)["kind"].Value)
fmt.Println(m.WorldToTile(core.Point{X: 40, Y: 20}))
}
Output: 4 3 ground 2 stone 2 1
func New ¶
New constructs an empty Tilemap of width by height tiles sized tileWidth by tileHeight points.
func NewInfinite ¶
NewInfinite constructs an unbounded Tilemap with Infinite set to true. Add sparse layers with NewChunkedTileLayer.
func (*Tilemap) AddTilesetDoc ¶
func (m *Tilemap) AddTilesetDoc(doc *TilesetDoc, firstGID uint32, assets TilesetAssets) (*Tileset, error)
AddTilesetDoc builds doc, which must validate, into a Tileset whose global tile IDs start at firstGID (1 when 0), resolving its image or atlas through assets, appends it to m.Tilesets in FirstGID order and sets the flags of its tiles on m (SetFlags). The new tileset carries doc's properties, per-tile properties, typed custom data, scene tiles, alternatives, collision shapes, physics layers, navigation layers, animations and terrain sets.
It refuses a tileset whose IDs would run past TileIDMask or overlap a tileset m already has, an atlas tileset without assets.Atlas, and atlas frames the atlas lacks.
Example ¶
ParseTileset reads a YAML tileset, and AddTilesetDoc builds it into a map's tileset with its flags, properties and collision shapes.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/tilemap"
)
// caveTileset is a YAML tileset (*.tileset.yaml): a grid image whose tile 0 is solid and whose tile 2 is a slope.
const caveTileset = `version: 1
name: cave
tileWidth: 16
tileHeight: 16
image: tiles/cave.png
columns: 4
tileCount: 4
tiles:
- id: 0
solid: true
properties:
kind: stone
- id: 2
shapes:
- kind: polygon
points: [[0, 16], [16, 0], [16, 16]]
`
func main() {
doc, err := tilemap.ParseTileset([]byte(caveTileset))
if err != nil {
fmt.Println(err)
return
}
m := tilemap.New(3, 1, 16, 16)
if _, err := m.AddTilesetDoc(doc, 1, tilemap.TilesetAssets{}); err != nil {
fmt.Println(err)
return
}
m.Layers = append(m.Layers, tilemap.NewTileLayer("ground", 3, 1, []uint32{1, 0, 3}))
fmt.Println(m.FlagsAt(0, 0) == tilemap.TileSolid, m.TileProperties(1)["kind"].Value)
fmt.Println(m.TileShapes(3)[0].Points)
}
Output: true stone [{0 16} {16 0} {16 16}]
func (*Tilemap) AppendYSortTiles ¶
AppendYSortTiles appends every visible non-empty tile of layer overlapping cam.VisibleBounds() (or every non-empty tile when cam is nil) to dst in deterministic painter's order, returning the updated slice.
Each tile's SortY is its bottom edge in world coordinates (offY + tileOriginY + TileHeight) plus any per-tile PropSortOriginY offset. Animated tiles resolve to their current frame at call time. Reusing dst across frames performs zero heap allocations once its capacity is warmed up.
func (*Tilemap) ApplyAutotile ¶
func (m *Tilemap) ApplyAutotile(layerIndex int, set AutotileSet, terrainID func(gid uint32) bool)
ApplyAutotile updates every terrain cell in layerIndex using set's bitmask-to-GID mapping.
terrainID reports whether a raw tile GID belongs to the terrain (nil treats any non-zero GID as terrain).
func (*Tilemap) ApplyTerrain ¶
ApplyTerrain updates every cell belonging to the named terrain in layerIndex using its autotile rules, returning false when the terrain is not defined on any tileset of m or layerIndex is out of range.
func (*Tilemap) AtlasBatching ¶
AtlasBatching reports whether plain orthogonal tiles use DrawAtlas runs.
func (*Tilemap) CacheDirtyChunks ¶
CacheDirtyChunks bakes every dirty or uncached loaded chunk in the chunked layer at layerIndex (in deterministic (Y, X) order) and returns how many chunks were baked.
func (*Tilemap) CacheStaticChunk ¶
func (m *Tilemap) CacheStaticChunk(layerIndex int, coord ChunkCoord, images map[string]image.Image) (*LayerCache, error)
CacheStaticChunk bakes one loaded chunk of a sparse chunked layer into a premultiplied *image.RGBA buffer so Draw and DrawLayer draw that chunk in a single DrawImageFrom operation.
If the chunk is empty (all GIDs are 0), any existing cache on that chunk is cleared and (nil, nil) is returned. Editing a tile inside another chunk never invalidates this chunk's cache.
func (*Tilemap) CacheStaticLayer ¶
func (m *Tilemap) CacheStaticLayer(layerIndex int, images map[string]image.Image) (*image.RGBA, core.ImageSource, error)
CacheStaticLayer bakes a static (non-animated) tile layer into a premultiplied *image.RGBA buffer and attaches it to the map so Draw and DrawLayer draw the layer in a single DrawImageFrom operation.
images maps tileset image URIs (with or without an "asset:" prefix) or tileset names to decoded image.Image pixel data; tilesets whose core.ImageSource.Pixels is already populated do not need an entry in images. Modifying the layer via SetTile or FillRect automatically marks the cache dirty.
func (*Tilemap) CellFlags ¶
CellFlags returns the per-cell override SetCellFlags set at (col, row) and whether one is set.
func (*Tilemap) ChunkAt ¶
func (m *Tilemap) ChunkAt(layerIndex int, coord ChunkCoord) *Chunk
ChunkAt returns the loaded chunk at coord in layerIndex, or nil if layerIndex is out of range, dense, or does not currently have coord loaded.
func (*Tilemap) ChunkCache ¶
func (m *Tilemap) ChunkCache(layerIndex int, coord ChunkCoord) *LayerCache
ChunkCache returns the static cache entry for coord in the chunked layer at layerIndex, or nil if absent or uncached.
func (*Tilemap) ChunkCoordForTile ¶
func (m *Tilemap) ChunkCoordForTile(layerIndex, col, row int) (ChunkCoord, bool)
ChunkCoordForTile converts tile (col, row) to the ChunkCoord owning it in layerIndex. Returns ok=false if layerIndex is out of range or not a chunked layer.
func (*Tilemap) ClearCellFlags ¶
ClearCellFlags removes any per-cell flag override at (col, row), restoring its tile-ID flags.
func (*Tilemap) ClearChunkCache ¶
func (m *Tilemap) ClearChunkCache(layerIndex int, coord ChunkCoord)
ClearChunkCache removes the static cache for coord in layerIndex without affecting other chunks.
func (*Tilemap) ClearLayerCache ¶
ClearLayerCache removes any cached image for layerIndex (or all per-chunk caches on a chunked layer).
func (*Tilemap) CustomDataLayer ¶
func (m *Tilemap) CustomDataLayer(name string) (CustomDataLayer, bool)
CustomDataLayer returns the first declared CustomDataLayer named name across m's tilesets, and whether one exists.
func (*Tilemap) CustomDataLayers ¶
func (m *Tilemap) CustomDataLayers() []CustomDataLayer
CustomDataLayers returns the unique typed custom data layers declared across m's tilesets, in declaration order.
func (*Tilemap) DistinctZs ¶
DistinctZs returns the sorted distinct draw Z values present across m's visible layers. Regular tiles, image layers, and object layers live at Z == 0; alternative tiles with non-zero Z add their Z values.
func (*Tilemap) Draw ¶
Draw draws every visible tile layer, image layer, and object layer (tile objects) into d in map layer order, culling to cam's visible world region when cam is non-nil.
Draw draws in world coordinates: call cam.Apply(d) before Draw (and any world-space sprites) to position the view.
func (*Tilemap) DrawImageLayer ¶
func (m *Tilemap) DrawImageLayer(d *core.Drawing, layer *ImageLayer, cam *Camera)
DrawImageLayer draws one image layer into d, applying its visibility, opacity, tint, offset, parallax factor, and repeat flags.
func (*Tilemap) DrawLayer ¶
DrawLayer draws one tile layer into d, visiting only the visible tiles overlapping cam.VisibleBounds() when cam is non-nil.
When layer.YSort is true, visible tiles are sorted in stable ascending SortY order (respecting per-tile PropSortOriginY offsets) and drawn individually without using any static layer cache. Otherwise, when the layer has a clean static cache created via CacheStaticLayer, DrawLayer draws it in a single DrawImageFrom operation.
func (*Tilemap) DrawObjectLayer ¶
func (m *Tilemap) DrawObjectLayer(d *core.Drawing, layer *ObjectLayer, cam *Camera)
DrawObjectLayer draws every visible tile object in layer into d in object order, applying layer visibility, opacity, tint, offset, parallax, object size, rotation, flip flags, tileset tileoffset, and tileset objectalignment, culling to cam.VisibleBounds() when cam is non-nil.
func (*Tilemap) DrawZ ¶
DrawZ draws every visible layer element of m whose draw Z equals z into d, culling to cam when non-nil. Image layers and object layers draw at z == 0; tile layers draw only cells whose effective Z equals z.
func (*Tilemap) FillRect ¶
FillRect writes gid across [col, col+w) x [row, row+h) in layerIndex.
On dense layers, out-of-bounds portions are clipped; on sparse chunked layers, arbitrary negative and positive rectangles are supported and only chunks whose tiles actually change are marked Dirty and Modified. Non-positive sizes are ignored.
func (*Tilemap) Flags ¶
Flags returns the TileFlags set on global tile ID tileID with SetFlags or from its tileset's properties, ignoring flip bits and any per-cell override.
func (*Tilemap) FlagsAt ¶
FlagsAt returns the combined TileFlags at (col, row) across all tile layers, or 0 if out of bounds.
func (*Tilemap) GridOrigin ¶
GridOrigin returns the world-space origin of cell (0, 0), satisfying physics.TileGridOrigin.
func (*Tilemap) GridSize ¶
GridSize returns the map's width and height in tile columns and rows, satisfying physics.TileGrid.
func (*Tilemap) HasAltZ ¶
HasAltZ reports whether any visible tile layer of m has at least one cell using an alternative tile with Z != 0.
func (*Tilemap) HasSceneTiles ¶
HasSceneTiles reports whether any tileset of m declares at least one scene tile.
func (*Tilemap) HasYSortLayers ¶
HasYSortLayers reports whether m contains at least one visible tile layer with YSort enabled.
func (*Tilemap) HexDistance ¶
HexDistance returns the grid step distance between hexagonal cells (c1, r1) and (c2, r2).
func (*Tilemap) HexNeighbors ¶
HexNeighbors returns the 6 hexagonal neighbors of offset cell (col, row) for the map's StaggerAxis and StaggerIndex.
func (*Tilemap) ImageLayer ¶
func (m *Tilemap) ImageLayer(name string) *ImageLayer
ImageLayer returns the first image layer with the given name, or nil if none matches.
func (*Tilemap) InvalidateChunkCache ¶
func (m *Tilemap) InvalidateChunkCache(layerIndex int, coord ChunkCoord)
InvalidateChunkCache marks only the chunk at coord in layerIndex dirty without disturbing other chunks.
func (*Tilemap) InvalidateLayerCache ¶
InvalidateLayerCache marks any cached image for layerIndex dirty so subsequent Draw calls fall back to live tile drawing until recached. For sparse chunked layers, all loaded chunks in layerIndex are marked dirty.
func (*Tilemap) Layer ¶
Layer returns the first tile layer with the given name, or nil if none matches.
func (*Tilemap) LayerCache ¶
func (m *Tilemap) LayerCache(layerIndex int) *LayerCache
LayerCache returns the static cache entry for layerIndex, or nil if that layer has not been cached.
func (*Tilemap) NavigationLayer ¶
func (m *Tilemap) NavigationLayer(name string) (TilesetNavigationLayer, bool)
NavigationLayer returns the first declared TilesetNavigationLayer named name across m's tilesets, and whether one exists.
func (*Tilemap) NavigationLayers ¶
func (m *Tilemap) NavigationLayers() []TilesetNavigationLayer
NavigationLayers returns the unique navigation layers declared across m's tilesets, in declaration order.
func (*Tilemap) ObjectLayer ¶
func (m *Tilemap) ObjectLayer(name string) *ObjectLayer
ObjectLayer returns the first object layer with the given name, or nil if none matches.
func (*Tilemap) OnTileChange ¶
func (m *Tilemap) OnTileChange(fn TileChangeFunc)
OnTileChange registers fn to be called whenever a cell changes via SetTile, SetTileAlt, SetTileCell, FillRect, PutChunk, or RemoveChunk.
func (*Tilemap) PhysicsLayer ¶
func (m *Tilemap) PhysicsLayer(name string) (TilesetPhysicsLayer, bool)
PhysicsLayer returns the first declared TilesetPhysicsLayer named name across m's tilesets, and whether one exists.
func (*Tilemap) PhysicsLayers ¶
func (m *Tilemap) PhysicsLayers() []TilesetPhysicsLayer
PhysicsLayers returns the unique physics layers declared across m's tilesets, in declaration order (first declaration wins for a repeated name).
func (*Tilemap) PutChunk ¶
PutChunk installs chunk into the chunked layer at layerIndex, replacing any existing chunk at chunk.Coord.
chunk.Size must match the layer's EffectiveChunkSize() and len(chunk.Tiles) must equal chunk.Size*chunk.Size. The installed chunk's Dirty flag is set to true so any static chunk cache is rebuilt, while chunk.Modified is preserved as passed.
func (*Tilemap) Raycast ¶
Raycast traces the line segment from -> to and returns the first tile matching mask (or any non-empty tile when mask == 0).
Example ¶
SetFlags marks tile kinds as solid, and Raycast finds the first solid tile along a line, as a line-of-sight or ground check does.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/tilemap"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
m := tilemap.New(8, 4, 16, 16, tilemap.NewGridTileset(1, core.ImageSource{URI: "asset:terrain.png"}, 16, 16, 2, 2))
m.Layers = append(m.Layers, tilemap.NewTileLayer("ground", 8, 4, make([]uint32, 8*4)))
m.FillRect(0, 5, 0, 1, 4, 2) // a wall at column 5
m.SetFlags(2, tilemap.TileSolid)
hit, ok := m.Raycast(core.Point{X: 8, Y: 24}, core.Point{X: 120, Y: 24}, tilemap.TileSolid)
fmt.Println(ok, hit.Col, hit.Row, hit.Point, hit.Normal)
}
Output: true 5 1 {80 24} {-1 0}
func (*Tilemap) RemoveChunk ¶
func (m *Tilemap) RemoveChunk(layerIndex int, coord ChunkCoord) *Chunk
RemoveChunk unloads and returns the chunk at coord from layerIndex (clearing its static cache), or returns nil if layerIndex is out of range, dense, or coord is not loaded.
func (*Tilemap) SceneTile ¶
SceneTile returns the SceneTile declared for gid on its tileset (ignoring flip bits), and whether gid is a scene tile.
func (*Tilemap) SetAtlasBatching ¶
SetAtlasBatching enables DrawAtlas batching for compatible tiles in orthogonal, projected and chunked layers. It is opt-in so existing draw-operation ordering remains stable for callers that inspect operations; tinted and flipped tiles retain their per-tile paths, while animated tiles use their current frame.
func (*Tilemap) SetAutotile ¶
func (m *Tilemap) SetAutotile(layerIndex, col, row int, placed bool, set AutotileSet, terrainID func(gid uint32) bool)
SetAutotile places (placed=true) or removes (placed=false) a terrain tile at (col, row) in layerIndex and updates that cell and all 8 surrounding terrain neighbors cleanly.
terrainID reports whether a raw tile GID belongs to the terrain (nil treats any non-zero GID as terrain).
func (*Tilemap) SetCellFlags ¶
SetCellFlags overrides the flags at a single map cell (col, row), taking precedence over per-tile flags. On maps with sparse chunked layers (or Infinite=true), negative and arbitrary positive coordinates are supported.
func (*Tilemap) SetFlags ¶
SetFlags sets the TileFlags associated with global tile ID tileID (flip bits are ignored).
func (*Tilemap) SetLayerYSort ¶
SetLayerYSort enables or disables per-tile Y-sorting on m.Layers[layerIndex]. Out-of-range layer indices are ignored.
func (*Tilemap) SetTerrain ¶
func (m *Tilemap) SetTerrain(layerIndex, col, row int, set *WangSet, terrain uint8, rng TerrainRand)
SetTerrain paints terrain (1-based index into set.Colors, or 0 to erase) at (col, row) in layerIndex, choosing tiles matching every neighbor's shared edges and corners for corner, edge, and mixed Wang sets.
Works on both orthogonal and isometric maps as well as dense and sparse chunked layers. When multiple tiles tie for best match, SetTerrain picks deterministically by tile probability using rng (or the lowest local TileID when rng is nil).
func (*Tilemap) SetTerrainRect ¶
func (m *Tilemap) SetTerrainRect(layerIndex, col, row, w, h int, set *WangSet, terrain uint8, rng TerrainRand)
SetTerrainRect paints terrain (1-based index into set.Colors, or 0 to erase) across [col, col+w) x [row, row+h) in layerIndex, updating painted cells and all affected neighbors so multi-terrain transitions remain seamless.
On dense layers, out-of-bounds portions are clipped; on sparse chunked layers, arbitrary negative and positive rectangles are supported. Non-positive sizes are ignored.
func (*Tilemap) SetTerrainTile ¶
SetTerrainTile places (placed=true) or removes (placed=false) a tile of the named terrain at (col, row) in layerIndex and updates that cell and its neighbors using SetAutotile, returning false when the terrain is not defined on any tileset of m or layerIndex is out of range.
func (*Tilemap) SetTile ¶
SetTile writes a raw GID at (col, row) in layerIndex; out-of-bounds calls on dense layers are ignored.
On sparse chunked layers, arbitrary negative and positive coordinates are supported, allocating a chunk on demand when gid != 0, and marking only that chunk Dirty and Modified (leaving all other chunks and their static caches clean). On dense layers, any cached static image for layerIndex is marked dirty so subsequent draws reflect the change immediately, and collision queries (FlagsAt, TilesInRect, Raycast) observe the updated tile at once.
func (*Tilemap) SetTileAlt ¶
SetTileAlt writes gid and alternative ID alt at (col, row) in layerIndex. When gid&TileIDMask == 0 or alt <= 0, the alternative ID at (col, row) is cleared. Out-of-bounds calls on dense layers are ignored.
func (*Tilemap) SetTileCell ¶
SetTileCell writes cell (raw GID and alternative ID) at (col, row) in layerIndex.
func (*Tilemap) SetTileSortOriginY ¶
SetTileSortOriginY sets the per-tile vertical Y-sort origin offset (in points relative to the tile's default bottom edge) on gid's tileset under PropSortOriginY.
Negative values shift the sort line upward (for example into a tall tree's trunk); positive values shift it downward.
func (*Tilemap) Terrain ¶
Terrain returns the terrain set named name of the first of m's tilesets that defines one, or nil.
func (*Tilemap) TileAltAt ¶
TileAltAt returns the alternative tile ID at (col, row) in layerIndex, or 0 for the base tile, empty, or out-of-bounds cells.
func (*Tilemap) TileAlternative ¶
func (m *Tilemap) TileAlternative(gid uint32, alt int) (TileAlternative, bool)
TileAlternative returns the TileAlternative defined for gid and alt on its tileset, and whether one exists.
func (*Tilemap) TileAt ¶
TileAt returns the raw GID (including flip flags) at (col, row) in layerIndex, or 0 if out of bounds or unloaded. For sparse chunked layers, negative and arbitrary positive coordinates are supported.
func (*Tilemap) TileBox ¶
TileBox returns the size of gid's tile in its tileset, which is the box its collision shapes are measured in, falling back to the map's tile size when the tileset gives none or gid has no tileset.
func (*Tilemap) TileCellAt ¶
TileCellAt returns the TileCell (raw GID and alternative ID) at (col, row) in layerIndex.
func (*Tilemap) TileCellData ¶
TileCellData returns the typed custom data value for cell on declared custom data layer name, checking the cell's alternative overrides first, then the base tile, then the layer's declared Default.
func (*Tilemap) TileCellShapes ¶
TileCellShapes returns the collision shapes of cell, using its alternative's Shapes override when defined (falling back to the base tile's Shapes) and applying the composed flip flags of the alternative and cell.
func (*Tilemap) TileCellSortOriginY ¶
TileCellSortOriginY returns the vertical Y-sort origin offset for cell, preferring its alternative's YSortOriginY, then the base tile's YAML ySortOriginY, then PropSortOriginY / alias custom properties.
func (*Tilemap) TileChangesSince ¶
TileChangesSince calls fn for each cell (col, row) whose tile or per-cell flags changed (through SetTile, FillRect, SetCellFlags or ClearCellFlags) since rev, and returns the current revision and whether every change since rev fit in the log.
When ok is false (for example after a bulk FillRect, a PutChunk or RemoveChunk, a SetFlags call, which can change every cell showing the tile, or more edits than the log holds), callers should rebuild from the full map.
func (*Tilemap) TileCollisionGroup ¶
func (m *Tilemap) TileCollisionGroup(gid uint32) (ObjectLayer, bool)
TileCollisionGroup returns the collision ObjectLayer authored on gid's tile in its tileset (flip bits ignored), and whether the tile defines one.
func (*Tilemap) TileData ¶
TileData returns the typed custom data value for gid on declared custom data layer name, falling back to the layer's declared Default when the tile omits name.
func (*Tilemap) TileDataAt ¶
TileDataAt returns the typed custom data value at (col, row) in layerIndex for custom data layer name, respecting any alternative tile at that cell.
func (*Tilemap) TileDataBool ¶
TileDataBool returns the boolean custom data value for gid on custom data layer name.
func (*Tilemap) TileDataFloat ¶
TileDataFloat returns the floating-point custom data value for gid on custom data layer name (accepting float64 or int).
func (*Tilemap) TileDataInt ¶
TileDataInt returns the integer custom data value for gid on custom data layer name.
func (*Tilemap) TileDataString ¶
TileDataString returns the string custom data value for gid on custom data layer name.
func (*Tilemap) TileFlagsAt ¶
TileFlagsAt returns the collision flags at (col, row) mapped to physics.TileFlags, satisfying physics.TileGrid.
func (*Tilemap) TileNavigation ¶
func (m *Tilemap) TileNavigation(gid uint32, layerName string) (TileNavigation, bool)
TileNavigation returns the TileNavigation definition of gid's tile on navigation layer layerName, flipped and rotated by gid's flip bits, and whether the tile defines one on that layer.
func (*Tilemap) TileOrigin ¶
TileOrigin returns the top-left corner of tile (col, row)'s bounding box in world coordinates.
func (*Tilemap) TilePhysics ¶
func (m *Tilemap) TilePhysics(gid uint32, layerName string) (TilePhysics, bool)
TilePhysics returns the TilePhysics definition of gid's tile on physics layer layerName, flipped and rotated by gid's flip bits, and whether the tile defines one on that layer.
func (*Tilemap) TileProperties ¶
func (m *Tilemap) TileProperties(gid uint32) Properties
TileProperties returns the custom properties attached to gid in its tileset, or nil if none exist.
func (*Tilemap) TileRevision ¶
TileRevision returns a counter incremented whenever SetTile, FillRect, PutChunk or RemoveChunk changes a tile cell, or SetFlags, SetCellFlags or ClearCellFlags changes collision flags.
func (*Tilemap) TileShapes ¶
TileShapes returns the collision shapes of gid's tile, flipped and rotated by gid's flip bits in the coordinates of its tileset's tile, or nil when the tile has none.
An unflipped gid returns the tileset's own slice, which the caller must not modify.
func (*Tilemap) TileSize ¶
TileSize returns the width and height of one tile in world coordinates, satisfying physics.TileGrid.
func (*Tilemap) TileSortOriginY ¶
TileSortOriginY returns the per-tile vertical Y-sort origin offset configured on gid (checking YAML ySortOriginY, PropSortOriginY, "y_sort_origin", and "ysort_origin"), or 0 if unset.
func (*Tilemap) TileToWorld ¶
TileToWorld returns the world-space center of tile (col, row) for the map's Orientation and Origin.
WorldToTile(TileToWorld(col, row)) round-trips back to (col, row) for orthogonal, isometric, staggered, and hexagonal maps.
func (*Tilemap) TilesInRect ¶
TilesInRect returns every map cell overlapping r whose flags match mask (or every non-empty cell when mask == 0), in row-major order.
Cells are half-open [col*TileWidth, (col+1)*TileWidth) x [row*TileHeight, (row+1)*TileHeight), so a rectangle touching an adjacent tile's edge or corner does not include it.
func (*Tilemap) TilesetForGID ¶
TilesetForGID finds the tileset owning gid and returns it along with the 0-based local tile ID.
func (*Tilemap) VisitLayers ¶
func (m *Tilemap) VisitLayers(fn func(tile *TileLayer, img *ImageLayer))
VisitLayers calls fn for every tile layer and image layer of m in map draw order. Exactly one of tile or img is non-nil on each call.
func (*Tilemap) WangSet ¶
WangSet returns the first WangSet named name across all tilesets of m, or nil if none matches.
func (*Tilemap) WorldBounds ¶
WorldBounds returns the world rectangle covering the whole map for its Orientation and Origin. For unbounded chunked maps with non-positive Width/Height, it returns the bounding box of currently loaded chunks.
type Tileset ¶
type Tileset struct {
Name string
FirstGID uint32
Image core.ImageSource
Atlas *sprite.Atlas
Frames []sprite.Frame
// TileImages holds per-tile images for image-collection tilesets, keyed by 0-based local tile ID.
TileImages map[uint32]TileImage
TileWidth float32
TileHeight float32
TileOffsetX float32
TileOffsetY float32
ObjectAlignment ObjectAlignment
Columns int
TileCount int
Spacing float32
Margin float32
Properties Properties
// TileProperties holds custom properties keyed by 0-based local tile ID.
TileProperties map[uint32]Properties
// TileProbabilities holds per-tile random selection weights keyed by 0-based local tile ID (unset defaults to 1).
TileProbabilities map[uint32]float64
// Animations holds tile animations keyed by 0-based local tile ID.
Animations map[uint32]*TileAnimation
// TileCollisions holds each tile's collision object group as authored in Tiled's collision editor (.tmj/.tsj/.tmx/.tsx), keyed by 0-based local tile ID.
TileCollisions map[uint32]*ObjectLayer
// Shapes holds the collision shapes of tiles keyed by 0-based local tile ID, such as the ones Tiled's collision editor draws; an animated tile keeps the shapes of its own ID whichever frame shows.
Shapes map[uint32][]TileShape
// PhysicsLayers are the tileset's declared named physics layers, in declaration order.
PhysicsLayers []TilesetPhysicsLayer
// TilePhysics holds per-tile physics layer definitions keyed by 0-based local tile ID, then physics layer name.
TilePhysics map[uint32]map[string]TilePhysics
NavigationLayers []TilesetNavigationLayer
TileNavigation map[uint32]map[string]TileNavigation
// CustomDataLayers are the tileset's declared typed custom data layers, in declaration order.
CustomDataLayers []CustomDataLayer
// TileCustomData holds per-tile typed custom data values keyed by 0-based local tile ID, then custom data layer name.
TileCustomData map[uint32]map[string]any
// SceneTiles holds scene tile definitions keyed by 0-based local tile ID.
SceneTiles map[uint32]SceneTile
// TileAlternatives holds alternative tile variants keyed by 0-based local tile ID, then positive alternative ID.
TileAlternatives map[uint32]map[int]TileAlternative
// TileSortOrigins holds explicit YAML per-tile Y-sort origin offsets keyed by 0-based local tile ID.
TileSortOrigins map[uint32]float32
// WangSets holds Tiled Wang sets (terrain sets) defined on this tileset.
WangSets []WangSet
// Terrains are the tileset's terrain sets, such as the ones a YAML tileset defines (TilesetDoc.Terrains), in their order there; Tilemap.Terrain finds one by name.
Terrains []*Terrain
}
Tileset maps global tile IDs starting at FirstGID to rectangles of a grid image, frames of a sprite.Atlas, or per-tile images of an image-collection tileset.
func NewAtlasTileset ¶
NewAtlasTileset builds a Tileset from atlas whose local tile IDs (0, 1, ...) correspond to frameNames in order.
FirstGID defaults to 1 when 0.
func NewGridTileset ¶
func NewGridTileset(firstGID uint32, img core.ImageSource, tileWidth, tileHeight float32, columns, tileCount int) *Tileset
NewGridTileset builds a uniform grid Tileset over img with columns tiles per row.
FirstGID defaults to 1 when 0.
func (*Tileset) TileProbability ¶
TileProbability returns the selection probability for localID, defaulting to 1 when unset.
type TilesetAssets ¶
type TilesetAssets struct {
// Image returns the image at a tileset's Image path. When nil the image is core.ImageSource{URI: path}.
Image func(path string) (core.ImageSource, error)
// Atlas returns the atlas a tileset's Atlas names. It is required for an atlas tileset.
Atlas func(name string) (*sprite.Atlas, error)
// LayerMask optionally resolves collision layer names from PhysicsLayers[*].Layer / Mask into a physics.LayerMask (for example using project.Physics.LayerMask2D). When nil, Layer and Mask remain 0 (physics.LayerAll) while LayerNames and MaskNames are preserved.
LayerMask func(names []string) (physics.LayerMask, error)
// PhysicsMaterial optionally resolves a physics material file path (such as "materials/stone.physics.yaml") into a TileMaterial. When nil, MaterialPath is preserved and Material stays zero.
PhysicsMaterial func(path string) (TileMaterial, error)
}
TilesetAssets resolves the image, atlas, collision layer names and physics materials a TilesetDoc names, for Tilemap.AddTilesetDoc.
type TilesetDoc ¶
type TilesetDoc struct {
// Version is the schema version, from TilesetFormatVersion (1) to TilesetCurrentVersion (2).
Version int `yaml:"version" schema:"required"`
// Name is the tileset's human-readable name.
Name string `yaml:"name,omitempty"`
// TileWidth and TileHeight are each tile's size in points; both must be positive.
TileWidth int `yaml:"tileWidth" schema:"required,exclusiveMinimum=0"`
TileHeight int `yaml:"tileHeight" schema:"required,exclusiveMinimum=0"`
// Image is the grid image the tiles are cut from, a slash-separated path from the project root such as "tiles/cave.png". It requires Columns and TileCount.
Image string `yaml:"image,omitempty"`
// Columns is how many tiles one row of Image holds.
Columns int `yaml:"columns,omitempty" schema:"minimum=0"`
// TileCount is how many tiles Image holds, at most MaxTilesetTiles.
TileCount int `yaml:"tileCount,omitempty" schema:"minimum=0"`
// Spacing is the gap in points between neighbouring tiles of Image, and Margin the gap around its edge.
Spacing int `yaml:"spacing,omitempty" schema:"minimum=0"`
Margin int `yaml:"margin,omitempty" schema:"minimum=0"`
// Atlas names the sprite atlas the tiles are frames of, as a scene's sprites name atlases. It requires Frames.
Atlas string `yaml:"atlas,omitempty"`
// Frames are the names of Atlas's frames that are the tiles, in local ID order, at most MaxTilesetTiles and each named once.
Frames []string `yaml:"frames,omitempty"`
// Properties are custom properties of the whole tileset, each a bool, an integer, a number or a string. EncodeTileset writes a whole-number float with a decimal point (2.0), so that it reads back as a float.
Properties map[string]any `yaml:"properties,omitempty"`
// PhysicsLayers declares named physics layers for version 2 tilesets, each with collision layer/mask names and an optional default physics material file.
PhysicsLayers []TilesetPhysicsLayerDoc `yaml:"physicsLayers,omitempty"`
NavigationLayers []TilesetNavigationLayerDoc `yaml:"navigationLayers,omitempty"`
// CustomData declares named, typed custom data layers for version 2 tilesets, validated on load for every tile's Data map.
CustomData []CustomDataLayerDoc `yaml:"customData,omitempty"`
// Scenes declares scene tiles for version 2 tilesets, each mapping a local tile ID to a scene file instanced when placed on a tile layer.
Scenes []SceneTileDoc `yaml:"scenes,omitempty"`
// Terrains are the terrain sets the tiles' Terrain fields name, each with a unique name.
Terrains []TerrainDoc `yaml:"terrains,omitempty"`
// Tiles describe the tiles that carry anything beyond their picture, in ascending ID order with each ID at most once. A tile left out has no properties, flags, shapes, physics, navigation, custom data, alternatives, animation or terrain.
Tiles []TileDoc `yaml:"tiles,omitempty"`
}
TilesetDoc is a versioned YAML tileset (*.tileset.yaml): what each tile of one image or sprite atlas is, its custom properties, collision flags and shapes, physics layers, navigation layers, animation and terrain, defined once so that maps only place tiles. Tilemap.AddTilesetDoc builds it into a Tileset.
A tileset draws its tiles either from a grid image (Image, Columns and TileCount, with optional Spacing and Margin) or from frames of a sprite atlas (Atlas and Frames); exactly one of Image and Atlas is set. A tile's local ID is its index in the grid, row by row from the top left, or in Frames, starting at 0.
func LoadTilesetFS ¶
func LoadTilesetFS(fsys fs.FS, path string) (*TilesetDoc, error)
LoadTilesetFS reads the tileset file at path from fsys and parses it with ParseTileset, naming the file in its errors.
func ParseTileset ¶
func ParseTileset(data []byte) (*TilesetDoc, error)
ParseTileset decodes and validates a YAML tileset document (ValidateTileset), refusing unknown fields, a key given twice and a trailing document.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
func (*TilesetDoc) Clone ¶
func (doc *TilesetDoc) Clone() *TilesetDoc
Clone returns a deep copy of doc, or nil when doc is nil.
func (*TilesetDoc) Count ¶
func (doc *TilesetDoc) Count() int
Count returns how many image or atlas tiles doc defines: its TileCount for a grid image, or the length of its Frames for an atlas.
func (*TilesetDoc) HasAlternative ¶
func (doc *TilesetDoc) HasAlternative(tileID, alt int) bool
HasAlternative reports whether tileID declares an alternative with ID alt (always true when alt == 0 and doc.HasTile(tileID)).
func (*TilesetDoc) HasTile ¶
func (doc *TilesetDoc) HasTile(id int) bool
HasTile reports whether id is a valid local tile ID in doc: either an image/atlas tile (0 <= id < doc.Count()) or a declared scene tile (doc.SceneTile(id) != nil).
func (*TilesetDoc) SceneTile ¶
func (doc *TilesetDoc) SceneTile(id int) *SceneTileDoc
SceneTile returns a pointer to the SceneTileDoc with local ID id in doc, or nil when none matches.
type TilesetLoader ¶
type TilesetLoader struct {
// LoadTileset reads the raw bytes of an external tileset file (.tsx or .tsj) given its source path in the map (or resolved relative to a template's directory).
// When nil, LoadTiled falls back to LoadJSON.
LoadTileset func(source string) ([]byte, error)
// LoadJSON reads the raw bytes of an external tileset file (.tsj or .tsx) given its source path in the map.
// Kept for compatibility with existing callers; used when LoadTileset is nil.
LoadJSON func(source string) ([]byte, error)
// LoadTemplate reads the raw bytes of an external object template file (.tx or .tj) given its source path in the map.
LoadTemplate func(source string) ([]byte, error)
// LoadImage returns the ImageSource for a tileset, tile, or image-layer image path (resolved relative to the external tileset's or template's directory when loaded from one).
LoadImage func(imagePath string) (core.ImageSource, error)
}
TilesetLoader resolves external tileset files, object template files, and images referenced by a Tiled map.
Any callback may be nil: LoadTileset (or LoadJSON as a fallback) is only needed when the map or a template references an external .tsx or .tsj tileset, LoadTemplate is only needed when an object references an external .tx or .tj template, and LoadImage defaults to core.ImageSource{URI: imagePath}.
type TilesetNavigationLayer ¶
TilesetNavigationLayer declares one named navigation layer on a Tileset.
type TilesetNavigationLayerDoc ¶
type TilesetNavigationLayerDoc struct {
Name string `yaml:"name" schema:"required,minLength=1"`
Flags uint32 `yaml:"flags,omitempty"`
}
TilesetNavigationLayerDoc declares one named navigation layer in a version 2 TilesetDoc.
type TilesetPhysicsLayer ¶
type TilesetPhysicsLayer struct {
// Name uniquely identifies the physics layer on this tileset.
Name string
// LayerNames are the authored collision layer names (matching game.yaml physics.layers).
LayerNames []string
// MaskNames are the authored collision mask names (matching game.yaml physics.layers).
MaskNames []string
// Layer is the resolved 2D collision layer bitmask (0 defaults to physics.LayerAll).
Layer physics.LayerMask
// Mask is the resolved 2D collision filter mask (0 defaults to physics.LayerAll).
Mask physics.LayerMask
// MaterialPath is the optional physics material file path authored on this layer (such as "materials/stone.physics.yaml").
MaterialPath string
// Material holds the resolved material properties for this layer.
Material TileMaterial
}
TilesetPhysicsLayer declares one named physics collision layer on a Tileset.
type TilesetPhysicsLayerDoc ¶
type TilesetPhysicsLayerDoc struct {
// Name uniquely identifies the physics layer within the tileset; tiles reference it under TileDoc.Physics.
Name string `yaml:"name" schema:"required,minLength=1"`
// Layer names the collision layers this layer belongs to (matching game.yaml physics.layers). Empty defaults to all layers.
Layer []string `yaml:"layer,omitempty,flow"`
// Mask names the collision layers this layer collides with (matching game.yaml physics.layers). Empty defaults to all layers.
Mask []string `yaml:"mask,omitempty,flow"`
// Material optionally names a shared physics material file (such as "materials/stone.physics.yaml") by its slash-separated path from the project root.
Material string `yaml:"material,omitempty"`
}
TilesetPhysicsLayerDoc declares one named physics collision layer in a version 2 TilesetDoc.
type TwoFingerGesture ¶
type TwoFingerGesture interface {
// Pan returns the midpoint movement since the previous step and whether exactly two fingers are down.
Pan() (core.Point, bool)
// PinchCenter returns the midpoint of the two fingers in view points.
PinchCenter() core.Point
// PinchStepScale returns how much the fingers' spacing changed since the previous step, as a ratio, or 1 when it did not change.
PinchStepScale() float64
}
TwoFingerGesture is the per-step continuous state of a two-finger pan and pinch that ApplyPinchPan applies, such as input.GestureRecognizer.
type WangColor ¶
type WangColor struct {
Name string
Color core.Color
Tile int // 0-based local representative tile ID, or -1 if unset
Probability float64
Class string
Properties Properties
// contains filtered or unexported fields
}
WangColor describes one terrain color in a Tiled WangSet. Its 1-based terrain index in WangID values is its slice index + 1.
type WangID ¶
type WangID [8]uint8
WangID holds the 8 terrain color indices around a tile in Tiled's clockwise order: [Top, TopRight, Right, BottomRight, Bottom, BottomLeft, Left, TopLeft].
Terrain indices are 1-based (1..len(WangSet.Colors)); 0 means unset or empty.
type WangSet ¶
type WangSet struct {
Name string
Type WangSetType
Tile int // 0-based local representative tile ID, or -1 if unset
Class string
FirstGID uint32 // FirstGID of the owning Tileset (defaults to 1 when 0)
Colors []WangColor
WangTiles []WangTile
Properties Properties
// contains filtered or unexported fields
}
WangSet is a Tiled Wang set (terrain set) defining corner, edge, or mixed multi-terrain autotiling rules.
func (*WangSet) ColorIndex ¶
ColorIndex returns the 1-based terrain index of the first color named name in ws.Colors.
type WangSetType ¶
type WangSetType uint8
WangSetType selects which tile edges and corners a Tiled WangSet matches.
const ( // WangCorner matches the four tile corners (TopRight, BottomRight, BottomLeft, TopLeft). WangCorner WangSetType = iota // WangEdge matches the four tile edges (Top, Right, Bottom, Left). WangEdge // WangMixed matches all four tile edges and all four tile corners. WangMixed )
func (WangSetType) String ¶
func (t WangSetType) String() string
String returns the Tiled JSON name ("corner", "edge", or "mixed") for t.
type WangTile ¶
type WangTile struct {
TileID uint32
WangID WangID
Probability float64
// contains filtered or unexported fields
}
WangTile maps a 0-based local tile ID in its Tileset to its 8-slot WangID and selection probability.
type WorldLevel ¶
type WorldLevel struct {
// ID is the unique level identifier (LDtk level identifier or Tiled map fileName).
ID string
// IID is the LDtk instance ID, when loaded from an LDtk project.
IID string
// UID is the LDtk numeric UID, when loaded from an LDtk project.
UID int
// FileName is the Tiled map file path, when loaded from a Tiled .world file.
FileName string
// Origin is the level's top-left world position in points.
Origin core.Point
// Bounds is the level's world-space bounding rectangle in points.
Bounds core.Bounds
// WorldDepth is the LDtk worldDepth layer (0 for Tiled worlds).
WorldDepth int
// Neighbours lists adjacent or overlapping levels (populated by LDtk world loaders).
Neighbours []LevelNeighbour
// Load builds this level's *Tilemap with Origin (and Neighbours) populated.
Load func() (*Tilemap, error)
}
WorldLevel describes one level's world placement, metadata, and lazy loader inside a LevelWorld.
type WorldStream ¶
type WorldStream struct {
// contains filtered or unexported fields
}
WorldStream keeps the levels of a LevelWorld overlapping a moving camera or query region loaded at their world origins, unloads levels outside an optional hysteresis margin, reports enter/leave events, draws all loaded levels seamlessly, and supports cross-seam queries and uniform-grid physics adapters.
func NewWorldStream ¶
func NewWorldStream(cfg WorldStreamConfig) *WorldStream
NewWorldStream constructs a WorldStream from cfg.
func (*WorldStream) Close ¶
func (s *WorldStream) Close() []WorldStreamEvent
Close unloads every currently loaded level in deterministic world order, firing OnLeave and returning the leave events.
func (*WorldStream) Draw ¶
func (s *WorldStream) Draw(d *core.Drawing, cam *Camera)
Draw draws every currently loaded level into d in deterministic world order, honoring each level's Origin and culling to cam.
func (*WorldStream) FlagsAtWorld ¶
func (s *WorldStream) FlagsAtWorld(p core.Point) TileFlags
FlagsAtWorld returns the combined TileFlags at world point p across all currently loaded levels.
func (*WorldStream) GridFlagsAt ¶
func (s *WorldStream) GridFlagsAt(col, row int) TileFlags
GridFlagsAt returns the combined TileFlags at uniform grid cell (col, row) relative to GridOrigin across all loaded levels.
Together with TileSize, GridSize, and GridOrigin, this lets a thin physics.TileGrid + physics.TileGridOrigin adapter move a physics.Body or physics.CharacterBody seamlessly across seams between adjacent loaded levels.
func (*WorldStream) GridOrigin ¶
func (s *WorldStream) GridOrigin() (x, y float32)
GridOrigin returns the world-space origin (min X, min Y) of the combined loaded levels, implementing physics.TileGridOrigin.
func (*WorldStream) GridSize ¶
func (s *WorldStream) GridSize() (cols, rows int)
GridSize returns the combined column and row counts covering all currently loaded levels from GridOrigin.
func (*WorldStream) LevelAt ¶
func (s *WorldStream) LevelAt(p core.Point) (*WorldLevel, *Tilemap)
LevelAt returns the first currently loaded level and its *Tilemap containing world point p, or (nil, nil) if none matches.
func (*WorldStream) Loaded ¶
func (s *WorldStream) Loaded() []*Tilemap
Loaded returns all currently loaded *Tilemap instances in deterministic world order.
func (*WorldStream) LoadedCount ¶
func (s *WorldStream) LoadedCount() int
LoadedCount returns the number of currently loaded levels.
func (*WorldStream) LoadedLevels ¶
func (s *WorldStream) LoadedLevels() []*WorldLevel
LoadedLevels returns all currently loaded *WorldLevel descriptors in deterministic world order.
func (*WorldStream) Map ¶
func (s *WorldStream) Map(id string) *Tilemap
Map returns the currently loaded *Tilemap for level ID id, or nil if it is not loaded.
func (*WorldStream) Raycast ¶
func (s *WorldStream) Raycast(from, to core.Point, mask TileFlags) (RaycastHit, bool)
Raycast traces from -> to across all currently loaded levels and returns the closest hit matching mask.
func (*WorldStream) TileFlagsAt ¶
func (s *WorldStream) TileFlagsAt(col, row int) physics.TileFlags
TileFlagsAt returns the combined collision flags at uniform grid cell (col, row) relative to GridOrigin mapped to physics.TileFlags, satisfying physics.TileGrid.
func (*WorldStream) TileSize ¶
func (s *WorldStream) TileSize() (width, height float32)
TileSize returns the tile dimensions of the loaded levels for uniform-grid physics adapters (0, 0 when no levels are loaded).
func (*WorldStream) TilesInRect ¶
func (s *WorldStream) TilesInRect(r core.Bounds, mask TileFlags) []TileHit
TilesInRect returns every matching tile across all currently loaded levels overlapping r, in deterministic level order.
func (*WorldStream) Update ¶
func (s *WorldStream) Update(region core.Bounds) []WorldStreamEvent
Update unloads any loaded level whose Bounds no longer overlap region expanded by UnloadMargin, then loads any unloaded level whose Bounds overlap region expanded by LoadMargin.
Transitions happen in deterministic World.Levels order (unloads first, then loads), firing OnLeave / OnEnter and returning the resulting events.
func (*WorldStream) UpdateAnimations ¶
func (s *WorldStream) UpdateAnimations(dt time.Duration)
UpdateAnimations advances animated tiles on every currently loaded level by dt.
func (*WorldStream) UpdateCamera ¶
func (s *WorldStream) UpdateCamera(cam *Camera) []WorldStreamEvent
UpdateCamera updates streaming for cam.VisibleBounds() (doing nothing when cam is nil).
type WorldStreamConfig ¶
type WorldStreamConfig struct {
// World is the multi-level world to stream.
World *LevelWorld
// LoadMargin expands the query/camera rectangle on all four sides (in world points)
// when choosing which levels to load. Negative values are treated as 0.
LoadMargin float32
// UnloadMargin expands the query/camera rectangle on all four sides (in world points)
// beyond which loaded levels are unloaded (hysteresis). Values smaller than LoadMargin
// default to LoadMargin so a level cannot load and unload on the same update.
UnloadMargin float32
// OnEnter is called after a level is loaded and added to the active set.
OnEnter func(level *WorldLevel, m *Tilemap)
// OnLeave is called after a level is unloaded and removed from the active set.
OnLeave func(level *WorldLevel, m *Tilemap)
// OnError is called when loading a level fails.
OnError func(level *WorldLevel, err error)
}
WorldStreamConfig configures a region-based WorldStream over a LevelWorld.
type WorldStreamEvent ¶
type WorldStreamEvent struct {
Kind WorldStreamEventKind
Level *WorldLevel
Map *Tilemap
}
WorldStreamEvent describes one level load or unload transition produced by WorldStream.Update or Close.
type WorldStreamEventKind ¶
type WorldStreamEventKind uint8
WorldStreamEventKind identifies whether a level entered or left a WorldStream's loaded set.
const ( // WorldLevelEntered reports that a level was loaded and added to the active set. WorldLevelEntered WorldStreamEventKind = iota // WorldLevelLeft reports that a level was unloaded and removed from the active set. WorldLevelLeft )
type YSortDrawer ¶
type YSortDrawer struct {
// Stats, when not nil, counts atlas submissions, standalone tile draws, and batch-break reasons. Compiled to nothing under -tags release.
Stats *sprite.DrawCounter
// contains filtered or unexported fields
}
YSortDrawer batches consecutive unflipped YSortTile values sharing the same tileset and opacity into Drawing.DrawAtlas calls while reusing its internal scratch slices across frames.
func (*YSortDrawer) Flush ¶
func (dr *YSortDrawer) Flush(d *core.Drawing)
Flush emits any queued tiles into d and resets the run state while preserving slice capacity.
type YSortTile ¶
type YSortTile struct {
// SortY is the world-space Y coordinate used for painter's-order depth sorting:
// the tile's bottom edge plus any per-tile or alternative YSortOriginY offset.
SortY float32
// Z is the tile's draw order offset relative to its layer (from TileAlternative.Z, 0 for base tiles).
Z int
// Col and Row are the tile's grid coordinates within its TileLayer.
Col int
Row int
// GID is the raw global tile ID (including flip flags) stored in the layer.
GID uint32
// Alt is the alternative tile ID stored at (Col, Row), or 0 for the base tile.
Alt int
// LayerIndex is the index of the source TileLayer in Tilemap.Layers, or -1 if not attached.
LayerIndex int
// contains filtered or unexported fields
}
YSortTile is one visible tile collected from a TileLayer so it can be depth-sorted and interleaved with scene sprites and custom drawables in ascending SortY order.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package tileshape is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
|
Package tileshape is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/. |