tiled

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: MIT Imports: 16 Imported by: 58 modules, 65 packages

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

README

go-tiled

PkgGoDev Build Status

Go library to parse Tiled map editor file format (TMX) and render map to image. Currently supports only orthogonal finite maps rendering out-of-the-box.

Installing

go get github.com/lafriks/go-tiled

You can use go get -u to update the package. You can also just import and start using the package directly if you're using Go modules, and Go will then download the package on first compilation.

Basic Usage

package main

import (
    "fmt"
    "os"

    "github.com/lafriks/go-tiled"
    "github.com/lafriks/go-tiled/render"
)

const mapPath = "maps/map.tmx" // Path to your Tiled Map.

func main() {
    // Parse .tmx file.
    gameMap, err := tiled.LoadFile(mapPath)
    if err != nil {
        fmt.Printf("error parsing map: %s", err.Error())
        os.Exit(2)
    }

    fmt.Println(gameMap)

    // You can also render the map to an in-memory image for direct
    // use with the default Renderer, or by making your own.
    renderer, err := render.NewRenderer(gameMap)
    if err != nil {
        fmt.Printf("map unsupported for rendering: %s", err.Error())
        os.Exit(2)
    }

    // Render just layer 0 to the Renderer.
    err = renderer.RenderLayer(0)
    if err != nil {
        fmt.Printf("layer unsupported for rendering: %s", err.Error())
        os.Exit(2)
    }

    // Get a reference to the Renderer's output, an image.NRGBA struct.
    img := renderer.Result

    // Clear the render result after copying the output if separation of
    // layers is desired.
    renderer.Clear()

    // And so on. You can also export the image to a file by using the
    // Renderer's Save functions.
}
Embedded Filesystems

To work with embedded file systems via the embed package, both the tilemap and renderer need to be initialized WithFileSystem.

tm, err := tiled.LoadFile(mapPath, tiled.WithFileSystem(assets.Files))
...
r, err := render.NewRendererWithFileSystem(tm, assets.Files)

Documentation

For further documentation, see https://pkg.go.dev/github.com/lafriks/go-tiled or run:

godoc github.com/lafriks/go-tiled

Documentation

Overview

Package tiled is to to parse Tiled map editor file format (TMX).

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidDecodedTileCount error is returned when layer data has invalid tile count
	ErrInvalidDecodedTileCount = errors.New("tiled: invalid decoded tile count")
	// ErrEmptyLayerData error is returned when layer contains no data
	ErrEmptyLayerData = errors.New("tiled: missing layer data")
	// ErrUnknownEncoding error is returned when kayer data has unknown encoding
	ErrUnknownEncoding = errors.New("tiled: unknown data encoding")
)
View Source
var ErrInvalidObjectPoint = errors.New("tiled: invalid object point")

ErrInvalidObjectPoint error is returned if there is error parsing object points

View Source
var ErrInvalidTileGID = errors.New("tiled: invalid tile GID")

ErrInvalidTileGID error is returned when tile GID is not found

View Source
var ErrUnknownCompression = errors.New("tiled: invalid compression method")

ErrUnknownCompression error is returned when file contains invalid compression method

View Source
var NilLayerTile = &LayerTile{Nil: true}

NilLayerTile is reusable layer tile that is nil

Functions

This section is empty.

Types

type AnimationFrame

type AnimationFrame struct {
	// The local ID of a tile within the parent tileset.
	TileID uint32 `xml:"tileid,attr"`
	// How long (in milliseconds) this frame should be displayed before advancing to the next frame.
	Duration uint32 `xml:"duration,attr"`
}

AnimationFrame is single frame of animation

type Axis added in v0.11.0

type Axis string

Axis type

const (
	// AxisX is X axis
	AxisX Axis = "x"
	// AxisY is Y axis
	AxisY Axis = "y"
)

type Data

type Data struct {
	// The encoding used to encode the tile layer data. When used, it can be "base64" and "csv" at the moment.
	Encoding string `xml:"encoding,attr"`
	// The compression used to compress the tile layer data. Tiled Qt supports "gzip" and "zlib".
	Compression string `xml:"compression,attr"`
	// Raw data. Only populated when Encoding is "csv" or "base64".
	RawData []byte `xml:",innerxml"`
	// Parsed tile elements. Only populated when Encoding is not set.
	DataTiles []DataTile `xml:"tile"`
}

Data is raw data

func (*Data) UnmarshalXML added in v0.15.0

func (d *Data) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements a hand-rolled decode of the <data> element.

A tile layer's data is either one large text blob (csv/base64) or, for the uncompressed per-tile XML encoding, thousands of <tile gid="N"/> child elements. Letting encoding/xml decode DataTiles via reflection (as driven by the struct tags above) means paying its per-element, per-attribute reflection cost for every tile; walking the token stream directly and parsing "gid" by hand avoids that and is significantly faster for large maps using this encoding. The struct tags are kept so Data/DataTile still unmarshal and marshal correctly (round-trip to XML) when used directly with encoding/xml outside of this package.

type DataTile

type DataTile struct {
	// The global tile ID.
	GID uint32 `xml:"gid,attr"`
}

DataTile defines the value of a single tile on a tile layer

type Ellipse

type Ellipse struct{}

Ellipse is used to mark an object as an ellipse.

type Group

