Files
rosetta/src/Formats/codecs/Raster.luau
T

745 lines
26 KiB
Luau

--!strict
--!native
--!optimize 2
-- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
-- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and
-- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 /
-- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an
-- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed
-- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2.
--
-- local R = require("@formats/codecs/Raster")
-- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list:
-- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 },
-- { op = "close" } } -- (the Font:outline() format)
-- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } })
-- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty
-- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over)
-- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients)
-- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero)
--
-- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are
-- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to
-- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling.
--
-- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the
-- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths.
local Raster = {}
local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt
local readf32, writef32, readu8, writeu8 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8
local bcreate = buffer.create
export type Cmd = { op: string, [number]: number }
export type Path = { Cmd }
export type Transform = { number }
export type Mask = { x: number, y: number, width: number, height: number, coverage: buffer }
export type Options = {
transform: Transform?, -- default identity
rule: ("nonzero" | "evenodd")?, -- default "nonzero"
clip: { number }?, -- { x0, y0, x1, y1 } device pixel bounds (integers); default: the path's bounds (fill: the image)
tolerance: number?, -- curve flattening tolerance in device pixels (default 0.1)
maxPixels: number?, -- largest mask (default 2^26)
opacity: number?, -- fill: multiplies the coverage (0..1, default 1)
}
local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken
-- ------------------------------------------------------------------------------------------------ transforms
Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 })
-- multiply(m, n) -> m * n (apply n first, then m)
function Raster.multiply(m: Transform, n: Transform): Transform
return {
m[1] * n[1] + m[3] * n[2],
m[2] * n[1] + m[4] * n[2],
m[1] * n[3] + m[3] * n[4],
m[2] * n[3] + m[4] * n[4],
m[1] * n[5] + m[3] * n[6] + m[5],
m[2] * n[5] + m[4] * n[6] + m[6],
}
end
function Raster.translate(tx: number, ty: number): Transform
return { 1, 0, 0, 1, tx, ty }
end
function Raster.scale(sx: number, sy: number?): Transform
return { sx, 0, 0, sy or sx, 0, 0 }
end
function Raster.rotate(radians: number): Transform
local c, s = math.cos(radians), math.sin(radians)
return { c, s, -s, c, 0, 0 }
end
-- invert(m) -> m^-1 | nil (singular)
function Raster.invert(m: Transform): Transform?
local det = m[1] * m[4] - m[2] * m[3]
if det == 0 or det ~= det then
return nil
end
local id = 1 / det
local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id
return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) }
end
-- apply(m, x, y) -> x', y'
function Raster.apply(m: Transform, x: number, y: number): (number, number)
return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6]
end
-- ------------------------------------------------------------------------------------------------ path builder
local Builder = {}
Builder.__index = Builder
export type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder))
-- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path
-- takes a builder too)
function Raster.path(): Builder
return setmetatable({ cmds = {} :: Path }, Builder)
end
function Builder.moveTo(self: Builder, x: number, y: number): Builder
table.insert(self.cmds, { op = "moveTo", x, y })
return self
end
function Builder.lineTo(self: Builder, x: number, y: number): Builder
table.insert(self.cmds, { op = "lineTo", x, y })
return self
end
function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder
table.insert(self.cmds, { op = "quadTo", cx, cy, x, y })
return self
end
function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder
table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y })
return self
end
function Builder.close(self: Builder): Builder
table.insert(self.cmds, { op = "close" })
return self
end
-- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths
function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder
return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close()
end
function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder
local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle
self:moveTo(cx + rx, cy)
self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry)
self:cubicTo(cx - rx * k, cy + ry, cx - rx, cy + ry * k, cx - rx, cy)
self:cubicTo(cx - rx, cy - ry * k, cx - rx * k, cy - ry, cx, cy - ry)
self:cubicTo(cx + rx * k, cy - ry, cx + rx, cy - ry * k, cx + rx, cy)
return self:close()
end
local function commands(path: any): Path?
if type(path) ~= "table" then
return nil
end
if type(path.cmds) == "table" then
return path.cmds
end
return path
end
-- n numeric operands of a command, or nil
local function operands(c: any, n: number): boolean
if type(c) ~= "table" then
return false
end
for i = 1, n do
local v = c[i]
if type(v) ~= "number" or v ~= v or abs(v) > 1e15 then
return false
end
end
return true
end
-- ------------------------------------------------------------------------------------------------ flattening
-- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath
-- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty)
local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?)
local cmds = commands(path)
local polys: { { number } } = {}
if not cmds then
return polys
end
local m = transform or Raster.IDENTITY
local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6]
if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then
return polys
end
local tol = tolerance or 0.1
if type(tol) ~= "number" or not (tol > 0.001) then
tol = 0.1
end
local cur: { number }? = nil
local px, py = 0, 0 -- current point (device)
local sx, sy = 0, 0 -- subpath start (device)
local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge
local function point(x: number, y: number)
local poly = cur :: { number }
local n = #poly
poly[n + 1] = x
poly[n + 2] = y
if x < bx0 then
bx0 = x
end
if x > bx1 then
bx1 = x
end
if y < by0 then
by0 = y
end
if y > by1 then
by1 = y
end
end
local function start(x: number, y: number)
if cur and #cur >= minLen then
table.insert(polys, cur)
end
cur = {}
point(x, y)
sx, sy = x, y
px, py = x, y
end
for _, cmd in cmds do
local op = if type(cmd) == "table" then cmd.op else nil
if op == "moveTo" then
if operands(cmd, 2) then
start(a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f)
end
elseif op == "lineTo" then
if operands(cmd, 2) then
if not cur then
start(px, py)
end
px, py = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
point(px, py)
end
elseif op == "quadTo" then
if operands(cmd, 4) then
if not cur then
start(px, py)
end
local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f
local ddx, ddy = px - 2 * x1 + x2, py - 2 * y1 + y2
local n = ceil(sqrt(sqrt(ddx * ddx + ddy * ddy) * 0.25 / tol))
n = if n ~= n then 1 else max(1, min(n, 500))
local x0, y0 = px, py
for i = 1, n - 1 do
local t = i / n
local u = 1 - t
point(u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2)
end
point(x2, y2)
px, py = x2, y2
end
elseif op == "cubicTo" then
if operands(cmd, 6) then
if not cur then
start(px, py)
end
local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f
local x3, y3 = a * cmd[5] + c * cmd[6] + e, b * cmd[5] + d * cmd[6] + f
local ax, ay = px - 2 * x1 + x2, py - 2 * y1 + y2
local bxx, byy = x1 - 2 * x2 + x3, y1 - 2 * y2 + y3
local dd = max(sqrt(ax * ax + ay * ay), sqrt(bxx * bxx + byy * byy))
local n = ceil(sqrt(dd * 0.75 / tol))
n = if n ~= n then 1 else max(1, min(n, 500))
local x0, y0 = px, py
for i = 1, n - 1 do
local t = i / n
local u = 1 - t
local w0, w1, w2, w3 = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t
point(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3, w0 * y0 + w1 * y1 + w2 * y2 + w3 * y3)
end
point(x3, y3)
px, py = x3, y3
end
elseif op == "close" then
if cur then
if #cur >= minLen then
table.insert(polys, cur)
end
cur = nil
px, py = sx, sy
end
end
end
if cur and #cur >= minLen then
table.insert(polys, cur)
end
if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then
return polys
end
return polys, bx0, by0, bx1, by1
end
function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, number?)
return flatten(path, transform, tolerance, 6)
end
-- ------------------------------------------------------------------------------------------------ accumulation
-- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area
-- each pixel gains (font-rs's draw_line)
local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number)
if y0 == y1 then
return
end
local W = S - 2
local xl, xr = 0, W -- x stays in [0, W] (rounding in the splits and in x + dxdy * dy must never index outside)
local dir = 1
if y0 > y1 then
dir = -1
x0, x1 = x1, x0
y0, y1 = y1, y0
end
if y1 <= 0 or y0 >= H then
return
end
local dxdy = (x1 - x0) / (y1 - y0)
local x = x0
if y0 < 0 then
x -= y0 * dxdy
end
local ystart = max(0, floor(y0))
local yend = min(H, ceil(y1)) - 1
for y = ystart, yend do
local ls = y * S
local dy = min(y + 1, y1) - max(y, y0)
local xnext = x + dxdy * dy
if xnext < xl then
xnext = xl
elseif xnext > xr then
xnext = xr
end
if x < xl then
x = xl
elseif x > xr then
x = xr
end
local dd = dy * dir
local xa, xb = x, xnext
if xa > xb then
xa, xb = xb, xa
end
local xaf = floor(xa)
local xai = xaf
local xbc = ceil(xb)
local xbi = xbc
if xbi <= xai + 1 then
local xmf = 0.5 * (x + xnext) - xaf
local o = (ls + xai) * 4
writef32(acc, o, readf32(acc, o) + dd - dd * xmf)
writef32(acc, o + 4, readf32(acc, o + 4) + dd * xmf)
else
local s = 1 / (xb - xa)
local x0f = xa - xaf
local a0 = 0.5 * s * (1 - x0f) * (1 - x0f)
local x1f = xb - xbc + 1
local am = 0.5 * s * x1f * x1f
local o = (ls + xai) * 4
writef32(acc, o, readf32(acc, o) + dd * a0)
if xbi == xai + 2 then
writef32(acc, o + 4, readf32(acc, o + 4) + dd * (1 - a0 - am))
else
local a1 = s * (1.5 - x0f)
writef32(acc, o + 4, readf32(acc, o + 4) + dd * (a1 - a0))
local ds = dd * s
for xi = xai + 2, xbi - 2 do
local q = (ls + xi) * 4
writef32(acc, q, readf32(acc, q) + ds)
end
local a2 = a1 + (xbi - xai - 3) * s
local q = (ls + xbi - 1) * 4
writef32(acc, q, readf32(acc, q) + dd * (1 - a2 - am))
end
local q = (ls + xbi) * 4
writef32(acc, q, readf32(acc, q) + dd * am)
end
x = xnext
end
end
-- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the
-- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still
-- applies to the row)
local function clampx(x: number, W: number): number
return if x < 0 then 0 elseif x > W then W else x
end
local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number)
if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then
return -- horizontal, or non-finite (NaN fails every comparison)
end
if (y0 <= 0 and y1 <= 0) or (y0 >= H and y1 >= H) then
return
end
local dx = x1 - x0
local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none)
if dx ~= 0 then
local t0 = (0 - x0) / dx
local tw = (W - x0) / dx
if t0 > 0 and t0 < 1 then
ta = t0
end
if tw > 0 and tw < 1 then
tb = tw
end
if ta > tb then
ta, tb = tb, ta
end
end
local dy = y1 - y0
local px, py = x0, y0
if ta < 1 then
local qx, qy = x0 + dx * ta, y0 + dy * ta
line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy)
px, py = qx, qy
end
if tb < 1 then
local qx, qy = x0 + dx * tb, y0 + dy * tb
line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy)
px, py = qx, qy
end
line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1)
end
-- ------------------------------------------------------------------------------------------------ masks
-- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit")
function Raster.mask(path: any, opts: Options?): (Mask?, string?)
local o: Options = opts or {}
local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance)
if not bx0 then
return nil
end
if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then
return nil, "coordinates out of range"
end
local X0, Y0, X1, Y1 = floor(bx0 :: number), floor(by0 :: number), ceil(bx1 :: number), ceil(by1 :: number)
local clip = o.clip
if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then
Y0 = max(Y0, floor(clip[2]))
Y1 = min(Y1, ceil(clip[4]))
X1 = min(X1, ceil(clip[3]))
local cx0 = floor(clip[1])
X0 = max(X0, cx0)
end
local W, H = X1 - X0, Y1 - Y0
if W <= 0 or H <= 0 then
return nil
end
local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26
if W * H > maxPixels then
return nil, "limit"
end
local S = W + 2
local acc = bcreate(S * H * 4)
for _, poly in polys do
local n = #poly
local lx, ly = poly[n - 1] - X0, poly[n] - Y0
for i = 1, n - 1, 2 do
local x, y = poly[i] - X0, poly[i + 1] - Y0
edge(acc, S, W, H, lx, ly, x, y)
lx, ly = x, y
end
end
local cov = bcreate(W * H)
local evenodd = o.rule == "evenodd"
for y = 0, H - 1 do
local sum = 0
local ls = y * S
local os = y * W
for x = 0, W - 1 do
sum += readf32(acc, (ls + x) * 4)
local v = abs(sum)
if evenodd then
v = v % 2
if v > 1 then
v = 2 - v
end
elseif v > 1 then
v = 1
end
writeu8(cov, os + x, floor(v * 255 + 0.5))
end
end
return { x = X0, y = Y0, width = W, height = H, coverage = cov }
end
-- ------------------------------------------------------------------------------------------------ filling
-- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an
-- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in
-- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the
-- image; opts.opacity scales the coverage.
function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
return false, "fill: expected an rgba8 image"
end
local iw, ih = img.width, img.height
local px = img.pixels
if buffer.len(px) < iw * ih * 4 then
return false, "fill: image pixels too short"
end
local o: Options = table.clone(opts or {})
local clip = o.clip
if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then
o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) }
else
o.clip = { 0, 0, iw, ih }
end
local m, why = Raster.mask(path, o)
if not m then
return why == nil, why
end
local opacity = if type(o.opacity) == "number" then math.clamp(o.opacity, 0, 1) else 1
local fn: any = nil
local cr, cg, cb, ca = 0, 0, 0, 255
if type(paint) == "function" then
fn = paint
elseif type(paint) == "table" then
cr, cg, cb = tonumber(paint[1]) or 0, tonumber(paint[2]) or 0, tonumber(paint[3]) or 0
ca = tonumber(paint[4]) or 255
else
return false, "fill: paint must be a colour or a function"
end
local cov = m.coverage
local mw = m.width
for y = 0, m.height - 1 do
local iy = m.y + y
for x = 0, mw - 1 do
local cv = readu8(cov, y * mw + x)
if cv > 0 then
local ix = m.x + x
local r, g, b, a = cr, cg, cb, ca
if fn then
local ok, r2, g2, b2, a2 = pcall(fn, ix + 0.5, iy + 0.5)
if not ok then
return false, "fill: paint function failed"
end
r, g, b, a = tonumber(r2) or 0, tonumber(g2) or 0, tonumber(b2) or 0, tonumber(a2) or 255
end
local sa = math.clamp(a, 0, 255) / 255 * cv / 255 * opacity
if sa > 0 then
local p = (iy * iw + ix) * 4
local da = readu8(px, p + 3) / 255
local oa = sa + da * (1 - sa)
local k = da * (1 - sa)
writeu8(px, p, floor((math.clamp(r, 0, 255) * sa + readu8(px, p) * k) / oa + 0.5))
writeu8(px, p + 1, floor((math.clamp(g, 0, 255) * sa + readu8(px, p + 1) * k) / oa + 0.5))
writeu8(px, p + 2, floor((math.clamp(b, 0, 255) * sa + readu8(px, p + 2) * k) / oa + 0.5))
writeu8(px, p + 3, floor(oa * 255 + 0.5))
end
end
end
end
return true
end
-- ------------------------------------------------------------------------------------------------ stroking
export type StrokeOptions = {
width: number?, -- default 1
join: ("miter" | "round" | "bevel")?, -- default "miter"
cap: ("butt" | "round" | "square")?, -- default "butt"
miterLimit: number?, -- default 4 (SVG)
tolerance: number?, -- flattening tolerance in path units (default 0.1); scale it down for magnified strokes
closed: boolean?, -- treat every subpath as closed (default: only subpaths ending with "close")
}
-- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up
-- under the nonzero rule
local function polygon(out: Path, pts: { number })
local n = #pts
if n < 6 then
return
end
local area = 0
for i = 1, n - 1, 2 do
local j = if i + 2 > n then 1 else i + 2
area += pts[i] * pts[j + 1] - pts[j] * pts[i + 1]
end
if area == 0 then
return
end
if area > 0 then
table.insert(out, { op = "moveTo", pts[1], pts[2] })
for i = 3, n - 1, 2 do
table.insert(out, { op = "lineTo", pts[i], pts[i + 1] })
end
else
table.insert(out, { op = "moveTo", pts[n - 1], pts[n] })
for i = n - 3, 1, -2 do
table.insert(out, { op = "lineTo", pts[i], pts[i + 1] })
end
end
table.insert(out, { op = "close" })
end
local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number })
local da = a1 - a0
local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1))
local n = max(1, min(256, ceil(abs(da) / max(step, 0.01))))
for i = 0, n do
local t = a0 + da * i / n
table.insert(pts, cx + r * math.cos(t))
table.insert(pts, cy + r * math.sin(t))
end
end
-- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own
-- coordinate space: transform it like the path). Dashes are the caller's job (split the path first).
function Raster.stroke(path: any, opts: StrokeOptions?): Path
local o: StrokeOptions = opts or {}
local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2
local join = o.join or "miter"
local cap = o.cap or "butt"
local miterLimit = if type(o.miterLimit) == "number" and o.miterLimit >= 1 then o.miterLimit else 4
local tol = if type(o.tolerance) == "number" and o.tolerance > 0.0005 then o.tolerance else 0.1
local out: Path = {}
local cmds = commands(path)
if not cmds then
return out
end
-- subpaths with their closed flag (flatten loses it, so split here)
local subs: { { cmds: Path, closed: boolean } } = {}
local cur: Path? = nil
local lx, ly = 0, 0
for _, c in cmds do
local op = if type(c) == "table" then c.op else nil
if op == "moveTo" and operands(c, 2) then
cur = { c }
table.insert(subs, { cmds = cur :: Path, closed = o.closed == true })
lx, ly = c[1], c[2]
elseif op == "close" then
if cur then
subs[#subs].closed = true
cur = nil
end
elseif op == "lineTo" or op == "quadTo" or op == "cubicTo" then
if not cur then
cur = { { op = "moveTo", lx, ly } }
table.insert(subs, { cmds = cur :: Path, closed = o.closed == true })
end
table.insert(cur :: Path, c)
end
end
for _, sub in subs do
local polys = flatten(sub.cmds, nil, tol, 4)
local pts = polys[1]
if not pts then
-- a degenerate subpath (a single point): round / square caps draw a dot
local m = sub.cmds[1]
if #sub.cmds >= 1 and operands(m, 2) and cap ~= "butt" then
local d = {}
if cap == "round" then
arcPoints(m[1], m[2], hw, 0, 2 * math.pi, tol, d)
else
d = { m[1] - hw, m[2] - hw, m[1] + hw, m[2] - hw, m[1] + hw, m[2] + hw, m[1] - hw, m[2] + hw }
end
polygon(out, d)
end
continue
end
-- drop repeated points
local p: { number } = { pts[1], pts[2] }
for i = 3, #pts - 1, 2 do
if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then
table.insert(p, pts[i])
table.insert(p, pts[i + 1])
end
end
local closed = sub.closed
if closed and #p >= 4 and abs(p[1] - p[#p - 1]) < 1e-9 and abs(p[2] - p[#p]) < 1e-9 then
table.remove(p)
table.remove(p)
end
local n = #p // 2
if n < 2 then
continue
end
local segs = if closed then n else n - 1
-- segment bodies
local dirs: { number } = {}
for s = 0, segs - 1 do
local i, j = s, (s + 1) % n
local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2]
local dx, dy = x1 - x0, y1 - y0
local len = sqrt(dx * dx + dy * dy)
local ux, uy = dx / len, dy / len
dirs[2 * s + 1], dirs[2 * s + 2] = ux, uy
local nx, ny = -uy * hw, ux * hw
polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny })
end
-- joins
local function joinAt(k: number, s0: number, s1: number)
local x, y = p[2 * k + 1], p[2 * k + 2]
local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2]
local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2]
local cross = ax * by - ay * bx
if abs(cross) < 1e-12 and ax * bx + ay * by > 0 then
return
end
-- the outer side: left normals when turning right (cross < 0)
local sgn = if cross < 0 then 1 else -1
local n0x, n0y = -ay * hw * sgn, ax * hw * sgn
local n1x, n1y = -by * hw * sgn, bx * hw * sgn
if join == "round" then
local d = { x, y }
local a0 = math.atan2(n0y, n0x)
local a1 = math.atan2(n1y, n1x)
local da = a1 - a0
while da > math.pi do
da -= 2 * math.pi
end
while da < -math.pi do
da += 2 * math.pi
end
arcPoints(x, y, hw, a0, a0 + da, tol, d)
polygon(out, d)
else
local cosT = ax * bx + ay * by -- angle between directions
local miter = if join == "miter" then 1 / sqrt(max(1e-12, (1 + cosT) / 2)) else math.huge
if join == "miter" and miter <= miterLimit then
local mx, my = n0x + n1x, n0y + n1y
local ml = sqrt(mx * mx + my * my)
if ml > 1e-12 then
local scale = hw * miter / ml
polygon(out, { x, y, x + n0x, y + n0y, x + mx * scale, y + my * scale, x + n1x, y + n1y })
return
end
end
polygon(out, { x, y, x + n0x, y + n0y, x + n1x, y + n1y })
end
end
if closed then
for k = 0, n - 1 do
joinAt(k, (k - 1) % n, k)
end
else
for k = 1, n - 2 do
joinAt(k, k - 1, k)
end
-- caps
if cap ~= "butt" then
for _, endInfo in { { 0, 0, -1 }, { n - 1, segs - 1, 1 } } do
local k, s, sgn = endInfo[1], endInfo[2], endInfo[3]
local x, y = p[2 * k + 1], p[2 * k + 2]
local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn -- pointing outwards
local nx, ny = -uy * hw, ux * hw
if cap == "square" then
polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny })
else
local d = {}
local a0 = math.atan2(ny, nx)
arcPoints(x, y, hw, a0, a0 - math.pi, tol, d)
polygon(out, d)
end
end
end
end
end
return out
end
return Raster