759 lines
25 KiB
Luau
759 lines
25 KiB
Luau
--!strict
|
|
-- vector/svg/Parse: an SVG document (a codecs/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("@formats/codecs/Xml")
|
|
local Types = require("@formats/Types")
|
|
local Style = require("@formats/vector/svg/Style")
|
|
local PathData = require("@formats/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
|