type Group struct {
	// Unique ID of the layer.
	// Each layer that added to a map gets a unique id. Even if a layer is deleted,
	// no layer ever gets the same ID. Can not be changed in Tiled. (since Tiled 1.2)
	ID uint32 `xml:"id,attr"`
	// The name of the group layer.
	Name string `xml:"name,attr"`
	// The class of the group layer (since 1.9, defaults to "").
	Class string `xml:"class,attr"`
	// Rendering offset of the image layer in pixels. Defaults to 0. (since 0.15)
	OffsetX float64 `xml:"offsetx,attr"`
	// Rendering offset of the image layer in pixels. Defaults to 0. (since 0.15)
	OffsetY float64 `xml:"offsety,attr"`
	// The opacity of the layer as a value from 0 to 1. Defaults to 1.
	Opacity float32 `xml:"opacity,attr"`
	// Whether the layer is shown (1) or hidden (0). Defaults to 1.
	Visible bool `xml:"visible,attr"`
	// The parallax x factor of the layer 0 - 1.0
	ParallaxX float32 `xml:"parallaxx,attr"`
	// The parallax y factor of the layer 0 - 1.0
	ParallaxY float32 `xml:"parallaxy,attr"`
	// The compositing mode to use for this layer. Valid values are normal,
	// multiply, multiply (legacy), screen, overlay, darken, lighten, color dodge,
	// color burn, hard light, soft light, difference, exclusion, hue, saturation,
	// color and luminosity. (since 1.12, defaults to normal)
	Mode string `xml:"mode,attr"`
	// Custom properties
	Properties Properties `xml:"properties>property"`
	// Map layers
	Layers []*Layer `xml:"layer"`
	// Map object groups
	ObjectGroups []*ObjectGroup `xml:"objectgroup"`
	// Image layers
	ImageLayers []*ImageLayer `xml:"imagelayer"`
	// Group layers
	Groups []*Group `xml:"group"`
}

Group is a group layer, used to organize the layers of the map in a hierarchy.

func (*Group) DecodeGroup added in v0.3.1

func (g *Group) DecodeGroup(m *Map) error

DecodeGroup decodes Group data. This includes all subgroups and the Layer data for each.

func (*Group) UnmarshalXML

func (g *Group) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type HexColor added in v0.3.0

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

HexColor handles the conversion between hex color strings in form #AARRGGBB to color.RGBA structure. Be aware that this doesn't match CSS hex color because the alpha channel appears first.

func NewHexColor added in v0.3.0

func NewHexColor(r, g, b, a uint32) *HexColor

NewHexColor is a shorthand to build a *HexColor.

func ParseHexColor added in v0.3.0

func ParseHexColor(s string) (*HexColor, error)

ParseHexColor converts hex color strings into a *HexColor type. This function can handle colors with and withouth optional alpha channel The leading '#' character is not required for backwards compatibility with Transparency Tiled filed https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#image

func (*HexColor) MarshalXMLAttr added in v0.3.0

func (color *HexColor) MarshalXMLAttr(name xml.Name) (attr xml.Attr, err error)

MarshalXMLAttr implements xml.MarshalerAttr

func (*HexColor) RGBA added in v0.3.0

func (color *HexColor) RGBA() (r, g, b, a uint32)

RGBA implements color.Color interface

func (*HexColor) String added in v0.3.0

func (color *HexColor) String() string

func (*HexColor) UnmarshalXMLAttr added in v0.3.0

func (color *HexColor) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr implements xml.UnmarshalerAttr

type Image

type Image struct {
	// Used for embedded images, in combination with a data child element. Valid values are file extensions like png, gif, jpg, bmp, etc.
	Format string `xml:"format,attr"`
	// The reference to the tileset image file
	Source string `xml:"source,attr"`
	// Defines a specific color that is treated as transparent (example value: "#FF00FF" for magenta).
	// Up until Tiled 0.12, this value is written out without a # but this is planned to change.
	Trans *HexColor `xml:"trans,attr"`
	// The image width in pixels (optional, used for tile index correction when the image changes)
	Width int `xml:"width,attr"`
	// The image height in pixels (optional)
	Height int `xml:"height,attr"`
	// Embedded image content
	Data *Data `xml:"data,attr"`
}

Image source

type ImageLayer

type ImageLayer struct {
	// Unique ID of the layer.
	// Each layer that added to a map gets a unique id. Even if a layer is deleted,
	// no layer ever gets the same ID. Can not be changed in Tiled. (since Tiled 1.2)
	ID uint32 `xml:"id,attr"`
	// The name of the image layer.
	Name string `xml:"name,attr"`
	// The class of the image layer (since 1.9, defaults to "").
	Class string `xml:"class,attr"`
	// Rendering offset of the image layer in pixels. Defaults to 0. (since 0.15)
	OffsetX float64 `xml:"offsetx,attr"`
	// Rendering offset of the image layer in pixels. Defaults to 0. (since 0.15)
	OffsetY float64 `xml:"offsety,attr"`
	// The x position of the image layer in pixels. (deprecated since 0.15)
	X int `xml:"x,attr"`
	// The y position of the image layer in pixels. (deprecated since 0.15)
	Y int `xml:"y,attr"`
	// The opacity of the layer as a value from 0 to 1. Defaults to 1.
	Opacity float32 `xml:"opacity,attr"`
	// Whether the layer is shown (1) or hidden (0). Defaults to 1.
	Visible bool `xml:"visible,attr"`
	// Custom properties
	Properties Properties `xml:"properties>property"`
	// The group image
	Image *Image `xml:"image"`
	// The parallax x factor of the layer 0 - 1.0
	ParallaxX float32 `xml:"parallaxx,attr"`
	// The parallax y factor of the layer 0 - 1.0
	ParallaxY float32 `xml:"parallaxy,attr"`
	// The repeat x settings of the image.
	RepeatX bool `xml:"repeatx,attr"`
	// The repeat y settings of the image.
	RepeatY bool `xml:"repeaty,attr"`
	// The compositing mode to use for this layer. Valid values are normal,
	// multiply, multiply (legacy), screen, overlay, darken, lighten, color dodge,
	// color burn, hard light, soft light, difference, exclusion, hue, saturation,
	// color and luminosity. (since 1.12, defaults to normal)
	Mode string `xml:"mode,attr"`
}

