vector formats: comments are specs only

This commit is contained in:
4DBug committed 2026-11-01 01:53:48 -05:00
1 parent d91dc6c597
commit 89a2047349
10 files changed
+34 -126

No files matched your search

+4 -18
View File
@@ -1,11 +1,5 @@
--!strict
-- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes,
-- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space
-- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into
-- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a
-- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>.
-- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported.
-- Never throws.
-- vector/svg/Parse: an SVG document (an Xml tree) to a Types.Vector: the cascade, shapes, paints, groups, clips.
local Xml = require("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local Style = require("@rosetta/vector/svg/Style")
@@ -59,7 +53,7 @@ type Ctx = {
groups: { any },
clips: { any },
unsupported: { [string]: number },
vw: number, -- the current viewport (for percentages)
vw: number,
vh: number,
depth: number,
useDepth: number,
@@ -90,7 +84,7 @@ local function refId(s: string?): string?
return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)")
end
-- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style=""
-- cascade: presentation attributes < CSS rules (by specificity, then order) < style=""
local function specified(n: Node, ctx: Ctx): { [string]: string }
local out: { [string]: string } = {}
for k, v in pairs(n.attrs :: any) do
@@ -130,7 +124,6 @@ local function specified(n: Node, ctx: Ctx): { [string]: string }
return out
end
-- computed(parent, n) -> the element's computed property strings
local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string }
local out: { [string]: string } = {}
for k in pairs(INHERITED) do
@@ -188,7 +181,6 @@ local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number }
return list
end
-- a gradient attribute, looked up through href templates
local function gattr(g: Node, k: string, ctx: Ctx): string?
local cur: Node? = g
local guard = 0
@@ -250,7 +242,6 @@ local function gradient(g: Node, opacity: number, ctx: Ctx): any
return p
end
-- paint(value, opacity, st) -> Paint | nil (none)
local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any
if value == nil then
return nil
@@ -370,7 +361,6 @@ local function transformOf(n: Node): M
return IDENTITY
end
-- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox.
local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number?
local cp = ctx.ids[ref]
if cp == nil or local_(cp) ~= "clipPath" then
@@ -508,7 +498,6 @@ local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: numbe
table.insert(ctx.vector.paths, p)
end
-- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y)
function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M
if vb == nil or vb[3] <= 0 or vb[4] <= 0 then
return { 1, 0, 0, 1, x, y }
@@ -553,7 +542,6 @@ local function viewBox(n: Node): { number }?
end
local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?)
-- a layer for opacity / clip-path
local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1)
local clipRef = refId(st["clip-path"])
local g = group
@@ -563,7 +551,6 @@ local function container(n: Node, st: { [string]: string }, ctm: M, group: numbe
local bbox: { number }? = nil
local cp = ctx.ids[clipRef]
if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then
-- the group's bounding box in its user space: walk once into a scratch vector
local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips
local scratch = Types.Vector.new(0, 0)
ctx.vector, ctx.groups, ctx.clips = scratch, {}, {}
@@ -610,7 +597,7 @@ local function container(n: Node, st: { [string]: string }, ctm: M, group: numbe
end
end
-- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own
-- nested svg / symbol: overflow is hidden unless it says otherwise
local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number?
local ov = attr(n, "overflow")
if ov == "visible" or ov == "auto" then
@@ -698,7 +685,6 @@ walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: numbe
end
-- ------------------------------------------------------------------------------------------------ entry
-- document(doc, opts) -> Vector | nil, message
function Parse.document(doc: any): (Types.Vector?, string?)
local root = doc.root
if root == nil or Xml.localName(root.name) ~= "svg" then
+6 -17
View File
@@ -1,9 +1,6 @@
--!strict
-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands
-- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the
-- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a
-- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the
-- commands so far are kept, as the spec's error handling says).
-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3, SVG 2 "Path data"); arcs to cubics per implementation notes
-- F.6 (out-of-range radii scaled up); parsing stops at the first error, keeping the commands so far (as the spec says).
local PathData = {}
export type Cmd = { op: string, [number]: number }
@@ -13,7 +10,6 @@ local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math
local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 }
-- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out
local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd })
if x1 == x2 and y1 == y2 then
return
@@ -81,14 +77,13 @@ local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: numbe
end
PathData.arc = arc
-- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing)
function PathData.parse(d: string): ({ Cmd }, boolean)
local out: { Cmd } = {}
local i, n = 1, #d
local cx, cy = 0, 0 -- current point
local sx, sy = 0, 0 -- subpath start
local lcx, lcy = 0, 0 -- last control point (for S / T)
local last = "" -- previous command letter (upper case)
local cx, cy = 0, 0
local sx, sy = 0, 0
local lcx, lcy = 0, 0
local last = ""
local cmd: string? = nil
local rel = false
local nums: { number } = table.create(7) :: { number }
@@ -249,15 +244,12 @@ function PathData.parse(d: string): ({ Cmd }, boolean)
return out, true
end
-- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box
-- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves
function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?)
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
local px, py = 0, 0
for _, c in cmds do
local op = c.op
if op == "C" then
-- the curve's exact extrema
local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6]
for axis = 1, 2 do
local p0 = if axis == 1 then px else py
@@ -328,7 +320,6 @@ function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?)
return x0, y0, x1, y1
end
-- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros)
local function num(v: number): string
if v ~= v or v == math.huge or v == -math.huge then
return "0"
@@ -343,7 +334,6 @@ local function num(v: number): string
end
PathData.num = num
-- serialize(cmds) -> path data text
function PathData.serialize(cmds: { Cmd }): string
local out = {}
for _, c in cmds do
@@ -360,7 +350,6 @@ function PathData.serialize(cmds: { Cmd }): string
return table.concat(out, " ")
end
-- toRaster(cmds) -> the codecs/image/Raster command list (moveTo / lineTo / quadTo / cubicTo / close)
local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" }
function PathData.toRaster(cmds: { Cmd }): { any }
local out = table.create(#cmds)
+3 -15
View File
@@ -1,9 +1,5 @@
--!strict
-- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/image/Raster (antialiased coverage, nonzero / even-odd,
-- the stroker) and codecs/image/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and
-- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat,
-- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox
-- maps onto the image by meta.preserveAspectRatio. Never throws.
-- vector/svg/Render: a Types.Vector to an rgba8 Image via codecs/image/Raster and codecs/image/Blend.
local Types = require("@rosetta/Types")
local Raster = require("@rosetta/codecs/image/Raster")
local Blend = require("@rosetta/codecs/image/Blend")
@@ -42,7 +38,6 @@ local function stopColor(stops: { { number } }, t: number): (number, number, num
return s[2], s[3], s[4], s[5]
end
-- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds
local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))?
local stops = p.stops
if type(stops) ~= "table" or #stops == 0 then
@@ -128,7 +123,6 @@ local function gradientFn(p: any, device: M, bbox: { number }?): ((number, numbe
end
-- ------------------------------------------------------------------------------------------------ dashes
-- subpaths of a command list with their closed flag
local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } }
local out = {}
local cur: { any }? = nil
@@ -151,7 +145,6 @@ local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } }
return out
end
-- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol)
local function polyline(cmds: { any }, tol: number): { number }
local pts: { number } = {}
local px, py = 0, 0
@@ -269,16 +262,14 @@ end
-- ------------------------------------------------------------------------------------------------ rendering
export type Options = {
background: { number }?, -- r, g, b, a under the drawing (default transparent)
tolerance: number?, -- curve flattening in device pixels (default 0.1)
background: { number }?, -- r, g, b, a; default transparent
tolerance: number?, -- device pixels; default 0.1
}
-- the device transform scale (for stroke flattening tolerances)
local function scaleOf(m: M): number
return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3]))
end
-- rasterize(v, w, h, opts?) -> rgba8 Image
function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image
local o: Options = opts or {}
local img = Types.Image.new(w, h)
@@ -297,7 +288,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?)
local clips: { any } = if type(meta.clips) == "table" then meta.clips else {}
local tol = o.tolerance or 0.1
local clipCache: { [number]: buffer } = {}
-- a clip's coverage over the whole image (1 byte per pixel)
local function clipMask(id: number): buffer?
if clipCache[id] then
return clipCache[id]
@@ -325,7 +315,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?)
clipCache[id] = mask
return mask
end
-- the layer stack: { group id, image }
local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } }
local function chain(g: number?): { number }
local out = {}
@@ -365,7 +354,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?)
if type(p) ~= "table" or type(p.d) ~= "table" then
continue
end
-- groups: pop the layers this path is not in, push the ones it needs
local want = chain(p.group)
local keep = 1
while keep < #stack and stack[keep + 1].id == want[keep] do
+2 -13
View File
@@ -1,9 +1,5 @@
--!strict
-- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba /
-- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor),
-- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated
-- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped).
-- Never throws.
-- vector/svg/Style: SVG attribute value syntaxes (CSS Color 3, lengths, transform lists) and a <style> CSS subset.
local Raster = require("@rosetta/codecs/image/Raster")
local Style = {}
@@ -57,7 +53,6 @@ local function hue(p: number, q: number, t: number): number
return p
end
-- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value
function Style.color(s: string, current: { number }?): any
s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1")))
if s == "none" then
@@ -136,7 +131,7 @@ function Style.color(s: string, current: { number }?): any
return nil
end
-- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil
-- SVG number: sign? digits? ("." digits)? exponent?
local function scan(s: string, i: number): (number?, number)
local n = #s
local st = i
@@ -194,7 +189,6 @@ local function scan(s: string, i: number): (number?, number)
return tonumber(string.sub(s, st, i - 1)), i
end
-- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100)
local UNITS: { [string]: number } = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 }
function Style.length(s: string?, ref: number?, fontSize: number?): number?
if s == nil then
@@ -219,7 +213,6 @@ function Style.length(s: string?, ref: number?, fontSize: number?): number?
return if k then x * k else nil
end
-- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else
function Style.numbers(s: string?): { number }
local out = {}
if s == nil then
@@ -242,7 +235,6 @@ function Style.numbers(s: string?): { number }
return out
end
-- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error
local mul = Raster.multiply
Style.multiply = mul
function Style.transform(s: string): { number }?
@@ -285,7 +277,6 @@ function Style.transform(s: string): { number }?
return m
end
-- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped)
function Style.declarations(s: string): { [string]: string }
local out: { [string]: string } = {}
for decl in string.gmatch(s, "[^;]+") do
@@ -333,7 +324,6 @@ local function selector(s: string): Selector?
return sel
end
-- css(text, rules?) -> rules (appended to the list given)
function Style.css(text: string, rules: { Rule }?): { Rule }
local out: { Rule } = rules or {}
text = string.gsub(text, "/%*.-%*/", "")
@@ -362,7 +352,6 @@ function Style.css(text: string, rules: { Rule }?): { Rule }
return out
end
-- matches(sel, tag, id, classes) -> boolean
function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean
if sel.tag and sel.tag ~= tag then
return false
+1 -6
View File
@@ -1,7 +1,5 @@
--!strict
-- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients
-- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...>
-- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message.
-- vector/svg/Write: a Types.Vector to SVG text; never throws (bad values return nil, message).
local Xml = require("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local PathData = require("@rosetta/vector/svg/PathData")
@@ -41,7 +39,6 @@ local function matrix(m: any): string?
return "matrix(" .. table.concat(parts, " ") .. ")"
end
-- write(v) -> SVG text | nil, message
function Write.vector(v: Types.Vector): (string?, string?)
if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then
return nil, "needs a Vector value"
@@ -51,7 +48,6 @@ function Write.vector(v: Types.Vector): (string?, string?)
local clips: { any } = if type(meta.clips) == "table" then meta.clips else {}
local defs = {}
local gradients = 0
-- paints -> attribute values (gradients go to defs)
local function paintAttrs(p: any, which: string): { { any } }
if type(p) ~= "table" then
return { { which, "none" } }
@@ -109,7 +105,6 @@ function Write.vector(v: Types.Vector): (string?, string?)
return "url(#" .. clipIds[id] .. ")"
end
local root = {}
-- the open <g> stack: { id, children }
local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } }
local function chain(g: number?): { number }
local out = {}
+4 -14
View File
@@ -1,15 +1,7 @@
--!strict
-- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs
-- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg
-- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from
-- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke /
-- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and
-- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path
-- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %).
-- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and
-- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/image/Raster; encode writes SVG back from a Vector.
-- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also
-- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes.
-- vector/svg: SVG 1.1 / 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: shapes and paths, transforms,
-- nested svg / use / symbol, a CSS subset, gradients, clip-path, group opacity, strokes, dashes, units. Not supported
-- (meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject, switch conditions, CSS combinators.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -32,7 +24,7 @@ local Svg = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
maxBytes: number?, -- default 64 MB
}
export type EncodeOptions = {}
export type RasterizeOptions = Render.Options
@@ -77,8 +69,6 @@ function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox
-- maps onto w x h by its preserveAspectRatio.
function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?)
if type(v) ~= "table" or type(v.paths) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Vector value")
+4 -11
View File
@@ -1,12 +1,10 @@
--!strict
-- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip)
-- to gids and back; property values and their types; number formatting. Never throws.
-- vector/tiled/Data: tile layer data shared by TMX and TMJ: CSV, base64 (raw / zlib / gzip), properties, numbers.
local Base64 = require("@rosetta/core/Base64")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Data = {}
-- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message
function Data.csv(text: string): ({ number }?, string?)
local out = {}
for tok in string.gmatch(text, "[^,%s]+") do
@@ -19,7 +17,6 @@ function Data.csv(text: string): ({ number }?, string?)
return out, nil
end
-- base64(text, compression) -> { gid } | nil, message, unsupported?
function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?)
local raw, err = Base64.decode(text)
if not raw then
@@ -49,7 +46,6 @@ function Data.base64(text: string, compression: string?): ({ number }?, string?,
return out, nil, nil
end
-- toBase64(gids, compression?, level?) -> text | nil, message
function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?)
local b = buffer.create(#gids * 4)
for i, g in gids do
@@ -73,7 +69,7 @@ function Data.toBase64(gids: { number }, compression: string?, level: number?):
return Base64.encode(b), nil
end
-- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print
-- integers without a fraction (gids up to 2^32), others in the shortest form both runtimes print
function Data.num(v: number): string
if v % 1 == 0 and math.abs(v) < 2 ^ 53 then
return string.format("%.0f", v)
@@ -85,7 +81,7 @@ function Data.num(v: number): string
return s
end
-- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line)
-- Tiled's CSV layout: one row per line
function Data.csvText(gids: { number }, width: number): string
local rows = {}
local row = {}
@@ -102,7 +98,7 @@ function Data.csvText(gids: { number }, width: number): string
return "\n" .. table.concat(rows, ",\n") .. "\n"
end
-- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil)
-- Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque
function Data.color(s: string?): string?
if type(s) ~= "string" then
return nil
@@ -114,7 +110,6 @@ function Data.color(s: string?): string?
return "#" .. h
end
-- property values: TMX / TMJ type names -> a Luau value from text
function Data.value(typ: string, text: string): any
if typ == "int" or typ == "float" or typ == "object" then
return tonumber(text) or 0
@@ -126,7 +121,6 @@ function Data.value(typ: string, text: string): any
return text
end
-- typeOf(v, declared?) -> the Tiled type to write for v
function Data.typeOf(v: any, declared: string?): string
if declared then
return declared
@@ -141,7 +135,6 @@ function Data.typeOf(v: any, declared: string?): string
return "string"
end
-- sortedKeys(t) -> its string keys, sorted
function Data.sortedKeys(t: { [any]: any }): { string }
local out = {}
for k in pairs(t) do
+1 -6
View File
@@ -1,6 +1,5 @@
--!strict
-- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ
-- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?.
-- vector/tiled/Tmj: TMJ / TSJ (JSON map format, Tiled 1.12 docs) <-> a Types.TileMap.
local Types = require("@rosetta/Types")
local Data = require("@rosetta/vector/tiled/Data")
@@ -245,7 +244,6 @@ layer = function(v: any, depth: number): (any, string?, boolean?)
return nil, "unknown layer type " .. tostring(v.type)
end
-- tileset(v) -> Tileset (a map's entry, or a .tsj root)
function Tmj.tileset(v: any): any
local ts: any = {
firstGid = n(v.firstgid, 1),
@@ -297,7 +295,6 @@ function Tmj.tileset(v: any): any
return ts
end
-- read(value) -> TileMap | nil, message, unsupported?
function Tmj.read(v: any): (any, string?, boolean?)
if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then
return nil, "not a Tiled map (type is not \"map\")"
@@ -535,7 +532,6 @@ writeLayer = function(l: any, o: WriteOptions): (any, string?)
return obj(fields), nil
end
-- tilesetValue(ts, inMap) -> a JSON object
function Tmj.tilesetValue(ts: any, inMap: boolean): any
if inMap and type(ts.source) == "string" then
return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } })
@@ -590,7 +586,6 @@ function Tmj.tilesetValue(ts: any, inMap: boolean): any
})
end
-- write(map, opts) -> a JSON value | nil, message
function Tmj.write(map: any, o: WriteOptions): (any, string?)
local layers = {}
for _, l in map.layers do
+1 -9
View File
@@ -1,6 +1,5 @@
--!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?.
-- vector/tiled/Tmx: TMX / TSX (TMX map format, Tiled 1.12 docs) <-> a Types.TileMap.
local Xml = require("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local Data = require("@rosetta/vector/tiled/Data")
@@ -28,7 +27,6 @@ local function flag(n: Node, k: string, default: boolean): boolean
end
-- ------------------------------------------------------------------------------------------------ read
-- <properties> -> 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
@@ -68,7 +66,6 @@ local function withProps(t: any, n: Node)
end
end
-- the gids of a <data> (or <chunk>) node
local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?)
if encoding == "csv" then
return Data.csv(Xml.text(d))
@@ -233,7 +230,6 @@ layer = function(n: Node): (any, string?, boolean?)
return nil
end
-- a <tileset> element (in a map, or a .tsx root) -> Tileset
function Tmx.tileset(n: Node): any
local ts: any = {
firstGid = num(n, "firstgid", 1),
@@ -287,7 +283,6 @@ function Tmx.tileset(n: Node): any
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 <map>"
@@ -330,7 +325,6 @@ end
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
@@ -533,7 +527,6 @@ writeLayer = function(l: any, o: WriteOptions): (Node?, string?)
return nil, "unknown layer type " .. tostring(t)
end
-- tilesetNode(ts, inMap) -> <tileset>
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 } })
@@ -578,7 +571,6 @@ function Tmx.tilesetNode(ts: any, inMap: boolean): Node
}, 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)
+8 -17
View File
@@ -1,14 +1,7 @@
--!strict
-- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map
-- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib /
-- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles,
-- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers,
-- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets
-- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay
-- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the
-- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json".
-- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external
-- tilesets or images (callers resolve `source` / `imageSource` paths themselves).
-- vector/tiled: Tiled maps, TMX (XML) / TMJ (JSON), and TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map Format", "JSON
-- Map Format"). Supports: every orientation, tile / object / image / group layers, infinite maps, typed properties,
-- tilesets. Not supported: zstd layer data (Err.UNSUPPORTED), Wang sets / terrains, loading external tilesets / images.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -31,14 +24,14 @@ local Tiled = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 256 MB)
maxBytes: number?, -- default 256 MB
}
export type EncodeOptions = {
format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (JSON); default: the source's flavour, else tmx
format: string?, -- "tmx" | "tsx" | "tmj" | "tsj" | "json"; default: the source's flavour, else tmx
encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64"
compression: string?, -- base64 data: nil | "zlib" | "gzip"
level: number?, -- deflate level for compressed data (default 6)
indent: number?, -- spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON)
compression: string?, -- nil | "zlib" | "gzip"
level: number?, -- default 6
indent: number?, -- default 1 (TMX), 2 (TMJ); 0 = compact JSON
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -72,8 +65,6 @@ function Tiled.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its
-- meta.tileset is true) | nil, Err
function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if r.limit - r.base > maxBytes then