From 17106c2eb1e29a6a1a58c52681cc8643bdaa2a06 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:30:45 -0500 Subject: [PATCH] ws-arch: codecs/Raster: antialiased signed-area scanline rasterizer (lines, quads, cubics, affine transforms, nonzero + even-odd, clip, masks, fill with colour or paint function, polygon stroker with caps/joins); tests vs a supersampled winding reference --- docs/FORMATS.md | 1 + src/Formats/codecs/Raster.luau | 744 +++++++++++++++++++++++++++++++++ tests/codecs/raster.luau | 259 ++++++++++++ 3 files changed, 1004 insertions(+) create mode 100644 src/Formats/codecs/Raster.luau create mode 100644 tests/codecs/raster.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..a5a25a7 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,3 +10,4 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine diff --git a/src/Formats/codecs/Raster.luau b/src/Formats/codecs/Raster.luau new file mode 100644 index 0000000..953336e --- /dev/null +++ b/src/Formats/codecs/Raster.luau @@ -0,0 +1,744 @@ +--!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 diff --git a/tests/codecs/raster.luau b/tests/codecs/raster.luau new file mode 100644 index 0000000..8103a25 --- /dev/null +++ b/tests/codecs/raster.luau @@ -0,0 +1,259 @@ +-- codecs/Raster tests: exact coverage of axis-aligned rectangles at fractional positions; areas of circles; random +-- polygons and curves under random transforms against an independent 12 x 12 supersampled winding-number reference +-- (both fill rules); clipping, the stroker (width, caps, joins against analytic areas), fill() compositing and paint +-- functions; malformed paths never throw. Glyph rendering against FreeType is in tests/font/ttf.luau. +local T = require("@tests/T") +local R = require("@formats/codecs/Raster") +local Types = require("@formats/Types") + +local t = T.suite("raster") + +local function sum(m: any): number + if not m then + return 0 + end + local s = 0 + for i = 0, m.width * m.height - 1 do + s += buffer.readu8(m.coverage, i) + end + return s / 255 +end + +local function at(m: any, x: number, y: number): number + local i, j = x - m.x, y - m.y + if i < 0 or j < 0 or i >= m.width or j >= m.height then + return 0 + end + return buffer.readu8(m.coverage, j * m.width + i) +end + +-- 1. rectangles: exact per-pixel coverage +do + local p = R.path():rect(1.25, 2.5, 3.5, 2) + local m = R.mask(p) :: any + t:check(m, "rect mask") + t:eq(m.x, 1, "rect x") + t:eq(m.y, 2, "rect y") + t:eq(m.width, 4, "rect width") + t:eq(m.height, 3, "rect height") + -- row 2 covers y 2.5..3 (half), columns: 1 covers 0.75, 2-3 full, 4 covers 0.75 + t:eq(at(m, 1, 2), math.floor(0.75 * 0.5 * 255 + 0.5), "corner pixel") + t:eq(at(m, 2, 2), math.floor(0.5 * 255 + 0.5), "top edge pixel") + t:eq(at(m, 2, 3), 255, "interior pixel") + t:eq(at(m, 4, 3), math.floor(0.75 * 255 + 0.5), "right edge pixel") + t:check(math.abs(sum(m) - 7) < 0.02, "rect area 7: " .. sum(m)) + -- reversed orientation gives the same coverage + local q = R.path():moveTo(1.25, 2.5):lineTo(1.25, 4.5):lineTo(4.75, 4.5):lineTo(4.75, 2.5):close() + t:check(math.abs(sum(R.mask(q)) - 7) < 0.02, "reversed rect") +end + +-- 2. circles: area pi r^2 (cubic approximation error ~ 2.7e-4 r) +for _, r in { 3, 10.5, 40 } do + local m = R.mask(R.path():ellipse(50.3, 50.7, r, r)) + local a = sum(m) + t:check(math.abs(a - math.pi * r * r) < 0.01 * math.pi * r * r + 1, string.format("circle r=%g area %.2f", r, a)) +end + +-- 3. random paths against a supersampled winding reference +local function wind(polys: { { number } }, px: number, py: number): number + local w = 0 + for _, poly in polys do + local n = #poly + local x0, y0 = poly[n - 1], poly[n] + for i = 1, n - 1, 2 do + local x1, y1 = poly[i], poly[i + 1] + if y0 <= py then + if y1 > py and (x1 - x0) * (py - y0) - (px - x0) * (y1 - y0) > 0 then + w += 1 + end + elseif y1 <= py and (x1 - x0) * (py - y0) - (px - x0) * (y1 - y0) < 0 then + w -= 1 + end + x0, y0 = x1, y1 + end + end + return w +end + +local rand = T.rng(7) +local function rf(a: number, b: number): number + return a + (b - a) * rand(100000) / 100000 +end + +local worst, total, count = 0, 0, 0 +for case = 1, 24 do + local p = R.path() + for _ = 1, 1 + rand(3) do + p:moveTo(rf(0, 28), rf(0, 28)) + for _ = 1, 2 + rand(5) do + local k = rand(3) + if k == 0 then + p:lineTo(rf(0, 28), rf(0, 28)) + elseif k == 1 then + p:quadTo(rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28)) + else + p:cubicTo(rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28)) + end + end + p:close() + end + local ang = rf(0, 6.28) + local tr = R.multiply(R.translate(rf(-5, 5), rf(-5, 5)), R.multiply(R.rotate(ang), R.scale(rf(0.5, 1.2), rf(0.5, 1.2)))) + local rule = if case % 2 == 0 then "evenodd" else "nonzero" + local clip = { 0, 0, 32, 32 } + local m = R.mask(p, { transform = tr, rule = rule :: any, clip = clip, tolerance = 0.05 }) + local polys = R.flatten(p, tr, 0.01) + local err, n, mx = 0, 0, 0 + for y = 0, 31 do + for x = 0, 31 do + local inside = 0 + for sy = 0, 11 do + for sx = 0, 11 do + local w = wind(polys, x + (sx + 0.5) / 12, y + (sy + 0.5) / 12) + if (rule == "nonzero" and w ~= 0) or (rule == "evenodd" and w % 2 == 1) then + inside += 1 + end + end + end + local want = inside / 144 + local got = if m then at(m, x, y) / 255 else 0 + local d = math.abs(got - want) + err += d + n += 1 + if d > mx then + mx = d + end + end + end + total += err + count += n + worst = math.max(worst, err / n) + -- the area rules approximate where edges of opposite winding meet inside one pixel; on average they agree + t:check(err / n < 0.015, string.format("case %d (%s): mean abs error %.4f (max %.3f)", case, rule, err / n, mx)) +end +t:note("random paths: mean abs coverage error %.4f (worst case mean %.4f) vs 12x12 supersampling", total / count, worst) + +-- 4. even-odd vs nonzero on two nested squares of the same orientation +do + local p = R.path():rect(0, 0, 10, 10):rect(3, 3, 4, 4) + t:check(math.abs(sum(R.mask(p)) - 100) < 0.01, "nonzero fills the hole") + t:check(math.abs(sum(R.mask(p, { rule = "evenodd" })) - 84) < 0.01, "evenodd leaves the hole") + -- opposite orientation: a hole under both rules + local q = R.path():rect(0, 0, 10, 10):moveTo(3, 3):lineTo(3, 7):lineTo(7, 7):lineTo(7, 3):close() + t:check(math.abs(sum(R.mask(q)) - 84) < 0.01, "nonzero hole with opposite winding") +end + +-- 5. clipping: a shape larger than the clip, partly outside on every side +do + local m = R.mask(R.path():rect(-20.5, -3.25, 100, 50), { clip = { 0, 0, 16, 8 } }) :: any + t:check(m and m.x == 0 and m.y == 0 and m.width == 16 and m.height == 8, "clipped bounds") + t:check(math.abs(sum(m) - 128) < 0.01, "clipped area " .. sum(m)) + local m2 = R.mask(R.path():moveTo(-50, 4):lineTo(60, 4.5):lineTo(60, 6):lineTo(-50, 5):close(), { clip = { 0, 0, 10, 10 } }) + t:check(m2 ~= nil, "a sliver crossing the clip") + t:check(R.mask(R.path():rect(20, 20, 5, 5), { clip = { 0, 0, 10, 10 } }) == nil, "outside the clip is empty") +end + +-- 6. strokes: a line of length L and width w covers L*w (butt), L*w + w^2 (square), L*w + pi w^2/4 (round) +do + local line = R.path():moveTo(5, 10):lineTo(35, 10) + local a = sum(R.mask(R.stroke(line, { width = 4 }))) + t:check(math.abs(a - 120) < 0.05, "butt stroke area " .. a) + a = sum(R.mask(R.stroke(line, { width = 4, cap = "square" }))) + t:check(math.abs(a - 136) < 0.05, "square cap area " .. a) + a = sum(R.mask(R.stroke(line, { width = 4, cap = "round", tolerance = 0.01 }))) + t:check(math.abs(a - (120 + math.pi * 4)) < 0.3, "round cap area " .. a) + -- a closed square outline of side 20, width 2, miter joins: outer 22^2 - inner 18^2 + local sq = R.path():rect(10, 10, 20, 20) + a = sum(R.mask(R.stroke(sq, { width = 2 }))) + t:check(math.abs(a - (484 - 324)) < 0.1, "mitered square outline " .. a) + a = sum(R.mask(R.stroke(sq, { width = 2, join = "bevel" }))) + t:check(math.abs(a - (160 - 4 * 0.5)) < 0.1, "bevelled square outline " .. a) + a = sum(R.mask(R.stroke(sq, { width = 2, join = "round", tolerance = 0.01 }))) + t:check(math.abs(a - (160 - 4 * (1 - math.pi / 4))) < 0.15, "rounded square outline " .. a) + -- a sharp zig-zag past the miter limit falls back to bevels; still covered without holes + local zig = R.path():moveTo(0, 0):lineTo(20, 2):lineTo(0, 4) + t:check(sum(R.mask(R.stroke(zig, { width = 1, miterLimit = 4 }))) > 30, "zig-zag stroke") + -- a curve stroke: a circle outline of radius 10, width 1: area 2 pi r w + a = sum(R.mask(R.stroke(R.path():ellipse(20, 20, 10, 10), { width = 1, join = "round", tolerance = 0.01 }))) + t:check(math.abs(a - 2 * math.pi * 10) < 1, "circle outline " .. a) +end + +-- 7. fill onto an image: colours, opacity, paint functions, compositing over existing pixels +do + local img = Types.Image.new(8, 8) + t:check(R.fill(img, R.path():rect(0, 0, 4, 8), { 255, 0, 0, 255 }), "fill red") + t:eq(buffer.readu32(img.pixels, 0), 0xFF0000FF, "opaque red pixel") + t:eq(buffer.readu32(img.pixels, 4 * 5), 0, "untouched pixel") + R.fill(img, R.path():rect(2, 0, 4, 8), { 0, 0, 255, 255 }, { opacity = 0.5 }) + local p = 4 * 3 + t:check(buffer.readu8(img.pixels, p) == 128 and buffer.readu8(img.pixels, p + 2) == 128 and buffer.readu8(img.pixels, p + 3) == 255, "half blue over red") + p = 4 * 5 + t:check(buffer.readu8(img.pixels, p + 2) == 255 and buffer.readu8(img.pixels, p + 3) == 128, "half blue over transparent") + local calls = 0 + R.fill(img, R.path():rect(0, 7, 8, 1), function(x: number, _y: number) + calls += 1 + return x * 30, 0, 0, 255 + end) + t:eq(calls, 8, "paint function per covered pixel") + t:eq(buffer.readu8(img.pixels, (7 * 8 + 2) * 4), math.floor(2.5 * 30 + 0.5), "paint at the pixel centre") + -- a transform scaling a unit square to the whole image + local img2 = Types.Image.new(4, 4) + R.fill(img2, R.path():rect(0, 0, 1, 1), { 0, 255, 0, 255 }, { transform = R.scale(4) }) + t:eq(buffer.readu32(img2.pixels, 4 * 15), 0xFF00FF00, "transformed fill") + local inv = R.invert({ 2, 0, 0, 4, 3, 5 }) :: any + local x, y = R.apply(inv, R.apply({ 2, 0, 0, 4, 3, 5 }, 7, 11)) + t:check(math.abs(x - 7) < 1e-9 and math.abs(y - 11) < 1e-9, "invert") + t:check(R.fill(img2, R.path():rect(0, 0, 1, 1), function() + error("boom") + end) == false, "a failing paint function returns false") +end + +-- 8. malformed paths and huge / non-finite coordinates never throw +do + local bad: { any } = { + { { op = "moveTo" }, { op = "lineTo", 1 }, { op = "quadTo", 1, 2, "x", 4 }, { op = "close" } }, + { { op = "lineTo", 0 / 0, 1 }, { op = "lineTo", 5, 5 }, { op = "lineTo", 0, 5 } }, + { { op = "moveTo", 0, 0 }, { op = "lineTo", math.huge, 1 }, { op = "lineTo", 1, 1e300 } }, + { { op = "moveTo", -1e6, -1e6 }, { op = "lineTo", 1e6, -1e6 }, { op = "lineTo", 1e6, 1e6 } }, + { 5, "x", { op = "cubicTo" }, { op = 3 } }, + {}, + } + local threw = 0 + for i, p in bad do + for _, rule in { "nonzero", "evenodd" } do + local ok = pcall(function() + R.mask(p, { rule = rule :: any, clip = { 0, 0, 64, 64 } }) + R.mask(p, { transform = { 0 / 0, 0, 0, 1, 0, 0 } }) + R.stroke(p, { width = 3, cap = "round", join = "round" }) + R.fill(Types.Image.new(16, 16), p, { 1, 2, 3, 4 }, { transform = { 1e9, 0, 0, 1e9, 0, 0 } }) + end) + if not ok then + threw += 1 + print(" threw on bad path " .. i) + end + end + end + local _, why = R.mask(R.path():rect(0, 0, 5000, 5000), { maxPixels = 1000 }) + t:eq(why, "limit", "over maxPixels") + t:check(R.mask("nope") == nil and R.mask(nil) == nil, "non-paths") + -- random command soup through the fuzz helper: bytes -> commands + t:fuzz("mask", function(b: buffer) + local cmds = {} + local ops = { "moveTo", "lineTo", "quadTo", "cubicTo", "close" } + local i = 0 + while i + 1 < buffer.len(b) do + local c: any = { op = ops[buffer.readu8(b, i) % 5 + 1] } + for k = 1, 6 do + local q = i + k + c[k] = if q < buffer.len(b) then (buffer.readi8(b, q)) * 0.73 else 0 + end + table.insert(cmds, c) + i += 7 + end + R.mask(cmds, { rule = if buffer.len(b) % 2 == 0 then "evenodd" else "nonzero", clip = { -10, -10, 40, 40 } }) + return R.stroke(cmds, { width = 2.5, cap = "square", join = "miter" }) + end, { "\0\1\2\3\4\5\6\1\9\9\9\9\9\9\2\1\2\3\4\5\6\3\1\2\3\4\5\6\4" }, { garbage = 400 }) + t:eq(threw, 0, "malformed paths never throw") +end + +t:done()