ImageLayer is a layer consisting of a single image.

func (*ImageLayer) UnmarshalXML

func (l *ImageLayer) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type Layer

type Layer struct {

	// Unique ID of the layer.
	// Each layer that added to a map gets a unique id. Even if a layer is deleted,
	// no layer ever gets the same ID. Can not be changed in Tiled. (since Tiled 1.2)
	ID uint32 `xml:"id,attr"`
	// The name of the layer.
	Name string `xml:"name,attr"`
	// The class of this layer (since 1.9, defaults to "").
	Class string `xml:"class,attr"`
	// The opacity of the layer as a value from 0 to 1. Defaults to 1.
	Opacity float32 `xml:"opacity,attr"`
	// Whether the layer is shown (1) or hidden (0). Defaults to 1.
	Visible bool `xml:"visible,attr"`
	// Rendering offset for this layer in pixels. Defaults to 0. (since 0.14)
	OffsetX float64 `xml:"offsetx,attr"`
	// Rendering offset for this layer in pixels. Defaults to 0. (since 0.14)
	OffsetY float64 `xml:"offsety,attr"`
	// The parallax x factor of the layer 0 - 1.0
	ParallaxX float32 `xml:"parallaxx,attr"`
	// The parallax y factor of the layer 0 - 1.0
	ParallaxY float32 `xml:"parallaxy,attr"`
	// The compositing mode to use for this layer. Valid values are normal,
	// multiply, multiply (legacy), screen, overlay, darken, lighten, color dodge,
	// color burn, hard light, soft light, difference, exclusion, hue, saturation,
	// color and luminosity. (since 1.12, defaults to normal)
	Mode string `xml:"mode,attr"`
	// Custom properties
	Properties Properties `xml:"properties>property"`
	// This is the attribute you'd like to use, not Data. Tile entry at (x,y) is obtained using l.DecodedTiles[y*map.Width+x].
	Tiles []*LayerTile
	// contains filtered or unexported fields
}

Layer is a map layer

func (*Layer) DecodeLayer

func (l *Layer) DecodeLayer(m *Map) error

DecodeLayer decodes layer data

func (*Layer) GetTilePosition added in v0.3.0

func (l *Layer) GetTilePosition(tileID int) (int, int)

GetTilePosition returns the x,y position of the tileID on the current layer.

func (*Layer) IsEmpty

func (l *Layer) IsEmpty() bool

IsEmpty checks if layer has tiles other than nil

func (*Layer) UnmarshalXML

func (l *Layer) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type LayerTile

type LayerTile struct {
	// Tile ID
	ID uint32
	// Tile tileset
	Tileset *Tileset
	// Horizontal tile image flip
	HorizontalFlip bool
	// Vertical tile image flip
	VerticalFlip bool
	// Diagonal tile image flip
	DiagonalFlip bool
	// RotatedHexagonal120 marks the tile as rotated 120 degrees clockwise.
	// Only meaningful on hexagonal (and staggered) maps, where it combines with
	// HorizontalFlip/VerticalFlip/DiagonalFlip to produce all 6 rotations of a
	// hex tile in 60-degree steps: none = 0, DiagonalFlip = 60, this = 120,
	// Horizontal+Vertical = 180, Horizontal+Vertical+DiagonalFlip = 240,
	// Horizontal+Vertical+this = 300. Always false for other orientations.
	RotatedHexagonal120 bool
	// Tile is nil
	Nil bool
}

LayerTile is a layer tile

func (*LayerTile) GetTileRect added in v0.3.0

func (t *LayerTile) GetTileRect() image.Rectangle

GetTileRect returns the rectangle that contains the Tile in the original Tileset.Image

func (*LayerTile) IsNil

func (t *LayerTile) IsNil() bool

IsNil returs if tile is nil

type LoaderOption added in v0.7.0

type LoaderOption func(*loader)

LoaderOption is used with LoadReader and LoadFile functions to pass additional options

func WithFileSystem added in v0.7.0

func WithFileSystem(fileSystem fs.FS) LoaderOption

WithFileSystem returns an option to load level from a passed filesystem

type Map

