rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings

This commit is contained in:
4DBug committed 2026-11-01 01:19:16 -05:00
1 parent 2956576d7f
commit 22ddcd78fa
941 files changed
+3364 -3364

No files matched your search

+758
View File
@@ -0,0 +1,758 @@
--!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.
local Xml = require("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local Style = require("@rosetta/vector/svg/Style")
local PathData = require("@rosetta/vector/svg/PathData")
local Parse = {}
type Node = Types.XmlNode
type M = { number }
local IDENTITY = { 1, 0, 0, 1, 0, 0 }
local mul = Style.multiply
-- properties that inherit, and their initial values
local INHERITED: { [string]: string } = {
fill = "black",
["fill-opacity"] = "1",
["fill-rule"] = "nonzero",
stroke = "none",
["stroke-width"] = "1",
["stroke-opacity"] = "1",
["stroke-linecap"] = "butt",
["stroke-linejoin"] = "miter",
["stroke-miterlimit"] = "4",
["stroke-dasharray"] = "none",
["stroke-dashoffset"] = "0",
["clip-rule"] = "nonzero",
visibility = "visible",
color = "black",
["font-size"] = "16",
}
-- not inherited (reset per element)
local LOCAL: { [string]: boolean } = {
opacity = true,
["clip-path"] = true,
display = true,
["stop-color"] = true,
["stop-opacity"] = true,
mask = true,
filter = true,
}
local UNSUPPORTED: { [string]: boolean } = { text = true, image = true, pattern = true, mask = true, marker = true, filter = true, foreignObject = true, textPath = true, tspan = true }
local CONTAINERS = { g = true, a = true, switch = true }
local SHAPES = { path = true, rect = true, circle = true, ellipse = true, line = true, polyline = true, polygon = true }
type Ctx = {
ids: { [string]: Node },
rules: { Style.Rule },
vector: Types.Vector,
groups: { any },
clips: { any },
unsupported: { [string]: number },
vw: number, -- the current viewport (for percentages)
vh: number,
depth: number,
useDepth: number,
}
local function local_(n: Node): string
return Xml.localName(n.name)
end
local function attr(n: Node, k: string): string?
local a = n.attrs :: any
return a[k]
end
local function href(n: Node): string?
local h = attr(n, "href") or attr(n, "xlink:href")
if h == nil then
for k, v in pairs(n.attrs :: any) do
if type(k) == "string" and Xml.localName(k) == "href" then
return v
end
end
end
return h
end
local function refId(s: string?): string?
if s == nil then
return nil
end
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=""
local function specified(n: Node, ctx: Ctx): { [string]: string }
local out: { [string]: string } = {}
for k, v in pairs(n.attrs :: any) do
if type(k) == "string" and type(v) == "string" and (INHERITED[k] or LOCAL[k]) then
out[k] = v
end
end
if #ctx.rules > 0 then
local classes: { [string]: boolean } = {}
for c in string.gmatch(attr(n, "class") or "", "%S+") do
classes[c] = true
end
local hits: { Style.Rule } = {}
for _, r in ctx.rules do
if Style.matches(r.selector, local_(n), attr(n, "id"), classes) then
table.insert(hits, r)
end
end
table.sort(hits, function(a: any, b: any): boolean
if a.selector.specificity ~= b.selector.specificity then
return a.selector.specificity < b.selector.specificity
end
return a.order < b.order
end)
for _, r in hits do
for k, v in pairs(r.decls) do
out[k] = v
end
end
end
local st = attr(n, "style")
if st then
for k, v in pairs(Style.declarations(st)) do
out[k] = v
end
end
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
out[k] = parent[k]
end
for k, v in pairs(specified(n, ctx)) do
if v == "inherit" then
out[k] = parent[k]
elseif INHERITED[k] or LOCAL[k] then
out[k] = v
end
end
return out
end
local function len(s: string?, ref: number, st: { [string]: string }, default: number?): number?
local fs = Style.length(st["font-size"], 16) or 16
local v = Style.length(s, ref, fs)
if v == nil then
return default
end
return v
end
-- ------------------------------------------------------------------------------------------------ paints
local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number } }
local list = {}
local parentStyle = computed(INHERITED, g, ctx)
for _, s in Xml.children(g) do
if local_(s) == "stop" then
local st = computed(parentStyle, s, ctx)
local off = attr(s, "offset") or "0"
local o = tonumber(string.match(off, "^%s*([%d.eE+-]+)%s*%%%s*$") or "")
local offset = if o then o / 100 else (tonumber(off) or 0)
offset = math.clamp(offset, 0, 1)
if #list > 0 and offset < list[#list][1] then
offset = list[#list][1]
end
local col = Style.color(st["stop-color"] or "black", Style.color(st.color or "black")) or { 0, 0, 0, 255 }
if col == "none" then
col = { 0, 0, 0, 0 }
end
local op = math.clamp(tonumber(st["stop-opacity"] or "1") or 1, 0, 1)
table.insert(list, { offset, col[1], col[2], col[3], math.floor(col[4] * op + 0.5) })
end
end
if #list == 0 then
local h = refId(href(g))
local other = if h then ctx.ids[h] else nil
if other and not seen[other] then
seen[other] = true
return stops(other, ctx, seen)
end
end
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
while cur and guard < 16 do
local v = attr(cur, k)
if v ~= nil then
return v
end
local h = refId(href(cur))
cur = if h then ctx.ids[h] else nil
guard += 1
end
return nil
end
local function gradient(g: Node, opacity: number, ctx: Ctx): any
local kind = local_(g)
local units = gattr(g, "gradientUnits", ctx) or "objectBoundingBox"
local obb = units ~= "userSpaceOnUse"
local list = stops(g, ctx, { [g] = true })
if #list == 0 then
return "none"
end
if #list == 1 then
local s = list[1]
return { type = "color", color = { s[2], s[3], s[4], math.floor(s[5] * opacity + 0.5) } }
end
local function coord(k: string, default: string, ref: number): number
local v = gattr(g, k, ctx) or default
local pct = string.match(v, "^%s*([%d.eE+-]+)%s*%%%s*$")
if pct then
local x = tonumber(pct) or 0
return if obb then x / 100 else x / 100 * ref
end
return Style.length(v, ref) or 0
end
local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2)
local p: any = {
type = if kind == "linearGradient" then "linear" else "radial",
units = if obb then "objectBoundingBox" else "userSpaceOnUse",
spread = gattr(g, "spreadMethod", ctx) or "pad",
stops = list,
opacity = opacity,
}
local t = gattr(g, "gradientTransform", ctx)
if t then
p.transform = Style.transform(t)
end
if p.type == "linear" then
p.x1, p.y1 = coord("x1", "0%", ctx.vw), coord("y1", "0%", ctx.vh)
p.x2, p.y2 = coord("x2", "100%", ctx.vw), coord("y2", "0%", ctx.vh)
else
p.cx, p.cy = coord("cx", "50%", ctx.vw), coord("cy", "50%", ctx.vh)
p.r = coord("r", "50%", diag)
p.fx = if gattr(g, "fx", ctx) then coord("fx", "50%", ctx.vw) else p.cx
p.fy = if gattr(g, "fy", ctx) then coord("fy", "50%", ctx.vh) else p.cy
p.fr = coord("fr", "0%", diag)
end
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
end
local id = string.match(value, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)%s*(.*)$")
if id then
local fallback = string.match(value, "%)%s*(.-)%s*$")
local g = ctx.ids[id]
if g and (local_(g) == "linearGradient" or local_(g) == "radialGradient") then
local p = gradient(g, opacity, ctx)
return if p == "none" then nil else p
end
if g and local_(g) == "pattern" then
ctx.unsupported.pattern = (ctx.unsupported.pattern or 0) + 1
end
if fallback and fallback ~= "" then
return paint(fallback, opacity, st, ctx)
end
return nil
end
local c = Style.color(value, Style.color(st.color or "black") :: any)
if c == nil or c == "none" then
return nil
end
return { type = "color", color = { c[1], c[2], c[3], math.floor(c[4] * opacity + 0.5) } }
end
-- ------------------------------------------------------------------------------------------------ shapes
local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cmd }?
local kind = local_(n)
local vw, vh = ctx.vw, ctx.vh
local diag = math.sqrt((vw * vw + vh * vh) / 2)
if kind == "path" then
local d = attr(n, "d")
if d == nil then
return nil
end
local cmds = PathData.parse(d)
return cmds
elseif kind == "rect" then
local x, y = len(attr(n, "x"), vw, st, 0) :: number, len(attr(n, "y"), vh, st, 0) :: number
local w, h = len(attr(n, "width"), vw, st, 0) :: number, len(attr(n, "height"), vh, st, 0) :: number
if w <= 0 or h <= 0 then
return nil
end
local rx: number?, ry: number? = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st)
if rx and rx < 0 then
rx = nil
end
if ry and ry < 0 then
ry = nil
end
rx = rx or ry or 0
ry = ry or rx
local rx: number, ry: number = math.min(rx :: number, w / 2), math.min(ry :: number, h / 2)
if rx <= 0 or ry <= 0 then
return { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } :: { PathData.Cmd }
end
local out: { PathData.Cmd } = { { op = "M", x + rx, y }, { op = "L", x + w - rx, y } }
PathData.arc(x + w - rx, y, rx, ry, 0, false, true, x + w, y + ry, out)
table.insert(out, { op = "L", x + w, y + h - ry })
PathData.arc(x + w, y + h - ry, rx, ry, 0, false, true, x + w - rx, y + h, out)
table.insert(out, { op = "L", x + rx, y + h })
PathData.arc(x + rx, y + h, rx, ry, 0, false, true, x, y + h - ry, out)
table.insert(out, { op = "L", x, y + ry })
PathData.arc(x, y + ry, rx, ry, 0, false, true, x + rx, y, out)
table.insert(out, { op = "Z" } :: PathData.Cmd)
return out
elseif kind == "circle" or kind == "ellipse" then
local cx, cy = len(attr(n, "cx"), vw, st, 0) :: number, len(attr(n, "cy"), vh, st, 0) :: number
local rx, ry
if kind == "circle" then
rx = len(attr(n, "r"), diag, st, 0) :: number
ry = rx
else
rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st)
rx = rx or ry or 0
ry = ry or rx
end
if (rx :: number) <= 0 or (ry :: number) <= 0 then
return nil
end
local out: { PathData.Cmd } = { { op = "M", cx + rx, cy } }
PathData.arc(cx + rx, cy, rx, ry, 0, false, true, cx, cy + ry, out)
PathData.arc(cx, cy + ry, rx, ry, 0, false, true, cx - rx, cy, out)
PathData.arc(cx - rx, cy, rx, ry, 0, false, true, cx, cy - ry, out)
PathData.arc(cx, cy - ry, rx, ry, 0, false, true, cx + rx, cy, out)
table.insert(out, { op = "Z" } :: PathData.Cmd)
return out
elseif kind == "line" then
local x1, y1 = len(attr(n, "x1"), vw, st, 0) :: number, len(attr(n, "y1"), vh, st, 0) :: number
local x2, y2 = len(attr(n, "x2"), vw, st, 0) :: number, len(attr(n, "y2"), vh, st, 0) :: number
return { { op = "M", x1, y1 }, { op = "L", x2, y2 } } :: { PathData.Cmd }
elseif kind == "polyline" or kind == "polygon" then
local v = Style.numbers(attr(n, "points"))
if #v < 4 then
return nil
end
local out: { PathData.Cmd } = { { op = "M", v[1], v[2] } }
for i = 3, #v - 1, 2 do
table.insert(out, { op = "L", v[i], v[i + 1] })
end
if kind == "polygon" then
table.insert(out, { op = "Z" } :: PathData.Cmd)
end
return out
end
return nil
end
-- ------------------------------------------------------------------------------------------------ clip paths
local function transformOf(n: Node): M
local t = attr(n, "transform")
if t then
return Style.transform(t) or IDENTITY
end
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
return nil
end
local base = mul(ctm, transformOf(cp))
if attr(cp, "clipPathUnits") == "objectBoundingBox" then
if not bbox then
return nil
end
base = mul(base, { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] })
end
local cpStyle = computed(st, cp, ctx)
local paths = {}
local function add(n: Node, parentStyle: { [string]: string }, m: M, depth: number)
if depth > 8 then
return
end
local s = computed(parentStyle, n, ctx)
if s.display == "none" or s.visibility == "hidden" then
return
end
local k = local_(n)
local tm = mul(m, transformOf(n))
if SHAPES[k] then
local cmds = shape(n, s, ctx)
if cmds and #cmds > 0 then
table.insert(paths, { d = cmds, transform = tm, rule = s["clip-rule"] or "nonzero" })
end
elseif k == "use" then
local h = refId(href(n))
local target = if h then ctx.ids[h] else nil
if target then
local x, y = len(attr(n, "x"), ctx.vw, s, 0) :: number, len(attr(n, "y"), ctx.vh, s, 0) :: number
add(target, s, mul(tm, { 1, 0, 0, 1, x, y }), depth + 1)
end
end
end
for _, c in Xml.children(cp) do
add(c, cpStyle, base, 0)
end
table.insert(ctx.clips, { paths = paths })
return #ctx.clips
end
-- ------------------------------------------------------------------------------------------------ the walk
local walk: (n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) -> ()
local function bboxOf(cmds: { PathData.Cmd }): { number }?
local x0, y0, x1, y1 = PathData.bounds(cmds)
if not x0 then
return nil
end
return { x0 :: number, y0 :: number, x1 :: number, y1 :: number }
end
local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx)
if st.visibility == "hidden" or st.visibility == "collapse" then
return
end
local cmds = shape(n, st, ctx)
if not cmds or #cmds == 0 then
return
end
local tm = mul(ctm, transformOf(n))
local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1)
local fill = paint(st.fill, math.clamp(tonumber(st["fill-opacity"]) or 1, 0, 1), st, ctx)
local stroke = paint(st.stroke, math.clamp(tonumber(st["stroke-opacity"]) or 1, 0, 1), st, ctx)
local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2)
local sw = len(st["stroke-width"], diag, st, 1) :: number
if sw <= 0 then
stroke = nil
end
if fill == nil and stroke == nil then
return
end
if local_(n) == "line" then
fill = nil -- a line has no inside
end
local clipRef = refId(st["clip-path"])
local clipId: number? = nil
if clipRef then
clipId = clip(clipRef, tm, bboxOf(cmds), st, ctx)
if clipId == nil and ctx.ids[clipRef] then
return -- a broken clip reference (bad units): nothing shows
end
end
-- opacity on a shape with both a fill and a stroke: a group, so the overlap is not counted twice
local g = group
if opacity < 1 and fill and stroke then
table.insert(ctx.groups, { opacity = opacity, parent = group })
g = #ctx.groups
opacity = 1
end
local p: any = {
d = cmds,
fill = fill,
fillRule = if st["fill-rule"] == "evenodd" then "evenodd" else "nonzero",
stroke = stroke,
strokeWidth = sw,
transform = tm,
opacity = opacity,
group = g,
clip = clipId,
id = attr(n, "id"),
}
if stroke then
p.strokeLineJoin = st["stroke-linejoin"]
p.strokeLineCap = st["stroke-linecap"]
p.strokeMiterLimit = tonumber(st["stroke-miterlimit"]) or 4
local dash = st["stroke-dasharray"]
if dash and dash ~= "none" then
local list = {}
local ok = true
for part in string.gmatch(dash, "[^,%s]+") do
local v = len(part, diag, st)
if v == nil or v < 0 then
ok = false
end
table.insert(list, v or 0)
end
local sum = 0
for _, v in list do
sum += v
end
if ok and sum > 0 then
if #list % 2 == 1 then
table.move(list, 1, #list, #list + 1, list)
end
p.strokeDashArray = list
p.strokeDashOffset = len(st["stroke-dashoffset"], diag, st, 0)
end
end
end
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 }
end
local sx, sy = w / vb[3], h / vb[4]
local align, mode = "xmidymid", "meet"
if par then
local a, m = string.match(string.lower(par), "^%s*([%w]+)%s*(%a*)")
if a == "defer" then
a, m = string.match(string.lower(par), "^%s*defer%s+([%w]+)%s*(%a*)")
end
align = a or align
if m and m ~= "" then
mode = m
end
end
if align == "none" then
return { sx, 0, 0, sy, x - vb[1] * sx, y - vb[2] * sy }
end
local s = if mode == "slice" then math.max(sx, sy) else math.min(sx, sy)
local tx, ty = x - vb[1] * s, y - vb[2] * s
local ax, ay = string.match(align, "^x(%a%a%a)y(%a%a%a)$")
if ax == "mid" then
tx += (w - vb[3] * s) / 2
elseif ax == "max" then
tx += w - vb[3] * s
end
if ay == "mid" then
ty += (h - vb[4] * s) / 2
elseif ay == "max" then
ty += h - vb[4] * s
end
return { s, 0, 0, s, tx, ty }
end
local function viewBox(n: Node): { number }?
local v = Style.numbers(attr(n, "viewBox"))
if #v == 4 and v[3] > 0 and v[4] > 0 then
return v
end
return nil
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
if opacity < 1 or clipRef then
local clipId: number? = nil
if clipRef then
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, {}, {}
for _, c in children or Xml.children(n) do
walk(c, st, IDENTITY, nil, ctx)
end
ctx.vector, ctx.groups, ctx.clips = saveV, saveG, saveC
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
for _, p in scratch.paths do
local b = bboxOf(p.d)
if b then
local m = p.transform or IDENTITY
for _, corner in { { b[1], b[2] }, { b[3], b[2] }, { b[1], b[4] }, { b[3], b[4] } } do
local px = m[1] * corner[1] + m[3] * corner[2] + m[5]
local py = m[2] * corner[1] + m[4] * corner[2] + m[6]
x0, y0, x1, y1 = math.min(x0, px), math.min(y0, py), math.max(x1, px), math.max(y1, py)
end
end
end
if x0 <= x1 then
bbox = { x0, y0, x1, y1 }
end
end
clipId = clip(clipRef, ctm, bbox, st, ctx)
if clipId == nil and cp then
return
end
end
table.insert(ctx.groups, { opacity = opacity, parent = group, clip = clipId })
g = #ctx.groups
end
if local_(n) == "switch" then
-- the first child that renders (conditional attributes are not evaluated)
for _, c in children or Xml.children(n) do
if UNSUPPORTED[local_(c)] == nil then
walk(c, st, ctm, g, ctx)
return
end
end
return
end
for _, c in children or Xml.children(n) do
walk(c, st, ctm, g, ctx)
end
end
-- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own
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
return group
end
local rect = { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } }
table.insert(ctx.clips, { paths = { { d = rect, transform = m, rule = "nonzero" } } })
table.insert(ctx.groups, { opacity = 1, parent = group, clip = #ctx.clips })
return #ctx.groups
end
walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx)
if ctx.depth > 200 then
return
end
local kind = local_(n)
if kind == "defs" or kind == "clipPath" or kind == "linearGradient" or kind == "radialGradient" or kind == "symbol" or kind == "style" or kind == "title" or kind == "desc" or kind == "metadata" then
return
end
local st = computed(parentStyle, n, ctx)
if st.display == "none" then
return
end
if UNSUPPORTED[kind] then
ctx.unsupported[kind] = (ctx.unsupported[kind] or 0) + 1
return
end
ctx.depth += 1
if CONTAINERS[kind] then
container(n, st, mul(ctm, transformOf(n)), group, ctx)
elseif SHAPES[kind] then
emitShape(n, st, ctm, group, ctx)
elseif kind == "use" then
local h = refId(href(n))
local target = if h then ctx.ids[h] else nil
if target and ctx.useDepth < 16 then
ctx.useDepth += 1
local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number
local m = mul(mul(ctm, transformOf(n)), { 1, 0, 0, 1, x, y })
local tk = local_(target)
if tk == "symbol" or tk == "svg" then
local w = len(attr(n, "width") or attr(target, "width") or "100%", ctx.vw, st, ctx.vw) :: number
local h2 = len(attr(n, "height") or attr(target, "height") or "100%", ctx.vh, st, ctx.vh) :: number
local vb = viewBox(target)
local inner = mul(m, Parse.viewTransform(vb, attr(target, "preserveAspectRatio"), 0, 0, w, h2))
local saveW, saveH = ctx.vw, ctx.vh
if vb then
ctx.vw, ctx.vh = vb[3], vb[4]
end
local tst = computed(st, target, ctx)
-- the use element's own opacity applies to the symbol's content too
local uo = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1)
if uo < 1 then
tst.opacity = tostring(uo * math.clamp(tonumber(tst.opacity or "1") or 1, 0, 1))
end
if tst["clip-path"] == nil then
tst["clip-path"] = st["clip-path"]
end
-- the symbol's children as a group of the use element, clipped to its viewport
local vg = viewportGroup(target, m, 0, 0, w, h2, group, ctx)
container(n, tst, mul(inner, transformOf(target)), vg, ctx, Xml.children(target))
ctx.vw, ctx.vh = saveW, saveH
else
-- the referenced element as if it were the use element's only child
container(n, st, m, group, ctx, { target })
end
ctx.useDepth -= 1
end
elseif kind == "svg" then
local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number
local w = len(attr(n, "width") or "100%", ctx.vw, st, ctx.vw) :: number
local h = len(attr(n, "height") or "100%", ctx.vh, st, ctx.vh) :: number
local vb = viewBox(n)
local m = mul(ctm, Parse.viewTransform(vb, attr(n, "preserveAspectRatio"), x, y, w, h))
local saveW, saveH = ctx.vw, ctx.vh
if vb then
ctx.vw, ctx.vh = vb[3], vb[4]
else
ctx.vw, ctx.vh = w, h
end
container(n, st, m, viewportGroup(n, ctm, x, y, w, h, group, ctx), ctx)
ctx.vw, ctx.vh = saveW, saveH
end
ctx.depth -= 1
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
return nil, "the root element is not <svg>"
end
local ids: { [string]: Node } = {}
local rules: { Style.Rule } = {}
local count = 0
local function index(n: Node)
count += 1
if count > 1000000 then
return
end
local id = attr(n, "id")
if id and ids[id] == nil then
ids[id] = n
end
if local_(n) == "style" then
Style.css(Xml.text(n), rules)
end
for _, c in Xml.children(n) do
index(c)
end
end
index(root)
local vb = viewBox(root)
local w = Style.length(attr(root, "width") or "100%", if vb then vb[3] else 100) or 100
local h = Style.length(attr(root, "height") or "100%", if vb then vb[4] else 100) or 100
if w <= 0 or h <= 0 then
w, h = 100, 100
end
local v = Types.Vector.new(w, h)
v.viewBox = vb or { 0, 0, w, h }
local ctx: Ctx = {
ids = ids,
rules = rules,
vector = v,
groups = {},
clips = {},
unsupported = {},
vw = v.viewBox[3],
vh = v.viewBox[4],
depth = 0,
useDepth = 0,
}
local st = computed(INHERITED, root, ctx)
container(root, st, IDENTITY, nil, ctx)
v.meta.preserveAspectRatio = attr(root, "preserveAspectRatio")
v.meta.groups = ctx.groups
v.meta.clips = ctx.clips
if next(ctx.unsupported) then
v.meta.unsupported = ctx.unsupported
end
return v, nil
end
return Parse
+377
View File
@@ -0,0 +1,377 @@
--!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).
local PathData = {}
export type Cmd = { op: string, [number]: number }
local byte, sub, find = string.byte, string.sub, string.find
local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math.sin, math.atan2, math.ceil, math.pi
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
end
rx, ry = abs(rx), abs(ry)
if rx == 0 or ry == 0 then
table.insert(out, { op = "L", x2, y2 })
return
end
local phi = phiDeg % 360 * pi / 180
local cp, sp = cos(phi), sin(phi)
local dx, dy = (x1 - x2) / 2, (y1 - y2) / 2
local x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy
local lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry)
if lambda > 1 then
local s = sqrt(lambda)
rx, ry = rx * s, ry * s
end
local num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
local den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
local coef = if den == 0 then 0 else sqrt(math.max(0, num / den))
if fa == fs then
coef = -coef
end
local cxp, cyp = coef * rx * y1p / ry, -coef * ry * x1p / rx
local cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2
local function angle(ux: number, uy: number, vx: number, vy: number): number
return atan2(ux * vy - uy * vx, ux * vx + uy * vy)
end
local ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry
local vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry
local t1 = angle(1, 0, ux, uy)
local dt = angle(ux, uy, vx, vy)
if not fs and dt > 0 then
dt -= 2 * pi
elseif fs and dt < 0 then
dt += 2 * pi
end
local n = math.max(1, ceil(abs(dt) / (pi / 2) - 1e-9))
local step = dt / n
local k = 4 / 3 * math.tan(step / 4)
local px, py = x1, y1
for i = 1, n do
local a0 = t1 + (i - 1) * step
local a1 = t1 + i * step
local c0, s0, c1, s1 = cos(a0), sin(a0), cos(a1), sin(a1)
-- the unit-circle segment's control points, scaled by the radii, rotated by phi, moved to the centre
local e1x, e1y = c0 - k * s0, s0 + k * c0
local e2x, e2y = c1 + k * s1, s1 - k * c1
local ex, ey = c1, s1
local function map(x: number, y: number): (number, number)
x, y = x * rx, y * ry
return cp * x - sp * y + cx, sp * x + cp * y + cy
end
local ax, ay = map(e1x, e1y)
local bx, by = map(e2x, e2y)
local qx, qy = map(ex, ey)
if i == n then
qx, qy = x2, y2
end
table.insert(out, { op = "C", ax, ay, bx, by, qx, qy })
px, py = qx, qy
end
local _ = px + py
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 cmd: string? = nil
local rel = false
local nums: { number } = table.create(7) :: { number }
local function ws()
while i <= n do
local c = byte(d, i)
if c == 32 or c == 9 or c == 10 or c == 13 or c == 12 then
i += 1
else
break
end
end
end
local function comma()
ws()
if i <= n and byte(d, i) == 44 then
i += 1
ws()
end
end
local function digits(): boolean
local any = false
while i <= n do
local c = byte(d, i)
if c >= 48 and c <= 57 then
i += 1
any = true
else
break
end
end
return any
end
-- an SVG number: sign? (digits ("." digits?)? | "." digits) exponent?; "1.5.5" is 1.5 then .5
local function number(): number?
ws()
local s = i
local c = byte(d, i)
if c == 43 or c == 45 then
i += 1
end
local whole = digits()
local frac = false
if i <= n and byte(d, i) == 46 then
i += 1
frac = digits()
end
if not whole and not frac then
i = s
return nil
end
c = byte(d, i)
if c == 101 or c == 69 then
local save = i
i += 1
c = byte(d, i)
if c == 43 or c == 45 then
i += 1
end
if not digits() then
i = save
end
end
return tonumber(sub(d, s, i - 1))
end
local function flag(): number?
ws()
local c = byte(d, i)
if c == 48 or c == 49 then
i += 1
return c - 48
end
return nil
end
while true do
ws()
if i > n then
break
end
local c = sub(d, i, i)
local up = string.upper(c)
if ARGS[up] ~= nil and find(c, "%a") then
cmd = up
rel = c ~= up
i += 1
if up == "Z" then
table.insert(out, { op = "Z" } :: Cmd)
cx, cy = sx, sy
last = "Z"
cmd = nil
continue
end
elseif cmd == nil then
return out, false
end
local c2 = cmd :: string
local na = ARGS[c2]
for k = 1, na do
local v = if c2 == "A" and (k == 4 or k == 5) then flag() else number()
if v == nil then
return out, false
end
nums[k] = v
if k < na then
comma()
end
end
comma()
local ox, oy = if rel then cx else 0, if rel then cy else 0
if c2 == "M" then
cx, cy = nums[1] + ox, nums[2] + oy
sx, sy = cx, cy
table.insert(out, { op = "M", cx, cy })
cmd = "L" -- further pairs are line-tos
elseif c2 == "L" then
cx, cy = nums[1] + ox, nums[2] + oy
table.insert(out, { op = "L", cx, cy })
elseif c2 == "H" then
cx = nums[1] + ox
table.insert(out, { op = "L", cx, cy })
elseif c2 == "V" then
cy = nums[1] + (if rel then cy else 0)
table.insert(out, { op = "L", cx, cy })
elseif c2 == "C" then
local x1, y1, x2, y2 = nums[1] + ox, nums[2] + oy, nums[3] + ox, nums[4] + oy
cx, cy = nums[5] + ox, nums[6] + oy
table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy })
lcx, lcy = x2, y2
elseif c2 == "S" then
local x1, y1 = cx, cy
if last == "C" or last == "S" then
x1, y1 = 2 * cx - lcx, 2 * cy - lcy
end
local x2, y2 = nums[1] + ox, nums[2] + oy
cx, cy = nums[3] + ox, nums[4] + oy
table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy })
lcx, lcy = x2, y2
elseif c2 == "Q" then
local x1, y1 = nums[1] + ox, nums[2] + oy
cx, cy = nums[3] + ox, nums[4] + oy
table.insert(out, { op = "Q", x1, y1, cx, cy })
lcx, lcy = x1, y1
elseif c2 == "T" then
local x1, y1 = cx, cy
if last == "Q" or last == "T" then
x1, y1 = 2 * cx - lcx, 2 * cy - lcy
end
cx, cy = nums[1] + ox, nums[2] + oy
table.insert(out, { op = "Q", x1, y1, cx, cy })
lcx, lcy = x1, y1
elseif c2 == "A" then
local x2, y2 = nums[6] + ox, nums[7] + oy
arc(cx, cy, nums[1], nums[2], nums[3], nums[4] ~= 0, nums[5] ~= 0, x2, y2, out)
cx, cy = x2, y2
end
last = if c2 == "M" then "M" else c2
end
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
local p1 = if axis == 1 then ax else ay
local p2 = if axis == 1 then bx else by
local p3 = if axis == 1 then ex else ey
local a = -p0 + 3 * p1 - 3 * p2 + p3
local b = 2 * (p0 - 2 * p1 + p2)
local cc = p1 - p0
local ts = {}
if abs(a) < 1e-12 then
if abs(b) > 1e-12 then
table.insert(ts, -cc / b)
end
else
local disc = b * b - 4 * a * cc
if disc >= 0 then
local s = sqrt(disc)
table.insert(ts, (-b + s) / (2 * a))
table.insert(ts, (-b - s) / (2 * a))
end
end
for _, t in ts do
if t > 0 and t < 1 then
local mt = 1 - t
local v = mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3
if axis == 1 then
x0, x1 = math.min(x0, v), math.max(x1, v)
else
y0, y1 = math.min(y0, v), math.max(y1, v)
end
end
end
end
px, py = ex, ey
elseif op == "Q" then
local ax, ay, ex, ey = c[1], c[2], c[3], c[4]
for axis = 1, 2 do
local p0 = if axis == 1 then px else py
local p1 = if axis == 1 then ax else ay
local p2 = if axis == 1 then ex else ey
local den = p0 - 2 * p1 + p2
if abs(den) > 1e-12 then
local t = (p0 - p1) / den
if t > 0 and t < 1 then
local mt = 1 - t
local v = mt * mt * p0 + 2 * mt * t * p1 + t * t * p2
if axis == 1 then
x0, x1 = math.min(x0, v), math.max(x1, v)
else
y0, y1 = math.min(y0, v), math.max(y1, v)
end
end
end
end
px, py = ex, ey
elseif op == "M" or op == "L" then
px, py = c[1], c[2]
end
if op ~= "Z" then
x0, x1 = math.min(x0, px), math.max(x1, px)
y0, y1 = math.min(y0, py), math.max(y1, py)
end
end
if x0 > x1 then
return nil, nil, nil, nil
end
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"
end
local r = math.floor(v * 10000 + 0.5) / 10000
if r == math.floor(r) and abs(r) < 1e15 then
return string.format("%d", r)
end
local s = string.format("%.4f", r)
s = string.gsub(s, "0+$", "")
return s
end
PathData.num = num
-- serialize(cmds) -> path data text
function PathData.serialize(cmds: { Cmd }): string
local out = {}
for _, c in cmds do
local k = ARGS[c.op]
if k ~= nil then
local parts = { c.op }
local cnt = if c.op == "C" then 6 elseif c.op == "Q" then 4 elseif c.op == "Z" then 0 else 2
for j = 1, cnt do
table.insert(parts, num(tonumber(c[j]) or 0))
end
table.insert(out, table.concat(parts, " "))
end
end
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)
for i, c in cmds do
local r: any = { op = RASTER[c.op] or "close" }
for j = 1, #c do
r[j] = c[j]
end
out[i] = r
end
return out
end
return PathData
+427
View File
@@ -0,0 +1,427 @@
--!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.
local Types = require("@rosetta/Types")
local Raster = require("@rosetta/codecs/image/Raster")
local Blend = require("@rosetta/codecs/image/Blend")
local PathData = require("@rosetta/vector/svg/PathData")
local Parse = require("@rosetta/vector/svg/Parse")
local Render = {}
type M = { number }
local function mul(m: M, n: M): M
return Raster.multiply(m, n)
end
-- ------------------------------------------------------------------------------------------------ gradients
local function stopColor(stops: { { number } }, t: number): (number, number, number, number)
local n = #stops
if t <= stops[1][1] then
local s = stops[1]
return s[2], s[3], s[4], s[5]
end
if t >= stops[n][1] then
local s = stops[n]
return s[2], s[3], s[4], s[5]
end
for i = 2, n do
local b = stops[i]
if t <= b[1] then
local a = stops[i - 1]
local span = b[1] - a[1]
local f = if span > 0 then (t - a[1]) / span else 1
return a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f, a[4] + (b[4] - a[4]) * f, a[5] + (b[5] - a[5]) * f
end
end
local s = stops[n]
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
return nil
end
local g: M = { 1, 0, 0, 1, 0, 0 }
if p.units ~= "userSpaceOnUse" then
if not bbox or bbox[3] - bbox[1] <= 0 or bbox[4] - bbox[2] <= 0 then
return nil -- a zero-size box: the gradient is not rendered
end
g = { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] }
end
if type(p.transform) == "table" then
g = mul(g, p.transform)
end
local inv = Raster.invert(mul(device, g))
if not inv then
return nil
end
local a, b, c, d, e, f = inv[1], inv[2], inv[3], inv[4], inv[5], inv[6]
local spread = p.spread
local opacity = tonumber(p.opacity) or 1
local function wrap(t: number): number
if spread == "repeat" then
return t - math.floor(t)
elseif spread == "reflect" then
local r = t % 2
return if r > 1 then 2 - r else r
end
return t
end
if p.type == "linear" then
local x1, y1, x2, y2 = p.x1 or 0, p.y1 or 0, p.x2 or 1, p.y2 or 0
local dx, dy = x2 - x1, y2 - y1
local dd = dx * dx + dy * dy
if dd == 0 then
local r, gg, bb, aa = stopColor(stops, 1)
return function(): (number, number, number, number)
return r, gg, bb, aa * opacity
end
end
return function(x: number, y: number): (number, number, number, number)
local gx, gy = a * x + c * y + e, b * x + d * y + f
local t = wrap(((gx - x1) * dx + (gy - y1) * dy) / dd)
local r, gg, bb, aa = stopColor(stops, t)
return r, gg, bb, aa * opacity
end
end
local cx, cy, r = p.cx or 0.5, p.cy or 0.5, p.r or 0.5
local fx, fy = p.fx or cx, p.fy or cy
if r <= 0 then
local rr, gg, bb, aa = stopColor(stops, 1)
return function(): (number, number, number, number)
return rr, gg, bb, aa * opacity
end
end
-- SVG 1.1: a focal point outside the circle moves onto it
local fdx, fdy = fx - cx, fy - cy
local fd = math.sqrt(fdx * fdx + fdy * fdy)
if fd > r * 0.999 then
local k = r * 0.999 / fd
fx, fy = cx + fdx * k, cy + fdy * k
end
return function(x: number, y: number): (number, number, number, number)
local gx, gy = a * x + c * y + e, b * x + d * y + f
local dx, dy = gx - fx, gy - fy
local t
if dx == 0 and dy == 0 then
t = 0
else
-- the ray from the focus through the point meets the circle at s: t = 1 / s
local ox, oy = fx - cx, fy - cy
local qa = dx * dx + dy * dy
local qb = 2 * (dx * ox + dy * oy)
local qc = ox * ox + oy * oy - r * r
local disc = qb * qb - 4 * qa * qc
local s = (-qb + math.sqrt(math.max(0, disc))) / (2 * qa)
t = if s > 0 then 1 / s else 1
end
local rr, gg, bb, aa = stopColor(stops, wrap(t))
return rr, gg, bb, aa * opacity
end
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
for _, c in cmds do
if c.op == "M" then
cur = { c }
table.insert(out, { cmds = cur, closed = false })
elseif c.op == "Z" then
if cur then
out[#out].closed = true
-- a new subpath starts at the same point if more segments follow
local first = (cur :: { any })[1]
cur = { { op = "M", first[1], first[2] } }
table.insert(out, { cmds = cur, closed = false })
end
elseif cur then
table.insert(cur, c)
end
end
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
for _, c in cmds do
local op = c.op
if op == "M" or op == "L" then
px, py = c[1], c[2]
table.insert(pts, px)
table.insert(pts, py)
elseif op == "Q" or op == "C" then
local len = 0
local lx, ly = px, py
for k = 1, #c - 1, 2 do
len += math.sqrt((c[k] - lx) ^ 2 + (c[k + 1] - ly) ^ 2)
lx, ly = c[k], c[k + 1]
end
local steps = math.clamp(math.ceil(math.sqrt(len / math.max(tol, 1e-4))), 1, 512)
for i = 1, steps do
local t = i / steps
local mt = 1 - t
local x, y
if op == "Q" then
x = mt * mt * px + 2 * mt * t * c[1] + t * t * c[3]
y = mt * mt * py + 2 * mt * t * c[2] + t * t * c[4]
else
x = mt * mt * mt * px + 3 * mt * mt * t * c[1] + 3 * mt * t * t * c[3] + t * t * t * c[5]
y = mt * mt * mt * py + 3 * mt * mt * t * c[2] + 3 * mt * t * t * c[4] + t * t * t * c[6]
end
table.insert(pts, x)
table.insert(pts, y)
end
px, py = c[#c - 1], c[#c]
end
end
return pts
end
local function dashed(cmds: { any }, dashes: { number }, offset: number, tol: number): { any }
local out = {}
local total = 0
for _, v in dashes do
total += v
end
if total <= 0 then
return cmds
end
for _, sp in subpaths(cmds) do
if #sp.cmds < 2 then
continue
end
local pts = polyline(sp.cmds, tol)
if #pts < 4 then
continue
end
if sp.closed then
table.insert(pts, pts[1])
table.insert(pts, pts[2])
end
-- dash state at the start (offset wraps through the pattern)
local idx, left = 1, 0
local o = offset % total
if o < 0 then
o += total
end
while o > 0 do
if o >= dashes[idx] then
o -= dashes[idx]
idx = idx % #dashes + 1
else
break
end
end
left = dashes[idx] - o
local on = idx % 2 == 1
local cur: { any }? = nil
if on then
cur = { { op = "M", pts[1], pts[2] } }
end
for i = 1, #pts - 3, 2 do
local x0, y0, x1, y1 = pts[i], pts[i + 1], pts[i + 2], pts[i + 3]
local seg = math.sqrt((x1 - x0) ^ 2 + (y1 - y0) ^ 2)
local pos = 0
local guard = 0
while seg - pos > left and guard < 100000 do
guard += 1
pos += left
local t = pos / seg
local x, y = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t
if on then
table.insert(cur :: { any }, { op = "L", x, y })
for _, c in cur :: { any } do
table.insert(out, c)
end
cur = nil
else
cur = { { op = "M", x, y } }
end
on = not on
idx = idx % #dashes + 1
left = dashes[idx]
end
left -= seg - pos
if on and cur then
table.insert(cur, { op = "L", x1, y1 })
end
end
if on and cur and #cur > 1 then
for _, c in cur do
table.insert(out, c)
end
end
end
return out
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)
}
-- 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)
local px = img.pixels
local n = w * h
local bg = o.background
if type(bg) == "table" then
local val = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216
for i = 0, n - 1 do
buffer.writeu32(px, i * 4, val)
end
end
local meta: any = if type(v.meta) == "table" then v.meta else {}
local view = Parse.viewTransform(v.viewBox, meta.preserveAspectRatio, 0, 0, w, h)
local groups: { any } = if type(meta.groups) == "table" then meta.groups else {}
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]
end
local c = clips[id]
if type(c) ~= "table" then
return nil
end
local mask = buffer.create(n)
for _, cp in (if type(c.paths) == "table" then c.paths else {}) do
local m = Raster.mask(PathData.toRaster(cp.d), { transform = mul(view, cp.transform or Raster.IDENTITY), rule = cp.rule, clip = { 0, 0, w, h }, tolerance = tol })
if m then
for y = 0, m.height - 1 do
for x = 0, m.width - 1 do
local cv = buffer.readu8(m.coverage, y * m.width + x)
if cv > 0 then
local i = (m.y + y) * w + m.x + x
local old = buffer.readu8(mask, i)
buffer.writeu8(mask, i, math.min(255, old + cv - math.floor(old * cv / 255 + 0.5)))
end
end
end
end
end
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 = {}
local guard = 0
while g ~= nil and guard < 256 do
table.insert(out, 1, g)
local gr = groups[g]
g = if type(gr) == "table" then gr.parent else nil
guard += 1
end
return out
end
local function pop()
local top = table.remove(stack) :: any
local below = stack[#stack].img
local gr = groups[top.id] or {}
local mask: any = nil
if gr.clip then
local cm = clipMask(gr.clip)
mask = if cm then { pixels = cm, width = w, height = h, x = 0, y = 0, default = 0 } else { default = 0 }
end
Blend.composite(below.pixels, w, h, top.img.pixels, w, h, 0, 0, math.clamp(tonumber(gr.opacity) or 1, 0, 1), "normal", { mask = mask })
end
local function draw(target: Types.Image, cmds: { any }, paint: any, device: M, rule: string?, opacity: number, bbox: { number }?)
local fill: any
if paint.type == "color" then
fill = paint.color
else
fill = gradientFn(paint, device, bbox)
if not fill then
return
end
end
Raster.fill(target, cmds, fill, { transform = device, rule = rule, opacity = opacity, tolerance = tol })
end
for _, p in v.paths do
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
keep += 1
end
while #stack > keep do
pop()
end
for k = keep, #want do
table.insert(stack, { id = want[k], img = Types.Image.new(w, h) })
end
local device = mul(view, p.transform or Raster.IDENTITY)
local target = stack[#stack].img
local clipMaskBuf: buffer? = nil
if p.clip then
clipMaskBuf = clipMask(p.clip)
if not clipMaskBuf then
continue
end
target = Types.Image.new(w, h)
end
local opacity = math.clamp(tonumber(p.opacity) or 1, 0, 1)
local rcmds = PathData.toRaster(p.d)
local bbox: { number }? = nil
if (p.fill and p.fill.type ~= "color") or (p.stroke and p.stroke.type ~= "color") then
local x0, y0, x1, y1 = PathData.bounds(p.d)
if x0 then
bbox = { x0 :: number, y0 :: number, x1 :: number, y1 :: number }
end
end
if type(p.fill) == "table" then
draw(target, rcmds, p.fill, device, p.fillRule, opacity, bbox)
end
if type(p.stroke) == "table" and (tonumber(p.strokeWidth) or 1) > 0 then
local scale = math.max(scaleOf(device), 1e-6)
local src = p.d
if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then
src = dashed(p.d, p.strokeDashArray, tonumber(p.strokeDashOffset) or 0, tol / scale)
end
local outline = Raster.stroke(PathData.toRaster(src), {
width = tonumber(p.strokeWidth) or 1,
join = p.strokeLineJoin,
cap = p.strokeLineCap,
miterLimit = p.strokeMiterLimit,
tolerance = tol / scale,
})
draw(target, outline, p.stroke, device, "nonzero", opacity, bbox)
end
if clipMaskBuf then
Blend.composite(stack[#stack].img.pixels, w, h, target.pixels, w, h, 0, 0, 1, "normal", { mask = { pixels = clipMaskBuf, width = w, height = h, x = 0, y = 0, default = 0 } })
end
end
while #stack > 1 do
pop()
end
return img
end
return Render
+381
View File
@@ -0,0 +1,381 @@
--!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.
local Raster = require("@rosetta/codecs/image/Raster")
local Style = {}
local NAMED: { [string]: number } = {
aliceblue = 0xf0f8ff, antiquewhite = 0xfaebd7, aqua = 0x00ffff, aquamarine = 0x7fffd4, azure = 0xf0ffff,
beige = 0xf5f5dc, bisque = 0xffe4c4, black = 0x000000, blanchedalmond = 0xffebcd, blue = 0x0000ff,
blueviolet = 0x8a2be2, brown = 0xa52a2a, burlywood = 0xdeb887, cadetblue = 0x5f9ea0, chartreuse = 0x7fff00,
chocolate = 0xd2691e, coral = 0xff7f50, cornflowerblue = 0x6495ed, cornsilk = 0xfff8dc, crimson = 0xdc143c,
cyan = 0x00ffff, darkblue = 0x00008b, darkcyan = 0x008b8b, darkgoldenrod = 0xb8860b, darkgray = 0xa9a9a9,
darkgreen = 0x006400, darkgrey = 0xa9a9a9, darkkhaki = 0xbdb76b, darkmagenta = 0x8b008b, darkolivegreen = 0x556b2f,
darkorange = 0xff8c00, darkorchid = 0x9932cc, darkred = 0x8b0000, darksalmon = 0xe9967a, darkseagreen = 0x8fbc8f,
darkslateblue = 0x483d8b, darkslategray = 0x2f4f4f, darkslategrey = 0x2f4f4f, darkturquoise = 0x00ced1,
darkviolet = 0x9400d3, deeppink = 0xff1493, deepskyblue = 0x00bfff, dimgray = 0x696969, dimgrey = 0x696969,
dodgerblue = 0x1e90ff, firebrick = 0xb22222, floralwhite = 0xfffaf0, forestgreen = 0x228b22, fuchsia = 0xff00ff,
gainsboro = 0xdcdcdc, ghostwhite = 0xf8f8ff, gold = 0xffd700, goldenrod = 0xdaa520, gray = 0x808080,
grey = 0x808080, green = 0x008000, greenyellow = 0xadff2f, honeydew = 0xf0fff0, hotpink = 0xff69b4,
indianred = 0xcd5c5c, indigo = 0x4b0082, ivory = 0xfffff0, khaki = 0xf0e68c, lavender = 0xe6e6fa,
lavenderblush = 0xfff0f5, lawngreen = 0x7cfc00, lemonchiffon = 0xfffacd, lightblue = 0xadd8e6, lightcoral = 0xf08080,
lightcyan = 0xe0ffff, lightgoldenrodyellow = 0xfafad2, lightgray = 0xd3d3d3, lightgreen = 0x90ee90,
lightgrey = 0xd3d3d3, lightpink = 0xffb6c1, lightsalmon = 0xffa07a, lightseagreen = 0x20b2aa,
lightskyblue = 0x87cefa, lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xb0c4de,
lightyellow = 0xffffe0, lime = 0x00ff00, limegreen = 0x32cd32, linen = 0xfaf0e6, magenta = 0xff00ff,
maroon = 0x800000, mediumaquamarine = 0x66cdaa, mediumblue = 0x0000cd, mediumorchid = 0xba55d3,
mediumpurple = 0x9370db, mediumseagreen = 0x3cb371, mediumslateblue = 0x7b68ee, mediumspringgreen = 0x00fa9a,
mediumturquoise = 0x48d1cc, mediumvioletred = 0xc71585, midnightblue = 0x191970, mintcream = 0xf5fffa,
mistyrose = 0xffe4e1, moccasin = 0xffe4b5, navajowhite = 0xffdead, navy = 0x000080, oldlace = 0xfdf5e6,
olive = 0x808000, olivedrab = 0x6b8e23, orange = 0xffa500, orangered = 0xff4500, orchid = 0xda70d6,
palegoldenrod = 0xeee8aa, palegreen = 0x98fb98, paleturquoise = 0xafeeee, palevioletred = 0xdb7093,
papayawhip = 0xffefd5, peachpuff = 0xffdab9, peru = 0xcd853f, pink = 0xffc0cb, plum = 0xdda0dd,
powderblue = 0xb0e0e6, purple = 0x800080, rebeccapurple = 0x663399, red = 0xff0000, rosybrown = 0xbc8f8f,
royalblue = 0x4169e1, saddlebrown = 0x8b4513, salmon = 0xfa8072, sandybrown = 0xf4a460, seagreen = 0x2e8b57,
seashell = 0xfff5ee, sienna = 0xa0522d, silver = 0xc0c0c0, skyblue = 0x87ceeb, slateblue = 0x6a5acd,
slategray = 0x708090, slategrey = 0x708090, snow = 0xfffafa, springgreen = 0x00ff7f, steelblue = 0x4682b4,
tan = 0xd2b48c, teal = 0x008080, thistle = 0xd8bfd8, tomato = 0xff6347, turquoise = 0x40e0d0, violet = 0xee82ee,
wheat = 0xf5deb3, white = 0xffffff, whitesmoke = 0xf5f5f5, yellow = 0xffff00, yellowgreen = 0x9acd32,
}
local function clamp255(v: number): number
return math.clamp(math.floor(v + 0.5), 0, 255)
end
local function hue(p: number, q: number, t: number): number
t %= 1
if t < 1 / 6 then
return p + (q - p) * 6 * t
elseif t < 1 / 2 then
return q
elseif t < 2 / 3 then
return p + (q - p) * (2 / 3 - t) * 6
end
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
return "none"
elseif s == "transparent" then
return { 0, 0, 0, 0 }
elseif s == "currentcolor" then
return current or { 0, 0, 0, 255 }
end
local hex = string.match(s, "^#(%x+)$")
if hex then
local n = #hex
if n == 3 or n == 4 then
local v = {}
for k = 1, n do
v[k] = (tonumber(string.sub(hex, k, k), 16) :: number) * 17
end
return { v[1], v[2], v[3], v[4] or 255 }
elseif n == 6 or n == 8 then
local v = {}
for k = 1, n // 2 do
v[k] = tonumber(string.sub(hex, k * 2 - 1, k * 2), 16) :: number
end
return { v[1], v[2], v[3], v[4] or 255 }
end
return nil
end
local fn, args = string.match(s, "^(%a+)%s*%((.*)%)$")
if fn then
local parts = {}
for p in string.gmatch(args :: string, "[^,%s/]+") do
table.insert(parts, p)
end
local function comp(p: string?, scale: number): number?
if p == nil then
return nil
end
local pct = string.match(p, "^([%d.eE+-]+)%%$")
if pct then
local v = tonumber(pct)
return if v then v / 100 * scale else nil
end
return tonumber(p)
end
local function alpha(p: string?): number
if p == nil then
return 255
end
local v = comp(p, 1)
return clamp255((v or 1) * 255)
end
if fn == "rgb" or fn == "rgba" then
local r, g, b = comp(parts[1], 255), comp(parts[2], 255), comp(parts[3], 255)
if not (r and g and b) then
return nil
end
return { clamp255(r :: number), clamp255(g :: number), clamp255(b :: number), alpha(parts[4]) }
elseif fn == "hsl" or fn == "hsla" then
local h = tonumber((string.gsub(parts[1] or "", "deg$", "")))
local sat, l = comp(parts[2], 1), comp(parts[3], 1)
if not (h and sat and l) then
return nil
end
local hh = (h :: number) / 360
local ss, ll = math.clamp(sat :: number, 0, 1), math.clamp(l :: number, 0, 1)
local q = if ll < 0.5 then ll * (1 + ss) else ll + ss - ll * ss
local p = 2 * ll - q
return { clamp255(hue(p, q, hh + 1 / 3) * 255), clamp255(hue(p, q, hh) * 255), clamp255(hue(p, q, hh - 1 / 3) * 255), alpha(parts[4]) }
end
return nil
end
local v = NAMED[s]
if v then
return { v // 65536, v // 256 % 256, v % 256, 255 }
end
return nil
end
-- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil
local function scan(s: string, i: number): (number?, number)
local n = #s
local st = i
local c = string.byte(s, i)
if c == 43 or c == 45 then
i += 1
end
local any = false
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
any = true
else
break
end
end
if i <= n and string.byte(s, i) == 46 then
i += 1
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
any = true
else
break
end
end
end
if not any then
return nil, st
end
c = string.byte(s, i)
if c == 101 or c == 69 then
local save = i
i += 1
c = string.byte(s, i)
if c == 43 or c == 45 then
i += 1
end
local e = false
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
e = true
else
break
end
end
if not e then
i = save
end
end
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
return nil
end
local t = string.match(s, "^%s*(.-)%s*$") :: string
local x, j = scan(t, 1)
if x == nil then
return nil
end
local u = string.lower(string.sub(t, j))
if u == "" then
return x
elseif u == "%" then
return x / 100 * (ref or 100)
elseif u == "em" then
return x * (fontSize or 16)
elseif u == "ex" then
return x * (fontSize or 16) / 2
end
local k = UNITS[u]
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
return out
end
local i, n = 1, #s
while i <= n do
local c = string.byte(s, i)
if c == 32 or c == 44 or c == 9 or c == 10 or c == 13 then
i += 1
else
local v, j = scan(s, i)
if v == nil then
break
end
table.insert(out, v)
i = j
end
end
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 }?
local m = { 1, 0, 0, 1, 0, 0 }
local rest = s
while true do
rest = string.gsub(rest, "^[%s,]+", "")
if rest == "" then
break
end
local name, args, after = string.match(rest, "^(%a+)%s*(%b())(.*)$")
if not name then
return nil
end
rest = after :: string
local v = Style.numbers(string.sub(args :: string, 2, -2))
local t: { number }
if name == "matrix" and #v == 6 then
t = v
elseif name == "translate" and (#v == 1 or #v == 2) then
t = { 1, 0, 0, 1, v[1], v[2] or 0 }
elseif name == "scale" and (#v == 1 or #v == 2) then
t = { v[1], 0, 0, v[2] or v[1], 0, 0 }
elseif name == "rotate" and (#v == 1 or #v == 3) then
local r = v[1] * math.pi / 180
local c, sn = math.cos(r), math.sin(r)
t = { c, sn, -sn, c, 0, 0 }
if #v == 3 then
t = mul(mul({ 1, 0, 0, 1, v[2], v[3] }, t), { 1, 0, 0, 1, -v[2], -v[3] })
end
elseif name == "skewX" and #v == 1 then
t = { 1, 0, math.tan(v[1] * math.pi / 180), 1, 0, 0 }
elseif name == "skewY" and #v == 1 then
t = { 1, math.tan(v[1] * math.pi / 180), 0, 1, 0, 0 }
else
return nil
end
m = mul(m, t)
end
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
local k, v = string.match(decl, "^%s*([%w-]+)%s*:%s*(.-)%s*$")
if k and v then
v = string.gsub(v :: string, "%s*!important$", "")
out[string.lower(k :: string)] = v :: string
end
end
return out
end
-- ------------------------------------------------------------------------------------------------ CSS
export type Selector = { tag: string?, id: string?, classes: { string }, specificity: number }
export type Rule = { selector: Selector, decls: { [string]: string }, order: number }
local function selector(s: string): Selector?
s = string.gsub(s, "^%s*(.-)%s*$", "%1")
if s == "" or string.find(s, "[%s>+~%[:]") then
return nil -- combinators, attribute and pseudo selectors: not supported
end
local sel: Selector = { classes = {}, specificity = 0 }
local tag = string.match(s, "^([%a_][%w_-]*)")
if tag then
sel.tag = tag
sel.specificity += 1
s = string.sub(s, #tag + 1)
elseif string.sub(s, 1, 1) == "*" then
s = string.sub(s, 2)
end
while s ~= "" do
local kind, name, rest = string.match(s, "^([.#])([%w_-]+)(.*)$")
if not kind then
return nil
end
if kind == "." then
table.insert(sel.classes, name :: string)
sel.specificity += 100
else
sel.id = name
sel.specificity += 10000
end
s = rest :: string
end
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, "/%*.-%*/", "")
text = string.gsub(text, "<!%-%-", "")
text = string.gsub(text, "%-%->", "")
-- drop @rules with blocks (@media { ... { } }) and simple ones (@import ...;)
local guard = 0
while guard < 100 do
guard += 1
local s, e = string.find(text, "@[%w-]+[^{;]*%b{}")
if not s then
break
end
text = string.sub(text, 1, s - 1) .. string.sub(text, (e :: number) + 1)
end
text = string.gsub(text, "@[%w-]+[^;{]*;", "")
for sels, body in string.gmatch(text, "([^{}]+)(%b{})") do
local decls = Style.declarations(string.sub(body :: string, 2, -2))
for one in string.gmatch(sels, "[^,]+") do
local sel = selector(one)
if sel then
table.insert(out, { selector = sel, decls = decls, order = #out + 1 })
end
end
end
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
end
if sel.id and sel.id ~= id then
return false
end
for _, c in sel.classes do
if not classes[c] then
return false
end
end
return true
end
return Style
+203
View File
@@ -0,0 +1,203 @@
--!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.
local Xml = require("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local PathData = require("@rosetta/vector/svg/PathData")
local Write = {}
local num = PathData.num
local function el(name: string, attrs: { { any } }, children: { any }?): any
local o = Types.object()
for _, kv in attrs do
if kv[2] ~= nil then
Types.set(o, kv[1], if type(kv[2]) == "number" then num(kv[2]) else tostring(kv[2]))
end
end
return Xml.element(name, o :: any, children)
end
local function hex(c: { number }): string
return string.format("#%02x%02x%02x", math.clamp(math.floor(c[1] or 0), 0, 255), math.clamp(math.floor(c[2] or 0), 0, 255), math.clamp(math.floor(c[3] or 0), 0, 255))
end
local function matrix(m: any): string?
if type(m) ~= "table" or #m < 6 then
return nil
end
if m[1] == 1 and m[2] == 0 and m[3] == 0 and m[4] == 1 then
if m[5] == 0 and m[6] == 0 then
return nil
end
return "translate(" .. num(m[5]) .. " " .. num(m[6]) .. ")"
end
local parts = {}
for k = 1, 6 do
parts[k] = num(tonumber(m[k]) or 0)
end
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"
end
local meta: any = if type(v.meta) == "table" then v.meta else {}
local groups: { any } = if type(meta.groups) == "table" then meta.groups else {}
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" } }
end
if p.type == "color" and type(p.color) == "table" then
local a = p.color[4] or 255
return { { which, hex(p.color) }, { which .. "-opacity", if a < 255 then num(a / 255) else nil } }
end
if p.type ~= "linear" and p.type ~= "radial" then
return { { which, "none" } }
end
gradients += 1
local id = "g" .. gradients
local kids = {}
for _, s in (if type(p.stops) == "table" then p.stops else {}) do
local a = s[5] or 255
table.insert(kids, el("stop", { { "offset", s[1] or 0 }, { "stop-color", hex({ s[2], s[3], s[4] }) }, { "stop-opacity", if a < 255 then num(a / 255) else nil } }))
end
local attrs: { { any } } = { { "id", id }, { "gradientUnits", if p.units == "userSpaceOnUse" then "userSpaceOnUse" else nil } }
if p.type == "linear" then
table.insert(attrs, { "x1", p.x1 or 0 })
table.insert(attrs, { "y1", p.y1 or 0 })
table.insert(attrs, { "x2", p.x2 or 1 })
table.insert(attrs, { "y2", p.y2 or 0 })
else
table.insert(attrs, { "cx", p.cx or 0.5 })
table.insert(attrs, { "cy", p.cy or 0.5 })
table.insert(attrs, { "r", p.r or 0.5 })
table.insert(attrs, { "fx", p.fx })
table.insert(attrs, { "fy", p.fy })
if p.fr and p.fr ~= 0 then
table.insert(attrs, { "fr", p.fr })
end
end
table.insert(attrs, { "spreadMethod", if p.spread and p.spread ~= "pad" then p.spread else nil })
table.insert(attrs, { "gradientTransform", matrix(p.transform) })
table.insert(defs, el(if p.type == "linear" then "linearGradient" else "radialGradient", attrs, kids))
local op = tonumber(p.opacity) or 1
return { { which, "url(#" .. id .. ")" }, { which .. "-opacity", if op < 1 then num(op) else nil } }
end
local clipIds: { [number]: string } = {}
local function clipRef(id: number?): string?
if id == nil or type(clips[id]) ~= "table" then
return nil
end
if clipIds[id] == nil then
local cid = "c" .. id
clipIds[id] = cid
local kids = {}
for _, cp in (if type(clips[id].paths) == "table" then clips[id].paths else {}) do
table.insert(kids, el("path", { { "d", PathData.serialize(cp.d or {}) }, { "transform", matrix(cp.transform) }, { "clip-rule", if cp.rule == "evenodd" then "evenodd" else nil } }))
end
table.insert(defs, el("clipPath", { { "id", cid } }, kids))
end
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 = {}
local guard = 0
while g ~= nil and guard < 256 do
table.insert(out, 1, g)
local gr = groups[g]
g = if type(gr) == "table" then gr.parent else nil
guard += 1
end
return out
end
for _, p in v.paths do
if type(p) ~= "table" or type(p.d) ~= "table" then
continue
end
local want = chain(p.group)
local keep = 1
while keep < #stack and stack[keep + 1].id == want[keep] do
keep += 1
end
while #stack > keep do
table.remove(stack)
end
for k = keep, #want do
local gr = groups[want[k]] or {}
local kids = {}
local op = tonumber(gr.opacity) or 1
table.insert(stack[#stack].kids, el("g", { { "opacity", if op < 1 then op else nil }, { "clip-path", clipRef(gr.clip) } }, kids))
table.insert(stack, { id = want[k], kids = kids })
end
local attrs: { { any } } = { { "id", p.id }, { "d", PathData.serialize(p.d) }, { "transform", matrix(p.transform) } }
for _, kv in paintAttrs(p.fill, "fill") do
table.insert(attrs, kv)
end
table.insert(attrs, { "fill-rule", if p.fillRule == "evenodd" then "evenodd" else nil })
for _, kv in paintAttrs(p.stroke, "stroke") do
if kv[2] ~= "none" then
table.insert(attrs, kv)
end
end
if type(p.stroke) == "table" then
local sw = tonumber(p.strokeWidth) or 1
table.insert(attrs, { "stroke-width", if sw ~= 1 then sw else nil })
table.insert(attrs, { "stroke-linejoin", if p.strokeLineJoin and p.strokeLineJoin ~= "miter" then p.strokeLineJoin else nil })
table.insert(attrs, { "stroke-linecap", if p.strokeLineCap and p.strokeLineCap ~= "butt" then p.strokeLineCap else nil })
local ml = tonumber(p.strokeMiterLimit)
table.insert(attrs, { "stroke-miterlimit", if ml and ml ~= 4 then ml else nil })
if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then
local parts = {}
for k, d in p.strokeDashArray do
parts[k] = num(tonumber(d) or 0)
end
table.insert(attrs, { "stroke-dasharray", table.concat(parts :: { string }, " ") })
local off = tonumber(p.strokeDashOffset)
table.insert(attrs, { "stroke-dashoffset", if off and off ~= 0 then off else nil })
end
end
local op = tonumber(p.opacity) or 1
table.insert(attrs, { "opacity", if op < 1 then op else nil })
local node = el("path", attrs)
local cr = clipRef(p.clip)
if cr then
node = el("g", { { "clip-path", cr } }, { node })
end
table.insert(stack[#stack].kids, node)
end
local children = {}
if #defs > 0 then
table.insert(children, el("defs", {}, defs))
end
for _, c in root do
table.insert(children, c)
end
local vb = v.viewBox
local vbText = if type(vb) == "table" and #vb == 4 then num(vb[1]) .. " " .. num(vb[2]) .. " " .. num(vb[3]) .. " " .. num(vb[4]) else nil
local svg = el("svg", {
{ "xmlns", "http://www.w3.org/2000/svg" },
{ "width", v.width },
{ "height", v.height },
{ "viewBox", vbText },
{ "preserveAspectRatio", meta.preserveAspectRatio },
}, children)
local s, err = Xml.encode(Xml.document(svg, { version = "1.0", encoding = "UTF-8" }), { indent = 1 })
if not s then
return nil, tostring(err)
end
return s .. "\n", nil
end
return Write
+94
View File
@@ -0,0 +1,94 @@
--!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.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Sniff = require("@rosetta/core/Sniff")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Xml = require("@rosetta/codecs/text/Xml")
local Parse = require("@rosetta/vector/svg/Parse")
local Render = require("@rosetta/vector/svg/Render")
local Write = require("@rosetta/vector/svg/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Svg = {
name = "svg",
category = "vector",
extensions = { "svg" },
mime = { "image/svg+xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "codecs/image/Raster", "codecs/image/Blend", "core/Sniff" },
caps = { decode = true, encode = true, rasterize = true, text = false },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
}
export type EncodeOptions = {}
export type RasterizeOptions = Render.Options
-- ------------------------------------------------------------------------------------------------ sniff
function Svg.sniff(r: Bytes.Reader): number
local h = Sniff.text(r, 4096)
if not string.match(h, "^%s*<") then
return 0
end
if string.find(h, "<svg[%s>:]") or string.find(h, "<%w+:svg[%s>]") then
return 0.95
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Svg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Vector?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 26
if r.limit - r.base > maxBytes then
return nil, Err.new(Err.LIMIT, "file is over the byte limit")
end
local doc, xerr = Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base))
if not doc then
return nil, xerr
end
local v, msg = Parse.document(doc)
if not v then
return nil, Err.new(Err.CORRUPT, msg or "bad SVG")
end
v.meta.source = { format = "svg" }
return v, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?)
local s, err = Write.vector(v)
if not s then
return nil, Err.new(Err.ARG, err or "bad Vector")
end
return buffer.fromstring(s), nil
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")
end
local W = math.ceil(w or v.width or 0)
local H = math.ceil(h or v.height or 0)
if W < 1 or H < 1 or W * H > 2 ^ 26 then
return nil, Err.new(Err.ARG, "bad raster size")
end
return Render.rasterize(v, W, H, opts), nil
end
return Svg
+156
View File
@@ -0,0 +1,156 @@
--!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.
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
local v = tonumber(tok)
if v == nil or v < 0 or v >= 4294967296 or v % 1 ~= 0 then
return nil, "bad gid " .. string.sub(tok, 1, 20)
end
table.insert(out, v)
end
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
return nil, err, nil
end
local bytes: buffer = raw
if compression == "zlib" then
local z, zerr = Deflate.zlib(bytes)
if not z then
return nil, "zlib: " .. tostring(zerr), nil
end
bytes = z
elseif compression == "gzip" then
local z, zerr = Deflate.gunzip(bytes)
if not z then
return nil, "gzip: " .. tostring(zerr), nil
end
bytes = z
elseif compression ~= nil and compression ~= "" then
return nil, "compression " .. compression .. " is not supported", true
end
local n = buffer.len(bytes) // 4
local out: { number } = table.create(n) :: { number }
for i = 0, n - 1 do
out[i + 1] = buffer.readu32(bytes, i * 4)
end
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
buffer.writeu32(b, (i - 1) * 4, g % 4294967296)
end
if compression == "zlib" then
local z = Deflate.zlibCompress(b, { level = level or 6 })
if not z then
return nil, "zlib failed"
end
b = z
elseif compression == "gzip" then
local z = Deflate.gzip(b, { level = level or 6 })
if not z then
return nil, "gzip failed"
end
b = z
elseif compression ~= nil and compression ~= "" then
return nil, "compression " .. compression .. " is not supported"
end
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
function Data.num(v: number): string
if v % 1 == 0 and math.abs(v) < 2 ^ 53 then
return string.format("%.0f", v)
end
local s = string.format("%.15g", v)
if tonumber(s) ~= v then
s = string.format("%.17g", v)
end
return s
end
-- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line)
function Data.csvText(gids: { number }, width: number): string
local rows = {}
local row = {}
for i, g in gids do
table.insert(row, Data.num(g))
if width > 0 and i % width == 0 then
table.insert(rows, table.concat(row, ","))
row = {}
end
end
if #row > 0 then
table.insert(rows, table.concat(row, ","))
end
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)
function Data.color(s: string?): string?
if type(s) ~= "string" then
return nil
end
local h = string.lower((string.gsub(s, "^#", "")))
if #h == 8 and string.sub(h, 1, 2) == "ff" then
h = string.sub(h, 3)
end
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
elseif typ == "bool" then
return text == "true" or text == "1"
elseif typ == "color" then
return Data.color(text) or ""
end
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
end
if type(v) == "boolean" then
return "bool"
elseif type(v) == "number" then
return if v % 1 == 0 then "int" else "float"
elseif type(v) == "table" then
return "class"
end
return "string"
end
-- sortedKeys(t) -> its string keys, sorted
function Data.sortedKeys(t: { [any]: any }): { string }
local out = {}
for k in pairs(t) do
if type(k) == "string" then
table.insert(out, k)
end
end
table.sort(out)
return out
end
return Data
+634
View File
@@ -0,0 +1,634 @@
--!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?.
local Types = require("@rosetta/Types")
local Data = require("@rosetta/vector/tiled/Data")
local Tmj = {}
local function n(v: any, default: number?): number?
if type(v) == "number" then
return v
end
return default
end
local function b(v: any, default: boolean): boolean
if type(v) == "boolean" then
return v
end
return default
end
local function s(v: any): string?
if type(v) == "string" then
return v
end
return nil
end
local function list(v: any): { any }
if type(v) == "table" then
return v
end
return {}
end
-- ------------------------------------------------------------------------------------------------ read
local function properties(v: any): ({ [string]: any }, { [string]: string }?)
local props: { [string]: any } = {}
local types: { [string]: string }? = nil
for _, p in list(v) do
if type(p) == "table" and type(p.name) == "string" then
local typ = s(p.type) or "string"
local val: any = p.value
if typ == "class" then
local inner, innerTypes = {}, nil
if type(val) == "table" then
-- a class value is an object of member -> value (types come from the project): keep them as they are
for k, x in pairs(val) do
if type(k) == "string" then
inner[k] = x
end
end
end
val = { class = s(p.propertytype) or "", properties = inner, propertyTypes = innerTypes }
elseif typ == "int" or typ == "float" or typ == "object" then
val = n(val, 0)
elseif typ == "bool" then
val = val == true
elseif typ == "color" then
val = Data.color(s(val)) or ""
elseif type(val) ~= "string" then
val = if val == nil then "" else tostring(val)
end
props[p.name] = val
if typ ~= "string" then
types = types or {}
;(types :: any)[p.name] = typ
end
end
end
return props, types
end
local function withProps(t: any, v: any)
local props, types = properties(v.properties)
t.properties = props
if types then
t.propertyTypes = types
end
end
local function gids(v: any, encoding: string?, compression: string?): ({ number }?, string?, boolean?)
if type(v) == "string" then
if encoding == "base64" or encoding == nil then
return Data.base64(v, compression)
end
return nil, "unknown encoding " .. tostring(encoding), true
end
local out = {}
for _, g in list(v) do
if type(g) ~= "number" or g < 0 or g >= 4294967296 then
return nil, "bad gid", nil
end
table.insert(out, g)
end
return out, nil, nil
end
local function object(o: any): any
local obj: any = {
id = n(o.id),
name = s(o.name) or "",
class = s(o.class) or s(o.type) or "",
x = n(o.x, 0),
y = n(o.y, 0),
width = n(o.width, 0),
height = n(o.height, 0),
rotation = n(o.rotation, 0),
gid = n(o.gid),
visible = b(o.visible, true),
template = s(o.template),
shape = "rectangle",
}
withProps(obj, o)
if o.ellipse == true then
obj.shape = "ellipse"
elseif o.point == true then
obj.shape = "point"
end
for _, kind in { "polygon", "polyline" } do
if type(o[kind]) == "table" then
obj.shape = kind
local pts = {}
for _, p in o[kind] do
if type(p) == "table" then
table.insert(pts, { n(p.x, 0), n(p.y, 0) })
end
end
obj.points = pts
end
end
if type(o.text) == "table" then
local t = o.text
obj.shape = "text"
obj.text = {
text = s(t.text) or "",
fontFamily = s(t.fontfamily) or "sans-serif",
pixelSize = n(t.pixelsize, 16),
wrap = b(t.wrap, false),
color = Data.color(s(t.color)) or "#000000",
bold = b(t.bold, false),
italic = b(t.italic, false),
underline = b(t.underline, false),
strikeout = b(t.strikeout, false),
kerning = b(t.kerning, true),
halign = s(t.halign) or "left",
valign = s(t.valign) or "top",
}
end
return obj
end
local TYPES = { tilelayer = "tiles", objectgroup = "objects", imagelayer = "image", group = "group" }
local layer: (v: any, depth: number) -> (any, string?, boolean?)
local function common(v: any, typ: string): any
local l: any = {
type = typ,
id = n(v.id),
name = s(v.name) or "",
visible = b(v.visible, true),
opacity = n(v.opacity, 1),
x = n(v.x, 0),
y = n(v.y, 0),
offsetX = n(v.offsetx, 0),
offsetY = n(v.offsety, 0),
parallaxX = n(v.parallaxx, 1),
parallaxY = n(v.parallaxy, 1),
tintColor = Data.color(s(v.tintcolor)),
class = s(v.class) or "",
locked = b(v.locked, false),
}
withProps(l, v)
return l
end
local function objectGroup(v: any): any
local l = common(v, "objects")
l.drawOrder = s(v.draworder) or "topdown"
l.color = Data.color(s(v.color))
l.objects = {}
for _, o in list(v.objects) do
if type(o) == "table" then
table.insert(l.objects, object(o))
end
end
return l
end
layer = function(v: any, depth: number): (any, string?, boolean?)
if type(v) ~= "table" then
return nil, "a layer is not an object"
end
if depth > 100 then
return nil, "groups nested too deep"
end
local typ = TYPES[v.type]
if typ == "tiles" then
local l = common(v, "tiles")
l.width = n(v.width, 0)
l.height = n(v.height, 0)
l.encoding = s(v.encoding)
l.compression = s(v.compression)
if type(v.chunks) == "table" then
l.chunks = {}
for _, c in v.chunks do
if type(c) == "table" then
local g, err, uns = gids(c.data, l.encoding, l.compression)
if not g then
return nil, err, uns
end
table.insert(l.chunks, { x = n(c.x, 0), y = n(c.y, 0), width = n(c.width, 0), height = n(c.height, 0), data = g })
end
end
elseif v.data ~= nil then
local g, err, uns = gids(v.data, l.encoding, l.compression)
if not g then
return nil, err, uns
end
l.data = g
end
return l
elseif typ == "objects" then
return objectGroup(v)
elseif typ == "image" then
local l = common(v, "image")
l.imageSource = s(v.image)
l.imageWidth = n(v.imagewidth)
l.imageHeight = n(v.imageheight)
l.transparentColor = Data.color(s(v.transparentcolor))
l.repeatX = b(v.repeatx, false)
l.repeatY = b(v.repeaty, false)
return l
elseif typ == "group" then
local l = common(v, "group")
l.layers = {}
for _, c in list(v.layers) do
local sub, err, uns = layer(c, depth + 1)
if not sub then
return nil, err, uns
end
table.insert(l.layers, sub)
end
return l
end
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),
source = s(v.source),
name = s(v.name) or "",
tileWidth = n(v.tilewidth, 0),
tileHeight = n(v.tileheight, 0),
spacing = n(v.spacing, 0),
margin = n(v.margin, 0),
count = n(v.tilecount, 0),
columns = n(v.columns, 0),
objectAlignment = s(v.objectalignment),
class = s(v.class) or "",
imageSource = s(v.image),
imageWidth = n(v.imagewidth),
imageHeight = n(v.imageheight),
transparentColor = Data.color(s(v.transparentcolor)),
}
withProps(ts, v)
if type(v.tileoffset) == "table" then
ts.tileOffset = { x = n(v.tileoffset.x, 0), y = n(v.tileoffset.y, 0) }
end
local tiles = {}
for _, t in list(v.tiles) do
if type(t) == "table" then
local tile: any = { id = n(t.id, 0), class = s(t.class) or s(t.type) or "", probability = n(t.probability) }
withProps(tile, t)
tile.imageSource = s(t.image)
tile.imageWidth = n(t.imagewidth)
tile.imageHeight = n(t.imageheight)
if type(t.animation) == "table" then
tile.animation = {}
for _, f in t.animation do
if type(f) == "table" then
table.insert(tile.animation, { tileId = n(f.tileid, 0), duration = n(f.duration, 0) })
end
end
end
if type(t.objectgroup) == "table" then
tile.objectGroup = objectGroup(t.objectgroup)
end
table.insert(tiles, tile)
end
end
table.sort(tiles, function(x: any, y: any): boolean
return x.id < y.id
end)
ts.tiles = tiles
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\")"
end
local map: any = Types.TileMap.new(n(v.width, 0) :: number, n(v.height, 0) :: number, n(v.tilewidth, 0) :: number, n(v.tileheight, 0) :: number)
map.version = if type(v.version) == "number" then Data.num(v.version) else s(v.version)
map.tiledVersion = s(v.tiledversion)
map.orientation = s(v.orientation) or "orthogonal"
map.renderOrder = s(v.renderorder) or "right-down"
map.infinite = b(v.infinite, false)
map.nextLayerId = n(v.nextlayerid)
map.nextObjectId = n(v.nextobjectid)
map.backgroundColor = Data.color(s(v.backgroundcolor))
map.hexSideLength = n(v.hexsidelength)
map.staggerAxis = s(v.staggeraxis)
map.staggerIndex = s(v.staggerindex)
map.class = s(v.class) or ""
map.parallaxOriginX = n(v.parallaxoriginx, 0)
map.parallaxOriginY = n(v.parallaxoriginy, 0)
withProps(map, v)
for _, ts in list(v.tilesets) do
if type(ts) == "table" then
table.insert(map.tilesets, Tmj.tileset(ts))
end
end
for _, l in list(v.layers) do
local x, err, uns = layer(l, 0)
if not x then
return nil, err, uns
end
table.insert(map.layers, x)
end
return map, nil
end
-- ------------------------------------------------------------------------------------------------ write
local function obj(pairs_: { { any } }): any
local o = Types.object()
for _, kv in pairs_ do
if kv[2] ~= nil then
Types.set(o, kv[1], kv[2])
end
end
return o
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 propList(props: any, types: any): { any }?
if type(props) ~= "table" or next(props) == nil then
return nil
end
local out = {}
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 members = Types.object()
if type(v.properties) == "table" then
for _, mk in Data.sortedKeys(v.properties) do
Types.set(members, mk, v.properties[mk])
end
end
table.insert(out, obj({ { "name", k }, { "propertytype", v.class or "" }, { "type", "class" }, { "value", members } }))
else
table.insert(out, obj({ { "name", k }, { "type", typ }, { "value", v } }))
end
end
return out
end
local function writeObject(o: any): any
local t: any = nil
if o.shape == "text" and type(o.text) == "table" then
local x = o.text
t = obj({
{ "bold", nz(x.bold, false) },
{ "color", nz(x.color, "#000000") },
{ "fontfamily", nz(x.fontFamily, "sans-serif") },
{ "halign", nz(x.halign, "left") },
{ "italic", nz(x.italic, false) },
{ "kerning", nz(x.kerning, true) },
{ "pixelsize", nz(x.pixelSize, 16) },
{ "strikeout", nz(x.strikeout, false) },
{ "text", tostring(x.text or "") },
{ "underline", nz(x.underline, false) },
{ "valign", nz(x.valign, "top") },
{ "wrap", nz(x.wrap, false) },
})
end
local pts: any = nil
if (o.shape == "polygon" or o.shape == "polyline") and type(o.points) == "table" then
pts = {}
for _, p in o.points do
table.insert(pts, obj({ { "x", tonumber(p[1]) or 0 }, { "y", tonumber(p[2]) or 0 } }))
end
end
return obj({
{ "ellipse", if o.shape == "ellipse" then true else nil },
{ "gid", o.gid },
{ "height", o.height or 0 },
{ "id", o.id },
{ "name", o.name or "" },
{ "point", if o.shape == "point" then true else nil },
{ "polygon", if o.shape == "polygon" then pts else nil },
{ "polyline", if o.shape == "polyline" then pts else nil },
{ "properties", propList(o.properties, o.propertyTypes) },
{ "rotation", o.rotation or 0 },
{ "template", o.template },
{ "text", t },
{ "type", o.class or "" },
{ "visible", o.visible ~= false },
{ "width", o.width or 0 },
{ "x", o.x or 0 },
{ "y", o.y or 0 },
})
end
export type WriteOptions = { encoding: string?, compression: string?, level: number? }
local function writeObjectGroup(l: any): any
local objs = {}
for _, o in (if type(l.objects) == "table" then l.objects else {}) do
table.insert(objs, writeObject(o))
end
return objs
end
local writeLayer: (l: any, o: WriteOptions) -> (any, string?)
writeLayer = function(l: any, o: WriteOptions): (any, string?)
local t = l.type
local fields: { { any } } = {}
local function add(k: string, v: any)
table.insert(fields, { k, v })
end
if t == "tiles" then
local enc = o.encoding or l.encoding
if enc ~= "base64" then
enc = nil
end
local comp = if enc then (o.compression or (if o.encoding then nil else l.compression)) else nil
local function payload(g: { number }): (any, string?)
if enc == "base64" then
return Data.toBase64(g, comp, o.level)
end
return g, nil
end
if type(l.chunks) == "table" then
local chunks = {}
for _, c in l.chunks do
local d, err = payload(c.data or {})
if d == nil then
return nil, err
end
table.insert(chunks, obj({ { "data", d }, { "height", c.height or 0 }, { "width", c.width or 0 }, { "x", c.x or 0 }, { "y", c.y or 0 } }))
end
add("chunks", chunks)
local sx, sy = math.huge, math.huge
for _, c in l.chunks do
sx, sy = math.min(sx, c.x or 0), math.min(sy, c.y or 0)
end
if #l.chunks > 0 then
add("startx", sx)
add("starty", sy)
end
elseif type(l.data) == "table" then
local d, err = payload(l.data)
if d == nil then
return nil, err
end
add("data", d)
end
add("compression", comp)
add("encoding", enc)
add("height", l.height or 0)
elseif t == "objects" then
add("color", l.color)
add("draworder", l.drawOrder or "topdown")
elseif t == "image" then
add("image", l.imageSource or "")
add("imageheight", l.imageHeight)
add("imagewidth", l.imageWidth)
elseif t == "group" then
local kids = {}
for _, c in (if type(l.layers) == "table" then l.layers else {}) do
local x, err = writeLayer(c, o)
if x == nil then
return nil, err
end
table.insert(kids, x)
end
add("layers", kids)
else
return nil, "unknown layer type " .. tostring(t)
end
add("class", str(l.class))
add("id", l.id)
add("locked", nz(l.locked, false))
add("name", l.name or "")
if t == "objects" then
add("objects", writeObjectGroup(l))
end
add("offsetx", nz(l.offsetX, 0))
add("offsety", nz(l.offsetY, 0))
add("opacity", l.opacity or 1)
add("parallaxx", nz(l.parallaxX, 1))
add("parallaxy", nz(l.parallaxY, 1))
add("properties", propList(l.properties, l.propertyTypes))
if t == "image" then
add("repeatx", nz(l.repeatX, false))
add("repeaty", nz(l.repeatY, false))
end
add("tintcolor", l.tintColor)
if t == "image" then
add("transparentcolor", l.transparentColor)
end
add("type", if t == "tiles" then "tilelayer" elseif t == "objects" then "objectgroup" elseif t == "image" then "imagelayer" else "group")
add("visible", l.visible ~= false)
if t == "tiles" then
add("width", l.width or 0)
end
add("x", l.x or 0)
add("y", l.y or 0)
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 } })
end
local tiles: any = nil
if type(ts.tiles) == "table" and #ts.tiles > 0 then
tiles = {}
for _, tile in ts.tiles do
local anim: any = nil
if type(tile.animation) == "table" then
anim = {}
for _, f in tile.animation do
table.insert(anim, obj({ { "duration", f.duration or 0 }, { "tileid", f.tileId or 0 } }))
end
end
local og: any = nil
if type(tile.objectGroup) == "table" then
og = writeLayer(tile.objectGroup, {})
end
table.insert(tiles, obj({
{ "animation", anim },
{ "id", tile.id or 0 },
{ "image", tile.imageSource },
{ "imageheight", tile.imageHeight },
{ "imagewidth", tile.imageWidth },
{ "objectgroup", og },
{ "probability", tile.probability },
{ "properties", propList(tile.properties, tile.propertyTypes) },
{ "type", str(tile.class) },
}))
end
end
return obj({
{ "class", str(ts.class) },
{ "columns", ts.columns or 0 },
{ "firstgid", if inMap then ts.firstGid or 1 else nil },
{ "image", ts.imageSource },
{ "imageheight", ts.imageHeight },
{ "imagewidth", ts.imageWidth },
{ "margin", ts.margin or 0 },
{ "name", ts.name or "" },
{ "objectalignment", ts.objectAlignment },
{ "properties", propList(ts.properties, ts.propertyTypes) },
{ "spacing", ts.spacing or 0 },
{ "tilecount", ts.count or 0 },
{ "tileheight", ts.tileHeight or 0 },
{ "tileoffset", if type(ts.tileOffset) == "table" then obj({ { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }) else nil },
{ "tiles", tiles },
{ "tilewidth", ts.tileWidth or 0 },
{ "transparentcolor", ts.transparentColor },
{ "type", if inMap then nil else "tileset" },
})
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
local x, err = writeLayer(l, o)
if x == nil then
return nil, err
end
table.insert(layers, x)
end
local tilesets = {}
for _, ts in map.tilesets do
table.insert(tilesets, Tmj.tilesetValue(ts, true))
end
return obj({
{ "backgroundcolor", map.backgroundColor },
{ "class", str(map.class) },
{ "compressionlevel", -1 },
{ "height", map.height },
{ "hexsidelength", map.hexSideLength },
{ "infinite", map.infinite == true },
{ "layers", layers },
{ "nextlayerid", map.nextLayerId },
{ "nextobjectid", map.nextObjectId },
{ "orientation", map.orientation or "orthogonal" },
{ "parallaxoriginx", nz(map.parallaxOriginX, 0) },
{ "parallaxoriginy", nz(map.parallaxOriginY, 0) },
{ "properties", propList(map.properties, map.propertyTypes) },
{ "renderorder", map.renderOrder or "right-down" },
{ "staggeraxis", map.staggerAxis },
{ "staggerindex", map.staggerIndex },
{ "tiledversion", map.tiledVersion },
{ "tileheight", map.tileHeight },
{ "tilesets", tilesets },
{ "tilewidth", map.tileWidth },
{ "type", "map" },
{ "version", map.version or "1.10" },
{ "width", map.width },
}), nil
end
return Tmj
+618
View File
@@ -0,0 +1,618 @@
--!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("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local Data = require("@rosetta/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
-- <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
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 <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))
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 <tileset> 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 <map>"
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) -> <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 } })
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
+187
View File
@@ -0,0 +1,187 @@
--!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).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Sniff = require("@rosetta/core/Sniff")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Xml = require("@rosetta/codecs/text/Xml")
local Json = require("@rosetta/codecs/text/Json")
local Tmx = require("@rosetta/vector/tiled/Tmx")
local Tmj = require("@rosetta/vector/tiled/Tmj")
-- ------------------------------------------------------------------------------------------------ contract
local Tiled = {
name = "tiled",
category = "vector",
extensions = { "tmx", "tmj", "tsx", "tsj" },
mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" },
deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" },
caps = { decode = true, encode = true, tilesets = true, infinite = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 256 MB)
}
export type EncodeOptions = {
format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (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)
}
-- ------------------------------------------------------------------------------------------------ sniff
local function head(r: Bytes.Reader): string
local h = Sniff.text(r, 1024)
return h
end
function Tiled.sniff(r: Bytes.Reader): number
local h = head(r)
if string.match(h, "^%s*<") then
if string.find(h, "<map[%s>]") or string.find(h, "<tileset[%s>]") then
return 0.9
end
return 0
end
if string.match(h, "^%s*{") then
-- Tiled writes its keys sorted: "type" comes last, so look at the tail too
local n = r:remaining()
local tail = if n > 1024 then r:peek(1024, n - 1024) else ""
for _, part in { h, tail } do
if string.find(part, "\"type\"%s*:%s*\"map\"") or string.find(part, "\"type\"%s*:%s*\"tileset\"") then
return 0.8
end
end
if string.find(h, "\"tilewidth\"", 1, true) and (string.find(h, "\"orientation\"", 1, true) or string.find(h, "\"tilesets\"", 1, true)) then
return 0.6
end
end
return 0
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
return nil, Err.new(Err.LIMIT, "file is over the byte limit")
end
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local h = head(r)
local map: any, msg: string?, unsupported: boolean?
local flavour
if string.match(h, "^%s*<") then
local doc, xerr = Xml.decode(text)
if not doc then
return nil, xerr
end
local root = (doc :: any).root
if root == nil then
return nil, Err.new(Err.CORRUPT, "no root element")
end
if root.name == "tileset" then
map = Types.TileMap.new(0, 0, 0, 0)
map.tilesets = { Tmx.tileset(root) }
map.meta.tileset = true
flavour = "tsx"
else
map, msg, unsupported = Tmx.read(root)
flavour = "tmx"
end
else
local v, jerr = Json.decode(text)
if v == nil then
return nil, jerr
end
if type(v) == "table" and v.type == "tileset" then
map = Types.TileMap.new(0, 0, 0, 0)
map.tilesets = { Tmj.tileset(v) }
map.meta.tileset = true
flavour = "tsj"
else
map, msg, unsupported = Tmj.read(v)
flavour = "tmj"
end
end
if not map then
return nil, Err.new(if unsupported then Err.UNSUPPORTED else Err.CORRUPT, msg or "bad map")
end
map.meta.source = { format = flavour }
return map, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Tiled.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then
return nil, Err.new(Err.ARG, "needs a TileMap value")
end
local o: EncodeOptions = opts or {}
local meta: any = if type(map.meta) == "table" then map.meta else {}
local fmt = o.format or (if type(meta.source) == "table" then meta.source.format else nil) or "tmx"
fmt = string.lower(fmt)
if fmt == "tiled" then
fmt = if type(meta.source) == "table" and meta.source.format then meta.source.format else "tmx"
end
local tilesetOnly = meta.tileset == true or fmt == "tsx" or fmt == "tsj"
if o.encoding and o.encoding ~= "csv" and o.encoding ~= "base64" and o.encoding ~= "xml" then
return nil, Err.new(Err.ARG, "encoding must be csv, base64 or xml")
end
if o.compression and o.compression ~= "zlib" and o.compression ~= "gzip" then
return nil, Err.new(Err.ARG, "compression must be zlib or gzip")
end
local wo: Tmx.WriteOptions = { encoding = o.encoding :: string?, compression = o.compression, level = o.level }
if fmt == "tmx" or fmt == "tsx" or fmt == "xml" then
local doc: any, err: string?
if tilesetOnly then
if not map.tilesets[1] then
return nil, Err.new(Err.ARG, "no tileset to write")
end
doc = Xml.document(Tmx.tilesetNode(map.tilesets[1], false), { version = "1.0", encoding = "UTF-8" })
else
doc, err = Tmx.write(map, wo)
end
if not doc then
return nil, Err.new(Err.ARG, err or "bad map")
end
local s, xerr = Xml.encode(doc, { indent = o.indent or 1 })
if not s then
return nil, xerr
end
return buffer.fromstring(s .. "\n"), nil
elseif fmt == "tmj" or fmt == "tsj" or fmt == "json" then
local v: any, err: string?
if tilesetOnly then
if not map.tilesets[1] then
return nil, Err.new(Err.ARG, "no tileset to write")
end
v = Tmj.tilesetValue(map.tilesets[1], false)
else
v, err = Tmj.write(map, wo)
end
if v == nil then
return nil, Err.new(Err.ARG, err or "bad map")
end
local indent = if o.indent == 0 then nil else (o.indent or 2)
local s, jerr = Json.encode(v, { indent = indent })
if not s then
return nil, jerr
end
return buffer.fromstring(s .. "\n"), nil
end
return nil, Err.new(Err.ARG, "unknown format " .. tostring(fmt) .. " (tmx, tmj, tsx, tsj)")
end
return Tiled