vec: vector/svg (parse to Vector: paths/arcs, shapes, transforms, groups, use/symbol/nested svg, CSS subset, gradients, opacity groups, clip paths, units; rasterize via codecs/Raster + codecs/Blend; write SVG back). Tests vs resvg (PSNR) incl. resvg rendering our written SVG
This commit is contained in:
1 parent
84e5d2e4c9
commit
6c54b0c6d5
11 files changed
+2632
-3
No files matched your search
@@ -0,0 +1,427 @@
|
||||
--!strict
|
||||
-- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/Raster (antialiased coverage, nonzero / even-odd,
|
||||
-- the stroker) and codecs/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("@formats/Types")
|
||||
local Raster = require("@formats/codecs/Raster")
|
||||
local Blend = require("@formats/codecs/Blend")
|
||||
local PathData = require("@formats/vector/svg/PathData")
|
||||
local Parse = require("@formats/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
|
||||
Reference in new issue
Block a user