type Map struct {

	// The TMX format version, generally 1.0.
	Version string `xml:"version,attr"`
	// The Tiled version used to generate this file
	TiledVersion string `xml:"tiledversion,attr"`
	// The class of this map (since 1.9, defaults to "").
	Class string `xml:"class,attr"`
	// Map orientation. Tiled supports "orthogonal", "isometric", "staggered" (since 0.9) and "hexagonal" (since 0.11).
	Orientation string `xml:"orientation,attr"`
	// The order in which tiles on tile layers are rendered. Valid values are right-down (the default), right-up, left-down and left-up.
	// In all cases, the map is drawn row-by-row. (since 0.10, but only supported for orthogonal maps at the moment)
	RenderOrder string `xml:"renderorder,attr"`
	// The map width in tiles.
	Width int `xml:"width,attr"`
	// The map height in tiles.
	Height int `xml:"height,attr"`
	// The width of a tile.
	TileWidth int `xml:"tilewidth,attr"`
	// The height of a tile.
	TileHeight int `xml:"tileheight,attr"`
	// Only for hexagonal maps. Determines the width or height (depending on the staggered axis) of the tile's edge, in pixels.
	HexSideLength int `xml:"hexsidelength,attr"`
	// For staggered and hexagonal maps, determines which axis ("x" or "y") is staggered. (since 0.11)
	StaggerAxis Axis `xml:"staggeraxis,attr"`
	// For staggered and hexagonal maps, determines whether the "even" or "odd" indexes along the staggered axis are shifted. (since 0.11)
	StaggerIndex StaggerIndexType `xml:"staggerindex,attr"`
	// The background color of the map. (since 0.9, optional, may include alpha value since 0.15 in the form #AARRGGBB, defaults to fully transparent)
	BackgroundColor *HexColor `xml:"backgroundcolor,attr"`
	// Stores the next available ID for new layers. This number is stored to prevent reuse of the same ID after layers have been removed.
	// (since 1.2, defaults to the highest layer id in the file + 1; not computed by this package if absent)
	NextLayerID uint32 `xml:"nextlayerid,attr"`
	// Stores the next available ID for new objects. This number is stored to prevent reuse of the same ID after objects have been removed.
	// (since 0.11, defaults to the highest object id in the file + 1; not computed by this package if absent)
	NextObjectID uint32 `xml:"nextobjectid,attr"`
	// The compression level to use for tile layer data (defaults to -1, meaning algorithm-specific default level). (since 1.3)
	CompressionLevel int `xml:"compressionlevel,attr"`
	// Whether this map is infinite. An infinite map has no fixed size and grows in all directions;
	// its layer data would be stored in <chunk> elements.
	//
	// TODO: <chunk> elements are not parsed by this package yet. Loading an
	// infinite map's tile layer data is likely to fail or produce incorrect
	// results; only this flag itself is currently exposed.
	Infinite bool `xml:"infinite,attr"`
	// X coordinate of the parallax origin in pixels. (since 1.8, defaults to 0)
	ParallaxOriginX float64 `xml:"parallaxoriginx,attr"`
	// Y coordinate of the parallax origin in pixels. (since 1.8, defaults to 0)
	ParallaxOriginY float64 `xml:"parallaxoriginy,attr"`
	// Custom properties
	Properties *Properties `xml:"properties>property"`
	// Map tilesets
	Tilesets []*Tileset `xml:"tileset"`
	// Map layers
	Layers []*Layer `xml:"layer"`
	// Map object groups
	ObjectGroups []*ObjectGroup `xml:"objectgroup"`
	// Image layers
	ImageLayers []*ImageLayer `xml:"imagelayer"`
	// Group layers
	Groups []*Group `xml:"group"`
	// contains filtered or unexported fields
}

Map contains three different kinds of layers. Tile layers were once the only type, and are simply called layer, object layers have the objectgroup tag and image layers use the imagelayer tag. The order in which these layers appear is the order in which the layers are rendered by Tiled

func LoadFile added in v0.7.0

func LoadFile(fileName string, options ...LoaderOption) (*Map, error)

LoadFile function loads tiled map in TMX format from file

func LoadReader added in v0.7.0

func LoadReader(baseDir string, r io.Reader, options ...LoaderOption) (*Map, error)

LoadReader function loads tiled map in TMX format from io.Reader baseDir is used for loading additional tile data, current directory is used if empty

func (*Map) GetFileFullPath

func (m *Map) GetFileFullPath(fileName string) string

GetFileFullPath returns path to file relative to map file

func (*Map) TileGIDToTile

func (m *Map) TileGIDToTile(gid uint32) (*LayerTile, error)

TileGIDToTile is used to find tile data by GID

func (*Map) UnmarshalXML

func (m *Map) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type Object

type Object struct {
	// Unique ID of the object. Each object that is placed on a map gets a unique id. Even if an object was deleted, no object gets the same ID.
	// Can not be changed in Tiled Qt. (since Tiled 0.11)
	ID uint32 `xml:"id,attr"`
	// The name of the object. An arbitrary string.
	Name string `xml:"name,attr"`
	// The type of the object. An arbitrary string. (until 1.8)
	//
	// Deprecated: replaced by Class since 1.9
	Type string `xml:"type,attr"`
	// The class of the object. An arbitrary string. (defaults to "", renamed from 'type' since 1.9)
	Class string `xml:"class,attr"`
	// The x coordinate of the object.
	X float64 `xml:"x,attr"`
	// The y coordinate of the object.
	Y float64 `xml:"y,attr"`
	// The width of the object (defaults to 0).
	Width float64 `xml:"width,attr"`
	// The height of the object (defaults to 0).
	Height float64 `xml:"height,attr"`
	// The rotation of the object in degrees clockwise (defaults to 0). (since 0.10)
	Rotation float64 `xml:"rotation,attr"`
	// An reference to a tile (optional).
	GID uint32 `xml:"gid,attr"`
	// The opacity of the object as a value from 0 to 1. Defaults to 1.
	Opacity float32 `xml:"opacity,attr"`
	// Whether the object is shown (1) or hidden (0). Defaults to 1. (since 0.9)
	Visible bool `xml:"visible,attr"`
	// Custom properties
	Properties Properties `xml:"properties>property"`
	// Used to mark an object as an ellipse. The existing x, y, width and height attributes are used to determine the size of the ellipse.
	Ellipses []*Ellipse `xml:"ellipse"`
	// Polygons
	Polygons []*Polygon `xml:"polygon"`
	// Poly lines
	PolyLines []*PolyLine `xml:"polyline"`
	// Text
	Text *Text `xml:"text"`
	// Template
	TemplateSource string `xml:"template,attr"`
	TemplateLoaded bool   `xml:"-"`
	Template       *Template
}

