--!strict -- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/text/Xml tree <-> a Types.TileMap, and TSX tilesets. -- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. local Xml = require("@formats/codecs/text/Xml") local Types = require("@formats/Types") local Data = require("@formats/vector/tiled/Data") local Tmx = {} type Node = Types.XmlNode local function a(n: Node, k: string): string? return (n.attrs :: any)[k] end local function num(n: Node, k: string, default: number?): number? local v = a(n, k) if v == nil then return default end return tonumber(v) or default end local function flag(n: Node, k: string, default: boolean): boolean local v = a(n, k) if v == nil then return default end return v == "1" or v == "true" end -- ------------------------------------------------------------------------------------------------ read -- -> values, types (types only for the non-string ones) local function properties(n: Node?): ({ [string]: any }, { [string]: string }?) local props: { [string]: any } = {} local types: { [string]: string }? = nil if n == nil then return props, nil end for _, p in Xml.children(n, "property") do local name = a(p, "name") if name then local typ = a(p, "type") or "string" local v: any if typ == "class" then local inner, innerTypes = properties(Xml.child(p, "properties")) v = { class = a(p, "propertytype") or "", properties = inner, propertyTypes = innerTypes } else local text = a(p, "value") if text == nil then text = Xml.text(p) -- multi-line strings end v = Data.value(typ, text :: string) end props[name] = v if typ ~= "string" then types = types or {} ;(types :: any)[name] = typ end end end return props, types end local function withProps(t: any, n: Node) local props, types = properties(Xml.child(n, "properties")) t.properties = props if types then t.propertyTypes = types end end -- the gids of a (or ) node local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?) if encoding == "csv" then return Data.csv(Xml.text(d)) elseif encoding == "base64" then return Data.base64(Xml.text(d), compression) elseif encoding == nil or encoding == "" then local out = {} for _, t in Xml.children(d, "tile") do table.insert(out, num(t, "gid", 0) :: number) end return out, nil, nil end return nil, "unknown encoding " .. encoding, true end local function object(o: Node): any local obj: any = { id = num(o, "id"), name = a(o, "name") or "", class = a(o, "class") or a(o, "type") or "", x = num(o, "x", 0), y = num(o, "y", 0), width = num(o, "width", 0), height = num(o, "height", 0), rotation = num(o, "rotation", 0), gid = num(o, "gid"), visible = flag(o, "visible", true), template = a(o, "template"), shape = "rectangle", } withProps(obj, o) if Xml.child(o, "ellipse") then obj.shape = "ellipse" elseif Xml.child(o, "point") then obj.shape = "point" end for _, kind in { "polygon", "polyline" } do local p = Xml.child(o, kind) if p then obj.shape = kind local pts = {} for x, y in string.gmatch(a(p, "points") or "", "([^,%s]+),([^,%s]+)") do table.insert(pts, { tonumber(x) or 0, tonumber(y) or 0 }) end obj.points = pts end end local t = Xml.child(o, "text") if t then obj.shape = "text" obj.text = { text = Xml.text(t), fontFamily = a(t, "fontfamily") or "sans-serif", pixelSize = num(t, "pixelsize", 16), wrap = flag(t, "wrap", false), color = Data.color(a(t, "color")) or "#000000", bold = flag(t, "bold", false), italic = flag(t, "italic", false), underline = flag(t, "underline", false), strikeout = flag(t, "strikeout", false), kerning = flag(t, "kerning", true), halign = a(t, "halign") or "left", valign = a(t, "valign") or "top", } end return obj end local layer: (n: Node) -> (any, string?, boolean?) local function common(n: Node, typ: string): any local l: any = { type = typ, id = num(n, "id"), name = a(n, "name") or "", visible = flag(n, "visible", true), opacity = num(n, "opacity", 1), x = num(n, "x", 0), y = num(n, "y", 0), offsetX = num(n, "offsetx", 0), offsetY = num(n, "offsety", 0), parallaxX = num(n, "parallaxx", 1), parallaxY = num(n, "parallaxy", 1), tintColor = Data.color(a(n, "tintcolor")), class = a(n, "class") or "", locked = flag(n, "locked", false), } withProps(l, n) return l end local function objectGroup(n: Node): any local l = common(n, "objects") l.drawOrder = a(n, "draworder") or "topdown" l.color = Data.color(a(n, "color")) l.objects = {} for _, o in Xml.children(n, "object") do table.insert(l.objects, object(o)) end return l end layer = function(n: Node): (any, string?, boolean?) local name = n.name if name == "layer" then local l = common(n, "tiles") l.width = num(n, "width", 0) l.height = num(n, "height", 0) local d = Xml.child(n, "data") if d then local enc, comp = a(d, "encoding"), a(d, "compression") l.encoding, l.compression = enc, comp local chunks = Xml.children(d, "chunk") if #chunks > 0 then l.chunks = {} for _, c in chunks do local g, err, uns = gids(c, enc, comp) if not g then return nil, err, uns end table.insert(l.chunks, { x = num(c, "x", 0), y = num(c, "y", 0), width = num(c, "width", 0), height = num(c, "height", 0), data = g }) end else local g, err, uns = gids(d, enc, comp) if not g then return nil, err, uns end l.data = g end end return l elseif name == "objectgroup" then return objectGroup(n) elseif name == "imagelayer" then local l = common(n, "image") l.repeatX = flag(n, "repeatx", false) l.repeatY = flag(n, "repeaty", false) local img = Xml.child(n, "image") if img then l.imageSource = a(img, "source") l.imageWidth = num(img, "width") l.imageHeight = num(img, "height") l.transparentColor = Data.color(a(img, "trans")) end return l elseif name == "group" then local l = common(n, "group") l.layers = {} for _, c in n.children do if type(c) == "table" then local sub, err, uns = layer(c) if err then return nil, err, uns end if sub then table.insert(l.layers, sub) end end end return l end return nil end -- a element (in a map, or a .tsx root) -> Tileset function Tmx.tileset(n: Node): any local ts: any = { firstGid = num(n, "firstgid", 1), source = a(n, "source"), name = a(n, "name") or "", tileWidth = num(n, "tilewidth", 0), tileHeight = num(n, "tileheight", 0), spacing = num(n, "spacing", 0), margin = num(n, "margin", 0), count = num(n, "tilecount", 0), columns = num(n, "columns", 0), objectAlignment = a(n, "objectalignment"), class = a(n, "class") or "", } withProps(ts, n) local off = Xml.child(n, "tileoffset") if off then ts.tileOffset = { x = num(off, "x", 0), y = num(off, "y", 0) } end local img = Xml.child(n, "image") if img then ts.imageSource = a(img, "source") ts.imageWidth = num(img, "width") ts.imageHeight = num(img, "height") ts.transparentColor = Data.color(a(img, "trans")) end local tiles = {} for _, t in Xml.children(n, "tile") do local tile: any = { id = num(t, "id", 0), class = a(t, "class") or a(t, "type") or "", probability = num(t, "probability") } withProps(tile, t) local ti = Xml.child(t, "image") if ti then tile.imageSource = a(ti, "source") tile.imageWidth = num(ti, "width") tile.imageHeight = num(ti, "height") end local anim = Xml.child(t, "animation") if anim then tile.animation = {} for _, f in Xml.children(anim, "frame") do table.insert(tile.animation, { tileId = num(f, "tileid", 0), duration = num(f, "duration", 0) }) end end local og = Xml.child(t, "objectgroup") if og then tile.objectGroup = objectGroup(og) end table.insert(tiles, tile) end ts.tiles = tiles return ts end -- read(root) -> TileMap | nil, message, unsupported? function Tmx.read(root: Node): (any, string?, boolean?) if root.name ~= "map" then return nil, "the root element is <" .. root.name .. ">, not " end local map: any = Types.TileMap.new(num(root, "width", 0) :: number, num(root, "height", 0) :: number, num(root, "tilewidth", 0) :: number, num(root, "tileheight", 0) :: number) map.version = a(root, "version") map.tiledVersion = a(root, "tiledversion") map.orientation = a(root, "orientation") or "orthogonal" map.renderOrder = a(root, "renderorder") or "right-down" map.infinite = flag(root, "infinite", false) map.nextLayerId = num(root, "nextlayerid") map.nextObjectId = num(root, "nextobjectid") map.backgroundColor = Data.color(a(root, "backgroundcolor")) map.hexSideLength = num(root, "hexsidelength") map.staggerAxis = a(root, "staggeraxis") map.staggerIndex = a(root, "staggerindex") map.class = a(root, "class") or "" map.parallaxOriginX = num(root, "parallaxoriginx", 0) map.parallaxOriginY = num(root, "parallaxoriginy", 0) withProps(map, root) for _, c in root.children do if type(c) == "table" then if c.name == "tileset" then table.insert(map.tilesets, Tmx.tileset(c)) else local l, err, uns = layer(c) if err then return nil, err, uns end if l then table.insert(map.layers, l) end end end end return map, nil end -- ------------------------------------------------------------------------------------------------ write type Attrs = { [string]: string } local function el(name: string, attrs: { { any } }, children: { any }?): Node -- attrs in order; nil / default values dropped by the caller local o = Types.object() for _, kv in attrs do if kv[2] ~= nil then local v = kv[2] Types.set(o, kv[1], if type(v) == "number" then Data.num(v) elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v)) end end return Xml.element(name, o :: any, children) end local function nz(v: any, default: any): any if v == nil or v == default then return nil end return v end local function str(v: any): string? if type(v) == "string" and v ~= "" then return v end return nil end local function propsNode(props: any, types: any): Node? if type(props) ~= "table" or next(props) == nil then return nil end local list = {} for _, k in Data.sortedKeys(props) do local v = props[k] local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil) if typ == "class" and type(v) == "table" then local inner = propsNode(v.properties, v.propertyTypes) table.insert(list, el("property", { { "name", k }, { "type", "class" }, { "propertytype", v.class or "" } }, if inner then { inner } else nil)) else local text = if type(v) == "boolean" then (if v then "true" else "false") elseif type(v) == "number" then Data.num(v) else tostring(v) if string.find(text, "\n", 1, true) then table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil } }, { text })) else table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil }, { "value", text } })) end end end return el("properties", {}, list) end local function addProps(children: { any }, t: any) local p = propsNode(t.properties, t.propertyTypes) if p then table.insert(children, p) end end local function writeObject(o: any): Node local kids = {} addProps(kids, o) local shape = o.shape if shape == "ellipse" then table.insert(kids, el("ellipse", {})) elseif shape == "point" then table.insert(kids, el("point", {})) elseif (shape == "polygon" or shape == "polyline") and type(o.points) == "table" then local pts = {} for _, p in o.points do table.insert(pts, Data.num(tonumber(p[1]) or 0) .. "," .. Data.num(tonumber(p[2]) or 0)) end table.insert(kids, el(shape, { { "points", table.concat(pts, " ") } })) elseif shape == "text" and type(o.text) == "table" then local t = o.text table.insert(kids, el("text", { { "fontfamily", nz(t.fontFamily, "sans-serif") }, { "pixelsize", nz(t.pixelSize, 16) }, { "wrap", nz(t.wrap, false) }, { "color", nz(t.color, "#000000") }, { "bold", nz(t.bold, false) }, { "italic", nz(t.italic, false) }, { "underline", nz(t.underline, false) }, { "strikeout", nz(t.strikeout, false) }, { "kerning", nz(t.kerning, true) }, { "halign", nz(t.halign, "left") }, { "valign", nz(t.valign, "top") }, }, { tostring(t.text or "") })) end return el("object", { { "id", o.id }, { "name", str(o.name) }, { "type", str(o.class) }, { "gid", o.gid }, { "x", o.x or 0 }, { "y", o.y or 0 }, { "width", nz(o.width, 0) }, { "height", nz(o.height, 0) }, { "rotation", nz(o.rotation, 0) }, { "visible", nz(o.visible, true) }, { "template", o.template }, }, kids) end local function commonAttrs(l: any, extra: { { any } }): { { any } } local out: { { any } } = { { "id", l.id }, { "name", str(l.name) or "" }, { "class", str(l.class) } } table.move(extra, 1, #extra, #out + 1, out) local tail = { { "visible", nz(l.visible, true) }, { "locked", nz(l.locked, false) }, { "opacity", nz(l.opacity, 1) }, { "tintcolor", l.tintColor }, { "offsetx", nz(l.offsetX, 0) }, { "offsety", nz(l.offsetY, 0) }, { "parallaxx", nz(l.parallaxX, 1) }, { "parallaxy", nz(l.parallaxY, 1) }, } table.move(tail, 1, #tail, #out + 1, out) return out end local function writeObjectGroup(l: any, tag: string?): Node local kids = {} addProps(kids, l) for _, o in (if type(l.objects) == "table" then l.objects else {}) do table.insert(kids, writeObject(o)) end return el(tag or "objectgroup", commonAttrs(l, { { "color", l.color }, { "draworder", nz(l.drawOrder, "topdown") } }), kids) end export type WriteOptions = { encoding: string?, compression: string?, level: number? } local writeLayer: (l: any, o: WriteOptions) -> (Node?, string?) writeLayer = function(l: any, o: WriteOptions): (Node?, string?) local t = l.type if t == "tiles" then local kids = {} addProps(kids, l) local enc = o.encoding or l.encoding or "csv" local comp = if o.encoding then o.compression else (o.compression or l.compression) if enc ~= "base64" then comp = nil end local function payload(g: { number }, width: number): (string?, string?) if enc == "csv" then return Data.csvText(g, width), nil end local s, err = Data.toBase64(g, comp, o.level) if not s then return nil, err end return "\n " .. s .. "\n ", nil end local dataKids = {} if type(l.chunks) == "table" then for _, c in l.chunks do local kids: { any } = {} if enc == "xml" then for _, g in (c.data or {}) do table.insert(kids, el("tile", { { "gid", if g ~= 0 then g else nil } })) end else local s, err = payload(c.data or {}, c.width or 0) if not s then return nil, err end kids = { s } end table.insert(dataKids, el("chunk", { { "x", c.x or 0 }, { "y", c.y or 0 }, { "width", c.width or 0 }, { "height", c.height or 0 } }, kids)) end elseif type(l.data) == "table" and enc == "xml" then for _, g in l.data do table.insert(dataKids, el("tile", { { "gid", if g ~= 0 then g else nil } })) end elseif type(l.data) == "table" then local s, err = payload(l.data, l.width or 0) if not s then return nil, err end dataKids = { s } end table.insert(kids, el("data", { { "encoding", if enc == "xml" then nil else enc }, { "compression", comp } }, dataKids)) return el("layer", commonAttrs(l, { { "x", nz(l.x, 0) }, { "y", nz(l.y, 0) }, { "width", l.width or 0 }, { "height", l.height or 0 } }), kids), nil elseif t == "objects" then return writeObjectGroup(l), nil elseif t == "image" then local kids = {} addProps(kids, l) if l.imageSource then table.insert(kids, el("image", { { "source", l.imageSource }, { "trans", l.transparentColor }, { "width", l.imageWidth }, { "height", l.imageHeight } })) end return el("imagelayer", commonAttrs(l, { { "repeatx", nz(l.repeatX, false) }, { "repeaty", nz(l.repeatY, false) } }), kids), nil elseif t == "group" then local kids = {} addProps(kids, l) for _, c in (if type(l.layers) == "table" then l.layers else {}) do local n, err = writeLayer(c, o) if not n then return nil, err end table.insert(kids, n) end return el("group", commonAttrs(l, {}), kids), nil end return nil, "unknown layer type " .. tostring(t) end -- tilesetNode(ts, inMap) -> function Tmx.tilesetNode(ts: any, inMap: boolean): Node if inMap and type(ts.source) == "string" then return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) end local kids = {} if type(ts.tileOffset) == "table" then table.insert(kids, el("tileoffset", { { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } })) end addProps(kids, ts) if ts.imageSource then table.insert(kids, el("image", { { "source", ts.imageSource }, { "trans", ts.transparentColor }, { "width", ts.imageWidth }, { "height", ts.imageHeight } })) end for _, tile in (if type(ts.tiles) == "table" then ts.tiles else {}) do local tk = {} addProps(tk, tile) if tile.imageSource then table.insert(tk, el("image", { { "source", tile.imageSource }, { "width", tile.imageWidth }, { "height", tile.imageHeight } })) end if type(tile.objectGroup) == "table" then table.insert(tk, writeObjectGroup(tile.objectGroup)) end if type(tile.animation) == "table" then local frames = {} for _, f in tile.animation do table.insert(frames, el("frame", { { "tileid", f.tileId or 0 }, { "duration", f.duration or 0 } })) end table.insert(tk, el("animation", {}, frames)) end table.insert(kids, el("tile", { { "id", tile.id or 0 }, { "type", str(tile.class) }, { "probability", tile.probability } }, tk)) end return el("tileset", { { "firstgid", if inMap then ts.firstGid or 1 else nil }, { "name", ts.name or "" }, { "class", str(ts.class) }, { "tilewidth", ts.tileWidth or 0 }, { "tileheight", ts.tileHeight or 0 }, { "spacing", nz(ts.spacing, 0) }, { "margin", nz(ts.margin, 0) }, { "tilecount", ts.count or 0 }, { "columns", ts.columns or 0 }, { "objectalignment", ts.objectAlignment }, }, kids) end -- write(map, opts) -> an XML document node | nil, message function Tmx.write(map: any, o: WriteOptions): (Node?, string?) local kids = {} addProps(kids, map) for _, ts in map.tilesets do table.insert(kids, Tmx.tilesetNode(ts, true)) end for _, l in map.layers do local n, err = writeLayer(l, o) if not n then return nil, err end table.insert(kids, n) end local root = el("map", { { "version", map.version or "1.10" }, { "tiledversion", map.tiledVersion }, { "class", str(map.class) }, { "orientation", map.orientation or "orthogonal" }, { "renderorder", map.renderOrder or "right-down" }, { "width", map.width }, { "height", map.height }, { "tilewidth", map.tileWidth }, { "tileheight", map.tileHeight }, { "hexsidelength", map.hexSideLength }, { "staggeraxis", map.staggerAxis }, { "staggerindex", map.staggerIndex }, { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, { "backgroundcolor", map.backgroundColor }, { "infinite", map.infinite == true }, { "nextlayerid", map.nextLayerId }, { "nextobjectid", map.nextObjectId }, }, kids) return Xml.document(root, { version = "1.0", encoding = "UTF-8" }), nil end return Tmx