Object is used to add custom information to your tile map, such as spawn points, warps, exits, etc.

func (*Object) UnmarshalXML added in v0.3.0

func (o *Object) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type ObjectGroup

type ObjectGroup struct {
	// Unique ID of the layer.
	// Each layer that added to a map gets a unique id. Even if a layer is deleted,
	// no layer ever gets the same ID. Can not be changed in Tiled. (since Tiled 1.2)
	ID uint32 `xml:"id,attr"`
	// The name of the object group.
	Name string `xml:"name,attr"`
	// The class of the object group (since 1.9, defaults to "").
	Class string `xml:"class,attr"`
	// The color used to display the objects in this group.
	Color *HexColor `xml:"color,attr"`
	// The opacity of the layer as a value from 0 to 1. Defaults to 1.
	Opacity float32 `xml:"opacity,attr"`
	// Whether the layer is shown (1) or hidden (0). Defaults to 1.
	Visible bool `xml:"visible,attr"`
	// Rendering offset for this layer in pixels. Defaults to 0. (since 0.14)
	OffsetX float64 `xml:"offsetx,attr"`
	// Rendering offset for this layer in pixels. Defaults to 0. (since 0.14)
	OffsetY float64 `xml:"offsety,attr"`
	// Whether the objects are drawn according to the order of appearance ("index") or sorted by their y-coordinate ("topdown"). Defaults to "topdown".
	DrawOrder string `xml:"draworder,attr"`
	// The parallax x factor of the layer 0 - 1.0
	ParallaxX float32 `xml:"parallaxx,attr"`
	// The parallax y factor of the layer 0 - 1.0
	ParallaxY float32 `xml:"parallaxy,attr"`
	// The compositing mode to use for this layer. Valid values are normal,
	// multiply, multiply (legacy), screen, overlay, darken, lighten, color dodge,
	// color burn, hard light, soft light, difference, exclusion, hue, saturation,
	// color and luminosity. (since 1.12, defaults to normal)
	Mode string `xml:"mode,attr"`
	// Custom properties
	Properties Properties `xml:"properties>property"`
	// Group objects
	Objects []*Object `xml:"object"`
}

ObjectGroup is in fact a map layer, and is hence called "object layer" in Tiled Qt

func (*ObjectGroup) DecodeObjectGroup added in v0.3.2

func (g *ObjectGroup) DecodeObjectGroup(m *Map) error

DecodeObjectGroup decodes object group data

func (*ObjectGroup) UnmarshalXML added in v0.4.0

func (g *ObjectGroup) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type Point

type Point struct {
	// Point X
	X float64
	// Point Y
	Y float64
}

Point is point

type Points

type Points []*Point

Points is array of points

func (*Points) UnmarshalXMLAttr

func (m *Points) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr decodes a single XML element beginning with the given start element.

type PolyLine

type PolyLine struct {
	// A list of x,y coordinates in pixels.
	Points *Points `xml:"points,attr"`
}

PolyLine follows the same placement definition as a polygon object.

type Polygon

type Polygon struct {
	// A list of x,y coordinates in pixels.
	Points *Points `xml:"points,attr"`
}

Polygon object is made up of a space-delimited list of x,y coordinates. The origin for these coordinates is the location of the parent object. By default, the first point is created as 0,0 denoting that the point will originate exactly where the object is placed.

type Properties

type Properties []*Property

Properties wraps any number of custom properties

func (Properties) Get

func (p Properties) Get(name string) *Property

Get finds the first property with the specified name and returns it, or nil if not found. Useful for reaching a class-typed property's nested Properties, e.g. obj.Properties.Get("entity").Properties.GetBool("enabled").

func (Properties) GetAll added in v0.15.0

func (p Properties) GetAll(name string) []string

GetAll finds the values of all properties with the specified name

func (Properties) GetBool

func (p Properties) GetBool(name string) bool

GetBool finds first bool property by specified name

func (Properties) GetColor added in v0.13.0

func (p Properties) GetColor(name string) color.Color

GetColor returns a color.Color by parsing the first property found using name. If unable to parse the value or find the value nil is returned.

func (Properties) GetFloat added in v0.3.0

func (p Properties) GetFloat(name string) float64

GetFloat finds first float property by specified name

func (Properties) GetInt added in v0.3.0

func (p Properties) GetInt(name string) int

GetInt finds first int property by specified name

func (Properties) GetString

func (p Properties) GetString(name string) string

GetString finds first string property by specified name

type Property

type Property struct {
	// The name of the property.
	Name string `xml:"name,attr"`
	// The type of the property. Can be string (default), int, float, bool, color,
	// file (since 0.16, with color and file added in 0.17), class or object (since 1.8).
	Type string `xml:"type,attr"`
	// The name of the custom property type, when Type is "class" (since 1.8).
	PropertyType string `xml:"propertytype,attr,omitempty"`
	// The value of the property.
	// Boolean properties have a value of either "true" or "false".
	// Color properties are stored in the format #AARRGGBB.
	// File properties are stored as paths relative from the location of the map file.
	// Empty for class-typed properties; see Properties instead.
	Value string `xml:"value,attr,omitempty"`
	// Properties holds the explicitly-set member values of a class-typed property.
	//
	// Per the TMX spec, a class member left at its class-defined default is not
	// serialized at all -- only overridden members appear here. Resolving a
	// member's default value requires the class definition from Tiled's project
	// file (commonly a .tiled-project JSON file), which is a wholly separate
	// format this package does not read; there is no way to recover a class
	// member's default value from a .tmx/.tsx file alone.
	Properties Properties `xml:"properties>property,omitempty"`
}

Property is used for custom properties

func (*Property) UnmarshalXML added in v0.14.0

func (p *Property) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements the xml.Unmarshaler interface for Property. Setting Value even if it's in the inner text.

type StaggerIndexType added in v0.11.0

type StaggerIndexType string

StaggerIndexType is stagger axis index type

const (
	// StaggerIndexOdd is odd stagger index
	StaggerIndexOdd StaggerIndexType = "odd"
	// StaggerIndexEven is even stagger index
	StaggerIndexEven StaggerIndexType = "even"
)

type Template added in v0.4.0

type Template struct {
	Tileset *Tileset `xml:"tileset"`
	Object  *Object  `xml:"object"`
}

Template is used for custom properties.

type Terrain

type Terrain struct {
	// The name of the terrain type.
	Name string `xml:"name,attr"`
	// The local tile-id of the tile that represents the terrain visually.
	Tile uint32 `xml:"tile,attr"`
	// Custom properties
	Properties Properties `xml:"properties>property"`
}

Terrain type

type Text

type Text struct {
	// The actual text
	Text string `xml:",chardata"`
	// The font family used (default: "sans-serif")
	FontFamily string `xml:"fontfamily,attr"`
	// The size of the font in pixels (not using points, because other sizes in the TMX format are also using pixels) (default: 16)
	Size int `xml:"pixelsize,attr"`
	// Whether word wrapping is enabled (1) or disabled (0). Defaults to 0.
	Wrap bool `xml:"wrap,attr"`
	// Color of the text in #AARRGGBB or #RRGGBB format (default: #000000)
	Color *HexColor `xml:"color,attr"`
	// Whether the font is bold (1) or not (0). Defaults to 0.
	Bold bool `xml:"bold,attr"`
	// Whether the font is italic (1) or not (0). Defaults to 0.
	Italic bool `xml:"italic,attr"`
	// Whether a line should be drawn below the text (1) or not (0). Defaults to 0.
	Underline bool `xml:"underline,attr"`
	// Whether a line should be drawn through the text (1) or not (0). Defaults to 0.
	Strikethrough bool `xml:"strikeout,attr"`
	// Whether kerning should be used while rendering the text (1) or not (0). Default to 1.
	Kerning bool `xml:"kerning,attr"`
	// Horizontal alignment of the text within the object (left (default), center, right or justify (since Tiled 1.2.1))
	HAlign string `xml:"halign,attr"`
	// Vertical alignment of the text within the object (top (default), center or bottom)
	VAlign string `xml:"valign,attr"`
}

Text contains a text and attributes such as bold, color, etc.

func (*Text) UnmarshalXML

func (t *Text) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type Tileset

type Tileset struct {

	// The TMX format version, generally 1.0.
	Version string `xml:"version,attr"`
	// The Tiled version used to generate this file
	TiledVersion string `xml:"tiledversion,attr"`
	// The first global tile ID of this tileset (this global ID maps to the first tile in this tileset).
	FirstGID uint32 `xml:"firstgid,attr"`
	// If this tileset is stored in an external TSX (Tile Set XML) file, this attribute refers to that file.
	// That TSX file has the same structure as the <tileset> element described here. (There is the firstgid
	// attribute missing and this source attribute is also not there. These two attributes are kept in the
	// TMX map, since they are map specific.)
	Source string `xml:"source,attr"`
	// External TSX source loaded.
	SourceLoaded bool `xml:"-"`
	// The name of this tileset.
	Name string `xml:"name,attr"`
	// The class of this tileset (since 1.9, defaults to "").
	Class string `xml:"class,attr"`
	// The (maximum) width of the tiles in this tileset.
	TileWidth int `xml:"tilewidth,attr"`
	// The (maximum) height of the tiles in this tileset.
	TileHeight int `xml:"tileheight,attr"`
	// The spacing in pixels between the tiles in this tileset (applies to the tileset image).
	Spacing int `xml:"spacing,attr"`
	// The margin around the tiles in this tileset (applies to the tileset image).
	Margin int `xml:"margin,attr"`
	// The number of tiles in this tileset (since 0.13)
	TileCount int `xml:"tilecount,attr"`
	// The number of tile columns in the tileset. For image collection tilesets it is editable and is used when displaying the tileset. (since 0.15)
	Columns int `xml:"columns,attr"`
	// Offset in pixels, to be applied when drawing a tile from the related tileset. When not present, no offset is applied.
	TileOffset *TilesetTileOffset `xml:"tileoffset"`
	// Controls the alignment for tile objects. Valid values are unspecified, topleft,
	// top, topright, left, center, right, bottomleft, bottom and bottomright.
	// (since 1.4, defaults to unspecified, for compatibility reasons)
	ObjectAlignment string `xml:"objectalignment,attr"`
	// The size to use when rendering tiles from this tileset on a tile layer.
	// Valid values are tile (the default) and grid. (since 1.9)
	TileRenderSize string `xml:"tilerendersize,attr"`
	// The fill mode to use when rendering tiles from this tileset. Valid values
	// are stretch (the default) and preserve-aspect-fit. (since 1.9)
	FillMode string `xml:"fillmode,attr"`
	// The grid used for the tiles in this tileset, only used in case of isometric
	// orientation, and determines how tile overlays for terrain and collision
	// information are rendered. (optional)
	Grid *TilesetGrid `xml:"grid"`
	// Describes which transformations can be applied to the tiles (e.g. to
	// extend a Wang set by transforming existing tiles). (optional, since 1.5)
	Transformations *TilesetTransformations `xml:"transformations"`
	// Custom properties
	Properties Properties `xml:"properties>property"`
	// Embedded image
	Image *Image `xml:"image"`
	// Defines an array of terrain types, which can be referenced from the terrain of the tile element.
	TerrainTypes []*Terrain `xml:"terraintypes>terrain"`
	// Tiles in tileset
	Tiles []*TilesetTile `xml:"tile"`
	// Contains the list of Wang sets defined for this tileset.
	WangSets WangSets `xml:"wangsets>wangset"`
	// contains filtered or unexported fields
}

Tileset is collection of tiles

func LoadTilesetFile added in v0.14.0

func LoadTilesetFile(fileName string, options ...LoaderOption) (*Tileset, error)

LoadTilesetFile loads a tiled map in TSX format from a file.

func LoadTilesetReader added in v0.14.0

func LoadTilesetReader(baseDir string, r io.Reader, options ...LoaderOption) (*Tileset, error)

LoadTilesetReader loads a tileset from an io.Reader. baseDir is used to locate relative paths to additional tileset data; default is currend directory if empty.

func (*Tileset) BaseDir added in v0.10.0

func (ts *Tileset) BaseDir() string

BaseDir returns the base directory.

func (*Tileset) GetFileFullPath

func (ts *Tileset) GetFileFullPath(fileName string) string

GetFileFullPath returns path to file relative to tileset file

func (*Tileset) GetTileRect added in v0.3.0

func (ts *Tileset) GetTileRect(tileID uint32) image.Rectangle

GetTileRect returns a rectangle that contains the tile in the tileset.Image

func (*Tileset) GetTilesetTile added in v0.9.0

func (ts *Tileset) GetTilesetTile(tileID uint32) (*TilesetTile, error)

GetTilesetTile returns TilesetTile by tileID

Example
package main

import (
	"fmt"
	"os"

	"github.com/lafriks/go-tiled"
)

func main() {
	var tiledMap *tiled.Map
	var err error
	tiledMap, err = tiled.LoadFile("assets/test_wangsets_w_properties_map.tmx")
	if err != nil {
		fmt.Printf("error parsing tiledMap: %s", err.Error())
		os.Exit(2)
	}

	// get the tile so that we can read its data
	tile, err := tiledMap.Layers[0].Tiles[0].Tileset.GetTilesetTile(15)
	if err != nil {
		panic(err)
	}

	fmt.Print(tile.ID)

}
Output:
15

func (*Tileset) SetBaseDir added in v0.10.0

func (ts *Tileset) SetBaseDir(baseDir string)

SetBaseDir sets the base directory.

func (*Tileset) UnmarshalXML added in v0.15.0

func (ts *Tileset) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type TilesetGrid added in v0.15.0

type TilesetGrid struct {
	// Orientation of the grid for the tiles in this tileset (orthogonal or
	// isometric, defaults to orthogonal)
	Orientation string `xml:"orientation,attr"`
	// Width of a grid cell
	Width int `xml:"width,attr"`
	// Height of a grid cell
	Height int `xml:"height,attr"`
}

TilesetGrid specifies the grid used for the tiles in a tileset, only used in case of isometric orientation.

type TilesetTile

type TilesetTile struct {
	// The local tile ID within its tileset.
	ID uint32 `xml:"id,attr"`
	// The type of the tile. Refers to an object type and is used by tile objects. (optional) (since 1.0, until 1.8)
	//
	// Deprecated: replaced by Class since 1.9
	Type string `xml:"type,attr"`
	// The type of the tile. Refers to an object type and is used by tile objects. (optional) (renamed from 'type' since 1.9)
	Class string `xml:"class,attr"`
	// X is position of the sub-rectangle representing this tile (default: 0)
	X int `xml:"x,attr"`
	// Y is position of the sub-rectangle representing this tile (default: 0)
	Y int `xml:"y,attr"`
	// Width of the sub-rectangle representing this tile (defaults to the image width)
	Width int `xml:"width,attr"`
	// Height of the sub-rectangle representing this tile (defaults to the image height)
	Height int `xml:"height,attr"`
	// Defines the terrain type of each corner of the tile, given as comma-separated indexes in the terrain types
	// array in the order top-left, top-right, bottom-left, bottom-right.
	// Leaving out a value means that corner has no terrain. (optional) (since 0.9)
	Terrain string `xml:"terrain,attr"`
	// A percentage indicating the probability that this tile is chosen when it competes with others while editing with the terrain tool. (optional, defaults to 1) (since 0.9)
	Probability float32 `xml:"probability,attr"`
	// Custom properties
	Properties Properties `xml:"properties>property"`
	// Embedded image
	Image *Image `xml:"image"`
	// Tile object groups
	ObjectGroups []*ObjectGroup `xml:"objectgroup"`
	// List of animation frames
	Animation []*AnimationFrame `xml:"animation>frame"`
}

TilesetTile information

func (*TilesetTile) UnmarshalXML added in v0.15.0

func (t *TilesetTile) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type TilesetTileOffset

type TilesetTileOffset struct {
	// Horizontal offset in pixels
	X int `xml:"x,attr"`
	// Vertical offset in pixels (positive is down)
	Y int `xml:"y,attr"`
}

TilesetTileOffset is used to specify an offset in pixels, to be applied when drawing a tile from the related tileset. When not present, no offset is applied

type TilesetTransformations added in v0.15.0

type TilesetTransformations struct {
	// Whether the tiles in this set can be flipped horizontally (default 0)
	HFlip bool `xml:"hflip,attr"`
	// Whether the tiles in this set can be flipped vertically (default 0)
	VFlip bool `xml:"vflip,attr"`
	// Whether the tiles in this set can be rotated in 90 degree increments (default 0)
	Rotate bool `xml:"rotate,attr"`
	// Whether untransformed tiles remain preferred, otherwise transformed tiles
	// are used to produce more variations (default 0)
	PreferUntransformed bool `xml:"preferuntransformed,attr"`
}

TilesetTransformations describes which transformations can be applied to the tiles in a tileset (e.g. to extend a Wang set by transforming existing tiles).

type WangColor added in v0.9.0

type WangColor struct {
	// The name of this color.
	Name string `xml:"name,attr"`
	// The class of this color. (since 1.9)
	Class string `xml:"class,attr"`
	// The color in #RRGGBB format (example: #c17d11).
	Color string `xml:"color,attr"`
	// The tile ID of the tile representing this color.
	TileID int64 `xml:"tile,attr"`
	// The relative probability that this color is chosen over others in case of multiple options. (defaults to 1)
	Probability float32 `xml:"probability,attr"`
}

WangColor that can be used to define the corner and/or edge of a Wang tile.

type WangPosition added in v0.9.0

type WangPosition int

WangPosition Wang Color mapping to position

const (
	// Top represents the top part of the tile
	Top WangPosition = iota
	// TopRight represents the top right part of the tile
	TopRight
	// Right represents the right part of the tile
	Right
	// BottomRight represents the bottom right part of the tile
	BottomRight
	// Bottom represents the bottom part of the tile
	Bottom
	// BottomLeft represents the bottom left part of the tile
	BottomLeft
	// Left represents the left part of the tile
	Left
	// TopLeft represents the top left part of the tile
	TopLeft
)

type WangSet added in v0.9.0

type WangSet struct {
	// The name of the Wang set.
	Name string `xml:"name,attr"`
	// The class of the Wang set. (renamed from 'type' since 1.9)
	Class string `xml:"class,attr"`
	// WangSet type.
	//
	// Deprecated: replaced by Class since 1.9
	Type string `xml:"type,attr"`
	// The tile ID of the tile representing this Wang set.
	TileID int64 `xml:"tile,attr"`
	// The list of corner and/or edge colors.
	WangColors []*WangColor `xml:"wangcolor"`
	// The list of wang tiles.
	WangTiles []*WangTile `xml:"wangtile"`
}

WangSet defines a list of corner colors and a list of edge colors, and any number of Wang tiles using these colors.

func (*WangSet) GetWangColors added in v0.9.0

func (w *WangSet) GetWangColors(tileID uint32) (map[WangPosition]*WangColor, error)

GetWangColors returns the wangcolors for the tileId. If corner type is used it will return an array of len 4 topRight, bottomRight, bottom left, top left if corner type is not used it will return an array of len 8 in the following order. top, top right, right, bottom right, bottom, bottom left, left, top left if there is no wangcolor assigned to a part of the tile it will return an nil pointer instead for that index

Example
package main

import (
	"fmt"
	"os"

	"github.com/lafriks/go-tiled"
)

func main() {
	var tiledMap *tiled.Map
	var err error
	tiledMap, err = tiled.LoadFile("assets/test_wangsets_map.tmx")
	if err != nil {
		fmt.Printf("error parsing tiledMap: %s", err.Error())
		os.Exit(2)
	}

	fmt.Println(tiledMap.Tilesets[0].WangSets[0].Name)

	wangColors, err := tiledMap.Tilesets[0].WangSets[0].GetWangColors(16)
	if err != nil {
		panic(err)
	}

	fmt.Printf("  TopRight:    %s\n", wangColors[tiled.TopRight].Name)
	fmt.Printf("  BottomRight: %s\n", wangColors[tiled.BottomRight].Name)
	fmt.Printf("  BottomLeft:  %s\n", wangColors[tiled.BottomLeft].Name)
	fmt.Printf("  TopLeft:     %s\n", wangColors[tiled.TopLeft].Name)

}
Output:
Summer
  TopRight:    Rock
  BottomRight: Water
  BottomLeft:  Water
  TopLeft:     Rock

func (*WangSet) UnmarshalXML added in v0.15.0

func (w *WangSet) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a single XML element beginning with the given start element.

type WangSets added in v0.9.0

type WangSets []*WangSet

WangSets contains the list of Wang sets defined for this tileset. https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#wangsets Can contain any number: <wangset>

type WangTile added in v0.9.0

type WangTile struct {
	// The tile ID.
	TileID uint32 `xml:"tileid,attr"`
	// WangID, given by a comma-separated list of indexes (starting from 1, because 0 means _unset_)
	// referring to the Wang colors in the Wang set in the following order:
	// top, top right, right, bottom right, bottom, bottom left, left, top left (since Tiled 1.5).
	// Before Tiled 1.5, the Wang ID was saved as a 32-bit unsigned integer stored in the format
	// 0xCECECECE (where each C is a corner color and each E is an edge color, in reverse order).
	WangID string `xml:"wangid,attr"`
}

WangTile by referring to a tile in the tileset and associating it with a certain Wang ID.

Directories

Path Synopsis
cmd
tmx2img command
Tool to convert a TMX file to an image.
Tool to convert a TMX file to an image.
internal
utils
Package utils contains some generic internal utilities
Package utils contains some generic internal utilities
Package render can be used to render parsed map to image.
Package render can be used to render parsed map to image.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址