merge ws/vec: svg (+raster), psd, aseprite, tiled, srt/vtt/ass, codecs/Blend, core/Base64, ops/LayerOps

This commit is contained in:
4DBug committed 2026-10-31 09:12:40 -05:00
commit 9821cd129b
38 files changed
+9899 -5

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
-- core/Base64 tests: the RFC 4648 vectors, whitespace / missing padding / URL-safe input, bad characters, random
-- round trips.
local T = require("@tests/T")
local Base64 = require("@formats/core/Base64")
local t = T.suite("base64")
for _, v in { { "", "" }, { "f", "Zg==" }, { "fo", "Zm8=" }, { "foo", "Zm9v" }, { "foob", "Zm9vYg==" }, { "fooba", "Zm9vYmE=" }, { "foobar", "Zm9vYmFy" } } do
t:eq(Base64.encode(v[1]), v[2], "encode " .. v[1])
t:eq(buffer.tostring(Base64.decode(v[2]) :: buffer), v[1], "decode " .. v[2])
end
t:eq(buffer.tostring(Base64.decode(" Zm9v\nYmE ") :: buffer), "fooba", "whitespace and no padding")
t:eq(buffer.tostring(Base64.decode("-_8=") :: buffer), "\251\255", "URL-safe alphabet")
local b, err = Base64.decode("Zm9v!")
t:check(b == nil and err, "bad character")
local b2 = Base64.decode("Zg==Zg")
t:check(b2 == nil, "data after padding")
local rand = T.rng(5)
for n = 0, 40 do
local s = buffer.create(n)
for i = 0, n - 1 do
buffer.writeu8(s, i, rand(256))
end
t:eq(buffer.tostring(Base64.decode(Base64.encode(s)) :: buffer), buffer.tostring(s), "round trip " .. n)
end
t:done()
+172
View File
@@ -0,0 +1,172 @@
-- layered/aseprite tests: sprites written by tools/fixtures/aseprite.py (RGBA / grayscale / indexed; raw, zlib and
-- linked cels; groups, hidden layers, blend modes, layer and cel opacity; old and new palettes; tags; user data) and
-- by LibreSprite (re-saved and from a GIF): every cel's pixels and position, and our flatten of every frame against
-- LibreSprite's rendering (PSNR); our encoder's sprite rendered by LibreSprite (tools/fixtures/_ours.luau); round
-- trips (linked cels kept), the contract and the fuzz pass. Fixtures: tools/fixtures/aseprite.py.
local T = require("@tests/T")
local Ase = require("@formats/layered/aseprite")
local LayerOps = require("@formats/ops/LayerOps")
local Types = require("@formats/Types")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/aseprite")
local Ours = require("@tests/gen/aseprite_ours")
local t = T.suite("aseprite")
local function decode(s: string | buffer, opts: any?): (any, any)
local b = if type(s) == "string" then buffer.fromstring(s) else s
return Ase.decode(Bytes.reader(b), opts)
end
local function psnr(a: buffer, b: string): number
local n = math.min(buffer.len(a), #b)
local se = 0
for i = 0, n - 1, 4 do
local aa, ab = buffer.readu8(a, i + 3), string.byte(b, i + 4)
for k = 0, 2 do
local d = (buffer.readu8(a, i + k) * aa - string.byte(b, i + k + 1) * ab) / 255
se += d * d
end
se += (aa - ab) * (aa - ab)
end
if se == 0 then
return 99
end
return 10 * math.log10(255 * 255 / (se / n))
end
-- the n-th node (groups included, file order) of a frame's tree
local function nodes(layers: { any }, out: { any }?): { any }
local o = out or {}
for _, l in layers do
table.insert(o, l)
if l.children then
nodes(l.children, o)
end
end
return o
end
t:eq(Ase.name, "aseprite", "name")
t:eq(Ase.category, "layered", "category")
t:check(Ase.caps.decode and Ase.caps.encode, "caps")
local samples = {}
for _, c in Fx.cases do
local doc, err = decode(c.data)
t:check(doc, c.name .. ": " .. tostring(err))
t:check(doc.width == c.width and doc.height == c.height, c.name .. ": size")
t:eq(#doc.frames, c.nframes, c.name .. ": frames")
for _, cel in c.cels do
local l = nodes(doc.frames[cel.frame].layers)[cel.layer]
local label = string.format("%s: frame %d layer %d", c.name, cel.frame, cel.layer)
t:check(l and l.x == cel.x and l.y == cel.y and l.image.width == cel.w and l.image.height == cel.h, label .. ": position / size")
t:eq(Crc32.of(l.image.pixels), cel.crc, label .. ": pixels")
end
-- our flatten vs LibreSprite's rendering of each frame
for fi, want in c.frames do
local img = LayerOps.flatten(doc, { frame = fi }) :: any
local p = psnr(img.pixels, want)
t:check(p >= 40, string.format("%s: frame %d vs LibreSprite: %.1f dB", c.name, fi, p))
if p < 99 then
t:note("%s frame %d: flatten vs LibreSprite %.1f dB", c.name, fi, p)
end
end
table.insert(samples, c.data)
end
-- the hand-made RGBA sprite's details
do
local doc = decode(Fx.cases[1].data)
local L = doc.layers
t:eq(#L, 4, "top level: Background, Group, Hidden, Top")
t:eq(L[2].name, "Group", "group")
t:eq(#L[2].children, 2, "group children")
t:eq(L[2].children[1].blend, "multiply", "blend")
t:eq(math.floor(L[2].children[1].opacity * 255 + 0.5), 200, "layer opacity")
t:eq(math.floor(L[2].children[2].fillOpacity * 255 + 0.5), 128, "cel opacity -> fillOpacity")
t:eq(L[3].visible, false, "hidden")
t:eq(L[2].children[1].userData.text, "mul layer", "layer user data")
t:eq(L[2].children[1].userData.color[4], 4, "user data colour")
t:eq(L[2].children[1].celUserData.text, "a cel", "cel user data")
t:eq(doc.frames[2].delay, 0.15, "frame delay")
t:check(doc.frames[3].layers[1].image == L[1].image and doc.frames[3].layers[1].link == 1, "linked cel shares the image")
t:eq(#doc.meta.tags, 2, "tags")
t:check(doc.meta.tags[2].name == "back" and doc.meta.tags[2].from == 2 and doc.meta.tags[2].to == 3 and doc.meta.tags[2].direction == "pingpong" and doc.meta.tags[2]["repeat"] == 3, "tag fields")
t:eq(doc.meta.tags[1].userData.text, "walk tag", "tag user data")
t:eq(#doc.meta.palette, 16, "palette")
t:eq(doc.meta.paletteNames[4], "fourth", "palette names")
t:eq(doc.meta.colorDepth, 32, "depth")
local idx = decode(Fx.cases[3].data)
t:eq(#idx.meta.palette, 5, "old palette chunk")
t:eq(idx.meta.colorDepth, 8, "indexed")
-- round trips: every frame's nodes and pixels, linked cels stay shared, depth kept
for ci, c in Fx.cases do
local d = decode(c.data)
local out, eerr = Ase.encode(d)
t:check(out, c.name .. ": encode: " .. tostring(eerr))
local back = decode(out :: buffer)
t:check(back, c.name .. ": decode ours")
t:eq(#back.frames, #d.frames, c.name .. ": rt frames")
t:eq(back.meta.colorDepth, d.meta.colorDepth, c.name .. ": rt depth")
for fi, f in d.frames do
local a, b = nodes(f.layers), nodes(back.frames[fi].layers)
t:eq(#b, #a, c.name .. ": rt nodes")
for k, l in a do
t:eq(b[k].name, l.name, "rt name")
t:check(buffer.tostring(b[k].image.pixels) == buffer.tostring(l.image.pixels), c.name .. ": rt pixels " .. l.name .. " frame " .. fi)
t:check(b[k].x == l.x and b[k].y == l.y, "rt position")
t:eq(b[k].visible, l.visible, "rt visible")
t:eq(b[k].fillOpacity, l.fillOpacity, "rt cel opacity")
if not l.children then
t:eq(b[k].blend, l.blend, "rt blend")
end
end
t:eq(back.frames[fi].delay, f.delay, "rt delay")
end
if ci == 1 then
t:check(back.frames[3].layers[1].image == back.layers[1].image, "rt: linked cel written as a link")
t:eq(back.meta.tags[2].direction, "pingpong", "rt tags")
t:eq(back.meta.paletteNames[1], "first", "rt palette names")
end
table.insert(samples, buffer.tostring(out :: buffer))
end
-- forced depths
local _, e = Ase.encode(doc, { depth = 16 })
t:check(e and e.code == Err.ARG, "colour sprite as grayscale: " .. tostring(e))
local g = decode(Fx.cases[2].data)
local g32 = decode(Ase.encode(g, { depth = 32 }) :: buffer)
t:eq(g32.meta.colorDepth, 32, "grayscale written as RGBA")
end
-- LibreSprite renders our encoder's sprite like our flatten does
t:eq(#Ours.frames, Ours.nframes, "LibreSprite read every frame of our sprite")
for fi, want in Ours.frames do
local ours = Ours.ours[fi]
local p = psnr(buffer.fromstring(ours), want)
t:check(p >= 40, string.format("our sprite frame %d: LibreSprite vs our flatten %.1f dB", fi, p))
t:note("our sprite frame %d: LibreSprite vs our flatten %.1f dB", fi, p)
end
-- a Layered without frames is one frame
do
local d = Types.Layered.new(4, 3)
d.layers = { Types.Layered.layer("only", Types.Image.new(2, 2), 1, 1) }
local back = decode(Ase.encode(d) :: buffer)
t:check(back and #back.frames == 1 and back.layers[1].name == "only" and back.layers[1].x == 1, "single frame")
local _, e = Ase.encode({ width = 4, height = 4, layers = { { name = "x" } } } :: any)
t:check(e and e.code == Err.ARG, "layer without an image")
local _, e2 = decode("\0\0\0\0\224\165")
t:check(e2 and e2.code == Err.TRUNCATED, "short header")
local bad = buffer.fromstring(Fx.cases[1].data)
buffer.writeu16(bad, 12, 24)
local _, e3 = decode(bad)
t:check(e3 and e3.code == Err.CORRUPT, "bad depth")
t:eq(Ase.sniff(Bytes.reader(buffer.fromstring(Fx.cases[1].data))), 1, "sniff")
end
t:fuzz("decode", function(b: buffer)
return Ase.decode(Bytes.reader(b))
end, samples, { mutations = 30, keepHeader = 6 })
t:done()
+184
View File
@@ -0,0 +1,184 @@
-- layered/psd tests: PSD / PSB files of every colour mode and depth, compression, groups, pass-through, clipping,
-- masks, fill opacity and blend mode (written by tools/fixtures/psd.py) plus an ImageMagick PSD, against psd-tools:
-- the merged image and every layer's pixels exact (8-bit; 16 / 32-bit within rounding), our flatten (ops/LayerOps)
-- against psd-tools' composite by PSNR; our encoder's PSD read back by psd-tools (tools/fixtures/_ours.luau), round
-- trips, the contract and the fuzz pass. Fixtures: tools/fixtures/psd.py.
local T = require("@tests/T")
local Psd = require("@formats/layered/psd")
local LayerOps = require("@formats/ops/LayerOps")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/psd")
local Ours = require("@tests/gen/psd_ours")
local t = T.suite("psd")
local function decode(s: string | buffer, opts: any?): (any, any)
local b = if type(s) == "string" then buffer.fromstring(s) else s
return Psd.decode(Bytes.reader(b), opts)
end
-- PSNR of two rgba8 buffers, colours premultiplied by alpha (the colour of a transparent pixel does not matter);
-- identical -> 99
local function psnr(a: buffer, b: string, opaque: boolean?): number
local n = math.min(buffer.len(a), #b)
local se = 0
for i = 0, n - 1, 4 do
local aa, ab = buffer.readu8(a, i + 3), string.byte(b, i + 4)
if opaque then
aa, ab = 255, 255
end
for k = 0, 2 do
local d = (buffer.readu8(a, i + k) * aa - string.byte(b, i + k + 1) * ab) / 255
se += d * d
end
se += (aa - ab) * (aa - ab)
end
if se == 0 then
return 99
end
return 10 * math.log10(255 * 255 / (se / n))
end
local function leaves(layers: any): { any }
local out = {}
for l in LayerOps.leaves(layers) do
table.insert(out, l)
end
return out
end
t:eq(Psd.name, "psd", "name")
t:eq(Psd.category, "layered", "category")
t:check(Psd.caps.decode and Psd.caps.encode, "caps")
-- PSNR floors for our flatten vs psd-tools' composite: blend modes where psd-tools' formulas differ from the W3C ones
-- (Photoshop's own differ from both) get a lower bar
local LOW = { ["blend-diss"] = 8, ["blend-hMix"] = 15, ["blend-sLit"] = 30, ["blend-vLit"] = 25, ["blend-lLit"] = 30, ["blend-pLit"] = 30, ["blend-div"] = 30, ["blend-idiv"] = 30, ["blend-fdiv"] = 25, ["blend-hue"] = 25, ["blend-sat"] = 25, ["blend-colr"] = 25, ["blend-lum"] = 25 }
local samples = {}
for _, c in Fx.cases do
local doc, err = decode(c.data)
t:check(doc, c.name .. ": " .. tostring(err))
t:eq(doc.kind, "layered", c.name .. ": kind")
t:check(doc.width == c.width and doc.height == c.height, c.name .. ": size")
local comp = doc.meta.composite
if #c.composite > 0 then
local src = doc.meta.source
local exact = (src.bitDepth == 8 or src.bitDepth == 1) and src.colorMode ~= "lab" and src.colorMode ~= "cmyk"
if exact then
t:check(buffer.tostring(comp.pixels) == c.composite, c.name .. ": merged image = psd-tools")
else
-- (PIL turns Lab into RGBA with alpha 0: compare the colours only)
local p = psnr(comp.pixels, c.composite, src.colorMode == "lab")
-- 16 / 32 bits: rounding; CMYK / Lab: different conversions (ours: naive CMYK, D65 Lab)
local floor = if src.colorMode == "lab" then 20 elseif src.colorMode == "cmyk" then 30 else 45
t:check(p > floor, string.format("%s: merged image PSNR %.1f", c.name, p))
t:note("%s: merged image vs psd-tools %.1f dB", c.name, p)
end
end
-- layers, in order, against psd-tools
local ours = leaves(doc.layers)
local ref = {}
for _, l in c.layers do
if not l.group then
table.insert(ref, l)
end
end
t:eq(#ours, #ref, c.name .. ": leaf count")
for i, r in ref do
local l = ours[i]
t:eq(l.name, r.name, c.name .. ": layer name")
if r.width > 0 then
t:check(l.x == r.left and l.y == r.top and l.image.width == r.width and l.image.height == r.height, c.name .. ": " .. r.name .. ": bounds")
end
if r.crc and doc.meta.source.bitDepth == 8 then
t:eq(Crc32.of(l.image.pixels), r.crc, c.name .. ": " .. r.name .. ": pixels")
end
end
-- our flatten vs psd-tools' composite
if c.flat and #ours > 0 then
local flat = LayerOps.flatten(doc) :: any
local p = psnr(flat.pixels, c.flat)
local floor = LOW[c.name] or 38
t:check(p >= floor, string.format("%s: flatten PSNR %.1f dB (floor %d)", c.name, p, floor))
if p < 99 then
t:note("%s: flatten vs psd-tools %.1f dB", c.name, p)
end
end
if #samples < 8 and (c.name == "rgb-layers" or c.name == "psb" or c.name == "rgb16-lr16" or c.name == "gray" or c.name == "indexed" or c.name == "bitmap" or c.name == "rgb32" or c.name == "cmyk") then
table.insert(samples, c.data)
end
end
-- the full document's structure
do
local doc
for _, c in Fx.cases do
if c.name == "rgb-layers" then
doc = decode(c.data)
end
end
local L = doc.layers
t:eq(#L, 8, "top level: bg, multiply, isolated, pass, base, clipped, masked, fill")
t:eq(L[2].blend, "multiply", "blend")
t:eq(math.floor(L[2].opacity * 255 + 0.5), 200, "opacity")
t:eq(L[3].name, "Isolated", "group name")
t:eq(L[3].blend, "normal", "isolated group blend")
t:eq(#L[3].children, 2, "group children")
t:eq(L[4].blend, "passThrough", "pass-through group")
t:eq(L[4].children[1].name, "Diff \u{e9}\u{65e5}", "unicode name (luni)")
t:eq(L[4].children[2].visible, false, "hidden layer")
t:eq(L[6].clip, true, "clipping layer")
t:check(L[7].mask and L[7].mask.image.format == "gray8" and L[7].mask.x == 8 and L[7].mask.y == 5, "mask")
t:eq(math.floor(L[8].fillOpacity * 255 + 0.5), 128, "fill opacity")
local only = decode(Fx.cases[1].data, { layers = false })
t:check(only and #only.layers == 0 and only.meta.composite, "layers = false: merged image only")
-- round trip: our PSD of the decoded document decodes to the same layers, and its merged image is our flatten
local out, eerr = Psd.encode(doc)
t:check(out, "encode: " .. tostring(eerr))
local back = decode(out :: buffer)
t:check(back, "decode our PSD")
local a, b = leaves(doc.layers), leaves(back.layers)
t:eq(#b, #a, "round trip: leaves")
for i, l in a do
t:eq(b[i].name, l.name, "rt name")
t:check(buffer.tostring(b[i].image.pixels) == buffer.tostring(l.image.pixels), "rt pixels " .. l.name)
t:check(b[i].x == l.x and b[i].y == l.y, "rt position")
t:eq(b[i].blend, l.blend, "rt blend")
t:eq(b[i].visible, l.visible, "rt visible")
t:eq(b[i].clip, l.clip, "rt clip")
t:eq(b[i].opacity, l.opacity, "rt opacity")
end
t:eq(back.layers[4].blend, "passThrough", "rt pass-through group")
t:check(back.layers[7].mask and buffer.tostring(back.layers[7].mask.image.pixels) == buffer.tostring(L[7].mask.image.pixels), "rt mask")
local flat = LayerOps.flatten(doc) :: any
-- the merged image is stored matted with white (as Photoshop does): exact where opaque, rounding elsewhere
local p = psnr(back.meta.composite.pixels, buffer.tostring(flat.pixels))
t:check(p > 45, string.format("rt merged = flatten (%.1f dB)", p))
table.insert(samples, buffer.tostring(out :: buffer))
end
-- psd-tools reads our encoder's PSD (checked when the fixtures were made)
for _, c in Ours.checks do
t:check(c.ok, "psd-tools on our PSD: " .. c.label)
end
t:note("psd-tools agrees with our PSD on %d facts", #Ours.checks)
-- errors
do
local _, e = decode("8BPS\0\1\0\0\0\0\0\0\0\3\0\0\0\10\0\0\0\10\0\8\0\3")
t:check(e and e.code == Err.TRUNCATED, "truncated after the header: " .. tostring(e))
local _, e2 = decode("8BPS\0\1\0\0\0\0\0\0\0\3\0\0\0\10\0\0\0\10\0\7\0\3")
t:check(e2 and e2.code == Err.CORRUPT, "bad depth: " .. tostring(e2))
local _, e3 = decode(Fx.cases[1].data, { maxPixels = 100 })
t:check(e3 and e3.code == Err.LIMIT, "maxPixels")
t:eq(Psd.sniff(Bytes.reader(buffer.fromstring("8BPS\0\1"))), 1, "sniff")
t:eq(Psd.sniff(Bytes.reader(buffer.fromstring("8BPS\0\3"))), 0, "sniff version 3")
local _, e4 = Psd.encode({ width = 4, height = 4, layers = { { name = "x" } } } :: any)
t:check(e4 and e4.code == Err.ARG, "encode: layer without an image")
end
t:fuzz("decode", function(b: buffer)
return Psd.decode(Bytes.reader(b))
end, samples, { mutations = 30, keepHeader = 4 })
t:done()
+144
View File
@@ -0,0 +1,144 @@
-- ops/LayerOps + codecs/Blend tests: blend mode formulas on single pixels against hand-computed W3C values, opacity,
-- masks, clipping, isolated vs pass-through groups, hidden layers, frames, leaves, bad arguments. (Whole-document
-- flattening against psd-tools is in tests/layered/psd.luau.)
local T = require("@tests/T")
local LayerOps = require("@formats/ops/LayerOps")
local Blend = require("@formats/codecs/Blend")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local t = T.suite("layerops")
local function px(r: number, g: number, b: number, a: number): Types.Image
local img = Types.Image.new(1, 1)
buffer.writeu8(img.pixels, 0, r)
buffer.writeu8(img.pixels, 1, g)
buffer.writeu8(img.pixels, 2, b)
buffer.writeu8(img.pixels, 3, a)
return img
end
local function get(img: any): (number, number, number, number)
local p = img.pixels
return buffer.readu8(p, 0), buffer.readu8(p, 1), buffer.readu8(p, 2), buffer.readu8(p, 3)
end
local function doc(layers: { any }): any
local d = Types.Layered.new(1, 1)
d.layers = layers
return d
end
local L = Types.Layered.layer
-- separable modes on opaque pixels: backdrop (200, 100, 50), source (100, 150, 250); values from the W3C formulas
local cases = {
normal = { 100, 150, 250 },
multiply = { 78, 59, 49 },
screen = { 222, 191, 251 },
darken = { 100, 100, 50 },
lighten = { 200, 150, 250 },
difference = { 100, 50, 200 },
exclusion = { 143, 132, 202 },
linearDodge = { 255, 250, 255 },
linearBurn = { 45, 0, 45 },
subtract = { 100, 0, 0 },
overlay = { 188, 118, 98 },
hardLight = { 157, 127, 247 },
colorDodge = { 255, 243, 255 },
colorBurn = { 115, 0, 46 },
hardMix = { 255, 0, 255 },
}
for mode, want in cases do
local top = L("top", px(100, 150, 250, 255))
top.blend = mode
local img = LayerOps.flatten(doc({ L("bottom", px(200, 100, 50, 255)), top })) :: any
local r, g, b, a = get(img)
t:check(math.abs(r - want[1]) <= 1 and math.abs(g - want[2]) <= 1 and math.abs(b - want[3]) <= 1 and a == 255, string.format("%s: got %d %d %d, want %d %d %d", mode, r, g, b, want[1], want[2], want[3]))
end
-- non-separable: luminosity of the source on the backdrop's hue
do
local top = L("top", px(255, 255, 255, 255))
top.blend = "luminosity"
local r, g, b = get(LayerOps.flatten(doc({ L("bottom", px(255, 0, 0, 255)), top })))
t:check(r == 255 and g == 255 and b == 255, "luminosity of white")
top.blend = "color"
local r2, g2, b2 = get(LayerOps.flatten(doc({ L("bottom", px(128, 128, 128, 255)), top })))
t:check(r2 == g2 and g2 == b2 and math.abs(r2 - 128) <= 1, "colour of a grey source keeps the grey")
end
-- opacity and alpha: 50% red over opaque blue
do
local top = L("top", px(255, 0, 0, 255))
top.opacity = 0.5
local r, g, b, a = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))
t:check(math.abs(r - 128) <= 1 and g == 0 and math.abs(b - 128) <= 1 and a == 255, "opacity mix")
local r2, _, _, a2 = get(LayerOps.flatten(doc({ top })))
t:check(r2 == 255 and math.abs(a2 - 128) <= 1, "over transparent: alpha scales")
end
-- hidden layers, masks, clipping
do
local top = L("top", px(255, 0, 0, 255))
top.visible = false
local r = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))
t:eq(r, 0, "hidden layer skipped")
local r2 = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top }), { hidden = true }))
t:eq(r2, 255, "hidden = true includes it")
top.visible = true
local m = Types.Image.new(1, 1, "gray8")
top.mask = { image = m, x = 0, y = 0, default = 255 }
t:eq((get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))), 0, "black mask hides")
top.mask = { image = m, x = 5, y = 5, default = 255 }
t:eq((get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))), 255, "outside the mask: default white")
top.mask = nil
local base = L("base", px(0, 255, 0, 0)) -- transparent base: the clipped layer shows nowhere
top.clip = true
local r3, g3, b3, a3 = get(LayerOps.flatten(doc({ base, top })))
t:check(a3 == 0, "clipped to a transparent base: " .. r3 .. g3 .. b3 .. a3)
base = L("base", px(0, 255, 0, 255))
local r4, g4 = get(LayerOps.flatten(doc({ base, top })))
t:check(r4 == 255 and g4 == 0, "clipped to an opaque base")
end
-- groups: an isolated multiply group multiplies its composite; pass-through multiplies each child onto the backdrop
do
local child = L("child", px(128, 128, 128, 255))
child.blend = "multiply"
local g = Types.Layered.group("g", { child })
local bottom = L("bottom", px(200, 200, 200, 255))
local r = get(LayerOps.flatten(doc({ bottom, g })))
t:check(math.abs(r - 100) <= 1, "pass-through: child multiplies the backdrop: " .. r)
g.blend = "normal"
local r2 = get(LayerOps.flatten(doc({ bottom, g })))
t:eq(r2, 128, "isolated group: the child multiplies nothing")
g.blend = "passThrough"
g.opacity = 0.5
local r3 = get(LayerOps.flatten(doc({ bottom, g })))
t:check(math.abs(r3 - 150) <= 1, "pass-through opacity mixes before / after: " .. r3)
end
-- frames, leaves, flattenFrames
do
local d = doc({ L("a", px(1, 2, 3, 255)) })
d.frames = { { layers = d.layers, delay = 0.1 }, { layers = { L("b", px(9, 8, 7, 255)) }, delay = 0.2 } }
t:eq((get(LayerOps.flatten(d, { frame = 2 }))), 9, "frame 2")
local anim = LayerOps.flattenFrames(d) :: any
t:check(anim.frames and #anim.frames == 2 and anim.frames[2].delay == 0.2, "flattenFrames")
local _, e = LayerOps.flatten(d, { frame = 5 })
t:check(e and e.code == Err.ARG, "missing frame")
local names = {}
for l, depth in LayerOps.leaves({ L("x", px(0, 0, 0, 0)), Types.Layered.group("g", { L("y", px(0, 0, 0, 0)), Types.Layered.group("h", { L("z", px(0, 0, 0, 0)) }) }) }) do
table.insert(names, (l :: any).name .. depth)
end
t:eq(table.concat(names, " "), "x0 y1 z2", "leaves with depth")
local _, e2 = LayerOps.flatten(5 :: any)
t:check(e2 and e2.code == Err.ARG, "flatten of a non-Layered")
end
-- Blend.composite clips its rectangles (no throw, nothing outside)
do
local dst = buffer.create(4 * 4 * 4)
local src = buffer.create(3 * 3 * 4)
buffer.fill(src, 0, 255)
for _, pos in { { -2, -2 }, { 3, 3 }, { -10, 0 }, { 100, 100 } } do
Blend.composite(dst, 4, 4, src, 3, 3, pos[1], pos[2], 1, "multiply")
end
Blend.composite(dst, 4, 4, src, 3, 3, 0, 0, 1, "nope")
Blend.composite(dst, 4, 4, src, 30, 30, 0, 0, 1, "normal") -- src too short: ignored
t:eq(buffer.readu8(dst, 0), 255, "composite clipping")
t:check(Blend.MODES.softLight and not Blend.MODES.nope, "MODES")
end
t:done()
+109
View File
@@ -0,0 +1,109 @@
-- subtitle/ass tests: ffmpeg's ASS output of a random script (times to the centisecond, text through the override
-- markup), hand-written ASS (styles, comments, commas in text, overrides, [Fonts]) and SSA v4 files against ffmpeg's
-- SRT conversion of them, styles as data, round trips through the encoder, the contract and the fuzz pass.
-- Fixtures: tools/fixtures/subtitles.py.
local T = require("@tests/T")
local Ass = require("@formats/subtitle/ass")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/subtitles")
local t = T.suite("ass")
local function decode(s: string): (any, any)
return Ass.decode(Bytes.reader(buffer.fromstring(s)))
end
local function plain(s: string): string
s = string.gsub(s, "<[^>]*>", "")
s = string.gsub(s, "{[^}]*}", "")
return s
end
local function same(subs: any, want: any, label: string, tol: number)
t:eq(#subs.cues, #want, label .. ": cue count")
for i, w in want do
local c = subs.cues[i]
t:check(math.abs(c.start * 1000 - w.start) <= tol, label .. ": cue " .. i .. " start " .. c.start)
t:check(math.abs(c.stop * 1000 - w.stop) <= tol, label .. ": cue " .. i .. " stop " .. c.stop)
t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text")
end
end
t:eq(Ass.name, "ass", "name")
t:check(Ass.caps.decode and Ass.caps.encode, "caps")
t:eq(Ass.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_ass))), 1, "sniff")
-- ffmpeg converts SRT to ASS with its own rounding (start and duration to centiseconds): within 10 ms
local subs, err = decode(Fx.ffmpeg_ass)
t:check(subs, "ffmpeg ass: " .. tostring(err))
same(subs, Fx.cues, "ffmpeg ass", 10)
t:eq(subs.styles.Default.Fontname, "Arial", "ffmpeg's Default style")
t:eq(subs.meta.scriptInfo.PlayResX, "384", "script info")
for _, h in Fx.hand do
if h.name ~= "vtt" then
local s, e = decode(h.data)
t:check(s, h.name .. ": " .. tostring(e))
same(s, h.cues, h.name .. " vs ffmpeg", 0.5)
end
end
local a = decode(Fx.hand[2].data)
t:eq(a.meta.scriptInfo.Title, "test", "Title")
t:eq(a.meta.scriptInfoOrder[1], "; Script generated by hand", "comment kept in order")
t:eq(a.styles.Top.Fontname, "Verdana", "style field")
t:eq(a.styles.Top.Alignment, "8", "style alignment")
t:eq(a.meta.styleOrder[2], "Top", "style order")
t:eq(a.cues[1].name, "Bob", "actor")
t:eq(a.cues[1].text, "Hello, <i>world</i>!", "italic markup")
t:eq(a.cues[1].raw, "Hello, {\\i1}world{\\i0}!", "raw text")
t:eq(a.cues[2].layer, 1, "layer")
t:eq(a.cues[2].style, "Top", "style")
t:eq(a.cues[2].text, "<b>Bold top</b>\nsecond line", "bold, \\N, an8 dropped")
t:eq(a.cues[3].text, "commas, inside, the text", "commas in the text field")
t:eq(#a.meta.comments, 1, "comment event")
t:eq(a.meta.sections[1].name, "Fonts", "[Fonts] kept")
t:eq(a.meta.sections[1].lines[2], "ABCDEF", "[Fonts] lines")
local ssa = decode(Fx.hand[3].data)
t:eq(ssa.meta.source.scriptType, "v4.00", "SSA script type")
t:eq(ssa.styles.Default.TertiaryColour, "65535", "SSA style field")
t:eq(ssa.cues[1].marked, "Marked=0", "SSA Marked")
-- round trips: the hand files exactly (same fields, same order), and the ffmpeg file through the cues
for _, s in { a, ssa, subs } do
local out = Ass.encode(s) :: buffer
local back = Ass.decode(Bytes.reader(out))
t:check(back, "round trip")
t:eq(#back.cues, #s.cues, "rt count")
for i, c in s.cues do
t:eq(math.floor(back.cues[i].start * 100 + 0.5), math.floor(c.start * 100 + 0.5), "rt start")
t:eq(math.floor(back.cues[i].stop * 100 + 0.5), math.floor(c.stop * 100 + 0.5), "rt stop")
t:eq(back.cues[i].text, c.text, "rt text")
t:eq(back.cues[i].raw, c.raw, "rt raw")
t:eq(back.cues[i].style, c.style, "rt style")
end
for nm, st in s.styles do
for k, v in st do
t:eq(back.styles[nm][k], v, "rt style " .. nm .. "." .. k)
end
end
end
t:eq(buffer.tostring(Ass.encode(a) :: buffer), Fx.hand[2].data, "hand ASS written back byte for byte")
-- cues from another format: markup converted, a Default style made
do
local out = Ass.encode({ kind = "subtitles", cues = { { start = 1, stop = 2.5, text = "<i>it</i> and <b>bold</b>\nline <font color=\"red\">x</font>" } }, styles = {}, meta = {} } :: any) :: buffer
local back = Ass.decode(Bytes.reader(out))
t:eq(back.cues[1].raw, "{\\i1}it{\\i0} and {\\b1}bold{\\b0}\\Nline x", "markup to overrides")
t:check(back.styles.Default ~= nil, "a Default style")
t:eq(back.cues[1].style, "Default", "cue style")
end
do
local _, e = decode("Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,x")
t:check(e and e.code == Err.CORRUPT, "no [Script Info]")
local _, e2 = Ass.encode({ cues = { { start = 0, stop = "x", text = "" } } } :: any)
t:check(e2 and e2.code == Err.ARG, "encode: bad stop")
end
t:fuzz("decode", function(b: buffer)
return Ass.decode(Bytes.reader(b))
end, { Fx.ffmpeg_ass, Fx.hand[2].data, Fx.hand[3].data }, { keepHeader = 13 })
t:done()
+102
View File
@@ -0,0 +1,102 @@
-- subtitle/srt tests: a random SRT script against ffmpeg (its own parse via its srt muxer: times to the millisecond,
-- text), ffmpeg's conversions of WebVTT / ASS / SSA files to SRT, odd layouts (no index, blank lines in text, CRLF,
-- BOM, dot decimals, coordinates), round trips through the encoder, the contract and the fuzz pass.
-- Fixtures: tools/fixtures/subtitles.py.
local T = require("@tests/T")
local Srt = require("@formats/subtitle/srt")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/subtitles")
local t = T.suite("srt")
local function decode(s: string): (any, any)
return Srt.decode(Bytes.reader(buffer.fromstring(s)))
end
local function plain(s: string): string
s = string.gsub(s, "<[^>]*>", "")
s = string.gsub(s, "{[^}]*}", "")
return s
end
local function ms(x: number): number
return math.floor(x * 1000 + 0.5)
end
local function same(subs: any, want: any, label: string)
t:eq(#subs.cues, #want, label .. ": cue count")
for i, w in want do
local c = subs.cues[i]
t:eq(ms(c.start), w.start, label .. ": cue " .. i .. " start")
t:eq(ms(c.stop), w.stop, label .. ": cue " .. i .. " stop")
t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text")
end
end
t:eq(Srt.name, "srt", "name")
t:eq(Srt.category, "subtitle", "category")
t:check(Srt.caps.decode and Srt.caps.encode, "caps")
-- the random script and ffmpeg's re-mux of it
local subs, err = decode(Fx.srt)
t:check(subs, "decode: " .. tostring(err))
same(subs, Fx.cues, "random")
t:eq(subs.cues[3].text, "<u>dog</u>\nalpha dog dog na\195\175ve alpha", "markup and lines kept")
t:eq(subs.cues[1].id, "1", "id")
same(decode(Fx.ffmpeg_srt), Fx.cues, "ffmpeg srt")
t:eq(Srt.sniff(Bytes.reader(buffer.fromstring(Fx.srt))), 0.9, "sniff")
t:eq(Srt.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_vtt))), 0, "sniff a vtt")
for _, h in Fx.hand do
same(decode(h.ffmpeg_srt), h.cues, "ffmpeg " .. h.name .. " -> srt")
end
-- odd layouts
do
local s = "\239\187\1911\r\n00:00:01.5 --> 00:00:02,25 X1:10 X2:20 Y1:5 Y2:6\r\nfirst\r\n\r\nsecond paragraph\r\n\r\n\r\n00:00:03,000 --> 00:00:04,000\r\nno index\r\n2\r\n00:00:05,000-->00:00:06,000\r\n"
local r = decode(s)
t:check(r, "odd layouts")
t:eq(#r.cues, 3, "odd: count")
t:eq(r.cues[1].start, 1.5, "odd: 1-digit fraction")
t:eq(r.cues[1].stop, 2.25, "odd: 2-digit fraction")
t:eq(r.cues[1].text, "first\n\nsecond paragraph", "odd: blank line inside a cue")
t:eq(r.cues[1].settings, "X1:10 X2:20 Y1:5 Y2:6", "odd: coordinates")
t:eq(r.cues[2].text, "no index", "odd: cue without an index, the next index stripped")
t:eq(r.cues[2].id, nil, "odd: no id")
t:eq(r.cues[3].text, "", "odd: empty cue")
local again = decode(buffer.tostring(Srt.encode(r) :: buffer))
t:eq(again.cues[1].text, r.cues[1].text, "odd: round trip keeps the blank line")
t:eq(again.cues[1].settings, r.cues[1].settings, "odd: round trip keeps the coordinates")
end
-- round trips (LF and CRLF)
for _, crlf in { false, true } do
local out = Srt.encode(subs, { crlf = crlf }) :: buffer
local back = Srt.decode(Bytes.reader(out))
t:check(back, "round trip decode")
t:eq(#back.cues, #subs.cues, "round trip count")
for i, c in subs.cues do
t:eq(ms(back.cues[i].start), ms(c.start), "round trip start " .. i)
t:eq(ms(back.cues[i].stop), ms(c.stop), "round trip stop " .. i)
t:eq(back.cues[i].text, c.text, "round trip text " .. i)
end
if not crlf then
t:eq(buffer.tostring(out), Fx.srt, "the encoder writes the canonical file byte for byte")
end
end
-- errors
do
local _, e = decode("just some text\nno timings")
t:check(e and e.code == Err.CORRUPT, "no cues: " .. tostring(e))
local _, e2 = decode("1\n00:00:01,000 --> 00:00:02,000\n\0bin")
t:check(e2 and e2.code == Err.CORRUPT, "NUL bytes")
local empty = decode("")
t:check(empty and #empty.cues == 0, "empty file: no cues")
local _, e3 = Srt.encode({ cues = { { start = -1, stop = 1, text = "x" } } } :: any)
t:check(e3 and e3.code == Err.ARG, "encode: negative time")
local _, e4 = Srt.encode(5 :: any)
t:check(e4 and e4.code == Err.ARG, "encode: not Subtitles")
end
t:fuzz("decode", function(b: buffer)
return Srt.decode(Bytes.reader(b))
end, { Fx.srt, Fx.ffmpeg_srt, Fx.hand[1].ffmpeg_srt })
t:done()
+95
View File
@@ -0,0 +1,95 @@
-- subtitle/vtt tests: ffmpeg's WebVTT output of a random script (times, text), a hand-written file with a header,
-- STYLE / REGION / NOTE blocks, ids, settings and hour timestamps against ffmpeg's SRT conversion of it, round trips
-- through the encoder, the contract and the fuzz pass. Fixtures: tools/fixtures/subtitles.py.
local T = require("@tests/T")
local Vtt = require("@formats/subtitle/vtt")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/subtitles")
local t = T.suite("vtt")
local function decode(s: string): (any, any)
return Vtt.decode(Bytes.reader(buffer.fromstring(s)))
end
local function plain(s: string): string
s = string.gsub(s, "<[^>]*>", "")
s = string.gsub(s, "{[^}]*}", "")
s = string.gsub(s, "&amp;", "&")
return s
end
local function ms(x: number): number
return math.floor(x * 1000 + 0.5)
end
local function same(subs: any, want: any, label: string)
t:eq(#subs.cues, #want, label .. ": cue count")
for i, w in want do
local c = subs.cues[i]
t:eq(ms(c.start), w.start, label .. ": cue " .. i .. " start")
t:eq(ms(c.stop), w.stop, label .. ": cue " .. i .. " stop")
t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text")
end
end
t:eq(Vtt.name, "vtt", "name")
t:check(Vtt.caps.decode and Vtt.caps.encode, "caps")
t:eq(Vtt.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_vtt))), 1, "sniff")
t:eq(Vtt.sniff(Bytes.reader(buffer.fromstring("WEBVTTX"))), 0, "sniff WEBVTTX")
local subs, err = decode(Fx.ffmpeg_vtt)
t:check(subs, "ffmpeg vtt: " .. tostring(err))
same(subs, Fx.cues, "ffmpeg vtt")
local hand
for _, h in Fx.hand do
if h.name == "vtt" then
hand = h
end
end
local v, verr = decode(hand.data)
t:check(v, "hand vtt: " .. tostring(verr))
same(v, hand.cues, "hand vtt vs ffmpeg")
t:eq(v.meta.header, "- a test file\nKind: captions", "header")
t:eq(v.meta.css[1], "::cue { color: yellow }", "STYLE")
t:eq(v.meta.regions[1], "id:r1 width:40%", "REGION")
t:eq(v.meta.notes[1], "this is a comment\nover two lines", "NOTE")
t:eq(v.cues[1].id, "intro", "id")
t:eq(v.cues[1].settings, "align:start position:10%", "settings")
t:eq(v.cues[1].text, "<v Roger>Hello <i>there</i></v>", "text kept")
t:eq(v.cues[3].settings, "line:0", "settings 3")
for _, s in { subs, v } do
local out = Vtt.encode(s) :: buffer
local back = Vtt.decode(Bytes.reader(out))
t:check(back, "round trip")
t:eq(#back.cues, #s.cues, "round trip count")
for i, c in s.cues do
t:eq(ms(back.cues[i].start), ms(c.start), "rt start")
t:eq(ms(back.cues[i].stop), ms(c.stop), "rt stop")
t:eq(back.cues[i].text, c.text, "rt text")
t:eq(back.cues[i].id, c.id, "rt id")
t:eq(back.cues[i].settings, c.settings, "rt settings")
end
t:eq(back.meta.header, s.meta.header, "rt header")
end
do
local back = decode(buffer.tostring(Vtt.encode(v) :: buffer))
t:eq(back.meta.css[1], v.meta.css[1], "rt css")
t:eq(back.meta.regions[1], v.meta.regions[1], "rt region")
-- text that WebVTT cannot hold
local w = Vtt.encode({ kind = "subtitles", cues = { { start = 0, stop = 1, text = "a\n\nb --> c" } }, styles = {}, meta = {} } :: any) :: buffer
local wb = Vtt.decode(Bytes.reader(w))
t:eq(wb.cues[1].text, "a\nb --&gt; c", "blank lines dropped, arrow escaped")
end
do
local _, e = decode("1\n00:00:01,000 --> 00:00:02,000\nx")
t:check(e and e.code == Err.CORRUPT, "no signature")
local _, e2 = Vtt.encode({ cues = { { start = 0, stop = 1 } } } :: any)
t:check(e2 and e2.code == Err.ARG, "encode: cue without text")
end
t:fuzz("decode", function(b: buffer)
return Vtt.decode(Bytes.reader(b))
end, { Fx.ffmpeg_vtt, hand.data }, { keepHeader = 6 })
t:done()
+151
View File
@@ -0,0 +1,151 @@
-- vector/svg tests: hand-written SVGs, one feature area each (shapes, every path command, arcs, transforms, stroke
-- joins / caps / dashes, fill rules, opacity, gradients, href, CSS, use / symbol, viewBox + preserveAspectRatio, nested
-- svg, clip paths, units, colours, inheritance), rasterized by us and compared with resvg by PSNR; our SVG writer's
-- output rendered by resvg against resvg's rendering of the original (tools/fixtures/_ours.luau); path data and
-- colour parsing details; round trips; errors; the fuzz pass. Fixtures: tools/fixtures/svg.py.
local T = require("@tests/T")
local Svg = require("@formats/vector/svg")
local PathData = require("@formats/vector/svg/PathData")
local Style = require("@formats/vector/svg/Style")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/svg")
local t = T.suite("svg")
local function decode(s: string): (any, any)
return Svg.decode(Bytes.reader(buffer.fromstring(s)))
end
-- PSNR over premultiplied RGBA (the colour of transparent pixels does not matter)
local function psnr(a: buffer | string, b: string): number
local sa = if type(a) == "string" then a else buffer.tostring(a)
local n = math.min(#sa, #b)
local se = 0
for i = 1, n, 4 do
local aa, ab = string.byte(sa, i + 3), string.byte(b, i + 3)
for k = 0, 2 do
local d = (string.byte(sa, i + k) * aa - string.byte(b, i + k) * ab) / 255
se += d * d
end
se += (aa - ab) * (aa - ab)
end
if se == 0 then
return 99
end
return 10 * math.log10(255 * 255 / (se / n))
end
t:eq(Svg.name, "svg", "name")
t:eq(Svg.category, "vector", "category")
t:check(Svg.caps.decode and Svg.caps.encode, "caps")
-- antialiasing differs between rasterizers (resvg: tiny-skia's analytic AA; ours: exact area coverage), so edges
-- cost a few dB; the floor catches wrong geometry / paint
local FLOOR = 30
local samples = {}
local worst, worstName = 99, ""
for _, c in Fx.cases do
local v, err = decode(c.svg)
t:check(v, c.name .. ": " .. tostring(err))
t:eq(v.kind, "vector", c.name .. ": kind")
local img = Svg.rasterize(v, c.width, c.height) :: any
t:check(img and img.width == c.width and img.height == c.height, c.name .. ": raster size")
local p = psnr(img.pixels, c.ref)
t:check(p >= FLOOR, string.format("%s: ours vs resvg %.1f dB", c.name, p))
t:note("%-16s ours vs resvg %5.1f dB, resvg(our SVG) vs resvg %5.1f dB", c.name, p, psnr(c.ours_ref, c.ref))
if p < worst then
worst, worstName = p, c.name
end
-- the writer: resvg renders our SVG like the original
t:check(#c.ours > 0, c.name .. ": our encoder wrote SVG")
local wp = psnr(c.ours_ref, c.ref)
t:check(wp >= 35, string.format("%s: resvg on our SVG vs the original %.1f dB", c.name, wp))
-- and we read our own SVG back to the same picture
local back = decode(c.ours)
t:check(back, c.name .. ": decode our SVG")
local img2 = Svg.rasterize(back, c.width, c.height) :: any
t:check(psnr(img2.pixels, buffer.tostring(img.pixels)) >= 40, c.name .. ": our SVG rasterizes like the original")
table.insert(samples, c.svg)
end
t:note("worst: %s %.1f dB", worstName, worst)
-- path data
do
local cmds, ok = PathData.parse("M1.5.5L-2-3e1 1e-1.2zm1,1 h2 v2 a1 1 0 0 1 2 2")
t:check(ok, "parse ok")
t:check(cmds[1].op == "M" and cmds[1][1] == 1.5 and cmds[1][2] == 0.5, "1.5.5 is two numbers")
t:check(cmds[2].op == "L" and cmds[2][1] == -2 and cmds[2][2] == -30, "-2-3e1")
t:check(cmds[3].op == "L" and cmds[3][1] == 0.1 and cmds[3][2] == 0.2, "implicit line-to after an exponent")
t:eq(cmds[4].op, "Z", "close")
t:check(cmds[5].op == "M" and cmds[5][1] == 2.5 and cmds[5][2] == 1.5, "relative move after close is from the start")
t:check(cmds[6].op == "L" and cmds[6][1] == 4.5, "h")
t:eq(cmds[#cmds].op, "C", "arc as cubics")
t:check(math.abs(cmds[#cmds][5] - 6.5) < 1e-9 and math.abs(cmds[#cmds][6] - 5.5) < 1e-9, "arc end point exact")
local part, ok2 = PathData.parse("M0 0 L10 10 L oops")
t:check(not ok2 and #part == 2, "an error keeps the commands before it")
local x0, y0, x1, y1 = PathData.bounds(PathData.parse("M0 0 C 10 -10 20 10 30 0"))
t:check(x0 == 0 and x1 == 30 and math.abs((y0 :: number) + 2.886751) < 1e-4 and math.abs((y1 :: number) - 2.886751) < 1e-4, "cubic bounds")
t:eq(PathData.serialize({ { op = "M", 1, 2.5 }, { op = "C", 0.12345, 1, 2, 3, 4, 5 }, { op = "Z" } }), "M 1 2.5 C 0.1235 1 2 3 4 5 Z", "serialize")
end
-- colours and lengths
do
local function col(s: string): string
local c = Style.color(s)
return if type(c) == "table" then table.concat(c, ",") else tostring(c)
end
t:eq(col("#f80"), "255,136,0,255", "#rgb")
t:eq(col("#ff008080"), "255,0,128,128", "#rrggbbaa")
t:eq(col("rgb(10%, 50%, 90%)"), "26,128,230,255", "rgb %")
t:eq(col("hsl(120, 100%, 25%)"), "0,128,0,255", "hsl")
t:eq(col("RebeccaPurple"), "102,51,153,255", "named, any case")
t:eq(col("none"), "none", "none")
t:eq(col("bogus"), "nil", "not a colour")
t:eq(Style.length("2mm"), 2 * 96 / 25.4, "mm")
t:eq(Style.length("50%", 64), 32, "%")
t:eq(Style.length("1.5em", nil, 10), 15, "em")
local m = Style.transform("translate(10) rotate(90) scale(2 3)") :: { number }
t:check(math.abs(m[1]) < 1e-12 and math.abs(m[2] - 2) < 1e-12 and math.abs(m[3] + 3) < 1e-12 and m[5] == 10, "transform list")
t:eq(Style.transform("translate(1,"), nil, "bad transform")
end
-- the model
do
local v = decode(Fx.cases[1].svg)
t:check(#v.paths == 7, "shapes: one path each")
t:check(v.paths[1].fill.type == "color" and v.paths[1].fill.color[1] == 255, "fill red")
t:eq(v.paths[2].strokeWidth, 2, "stroke width")
local text = decode("<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><text>hi</text><image href='x.png'/><rect width='5' height='5'/></svg>")
t:check(text.meta.unsupported.text == 1 and text.meta.unsupported.image == 1 and #text.paths == 1, "unsupported elements counted")
local ns = decode("<s:svg xmlns:s='http://www.w3.org/2000/svg' width='4' height='4'><s:rect width='4' height='4'/></s:svg>")
t:check(ns and #ns.paths == 1, "prefixed SVG namespace")
-- a round trip keeps the paths
local back = decode(buffer.tostring(Svg.encode(v) :: buffer))
t:eq(#back.paths, #v.paths, "round trip path count")
t:eq(Svg.sniff(Bytes.reader(buffer.fromstring(Fx.cases[1].svg))), 0.95, "sniff")
t:eq(Svg.sniff(Bytes.reader(buffer.fromstring("<html></html>"))), 0, "sniff html")
end
-- errors
do
local _, e = decode("<html/>")
t:check(e and e.code == Err.CORRUPT, "not svg: " .. tostring(e))
local _, e2 = decode("<svg><rect")
t:check(e2 ~= nil, "bad XML")
local _, e3 = Svg.encode({} :: any)
t:check(e3 and e3.code == Err.ARG, "encode a non-Vector")
local _, e4 = Svg.rasterize(decode(Fx.cases[1].svg), 0, 10)
t:check(e4 and e4.code == Err.ARG, "rasterize 0 x 10")
-- hostile: deep use recursion, huge coordinates
local r = decode("<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8'><g id='a'><use href='#a'/><rect width='1e30' height='1e30'/></g></svg>")
t:check(r ~= nil and Svg.rasterize(r, 8, 8) ~= nil, "self-referencing use, huge rect")
end
t:fuzz("decode + rasterize", function(b: buffer)
local v = Svg.decode(Bytes.reader(b))
if v then
return Svg.rasterize(v, 16, 16)
end
return nil
end, samples, { mutations = 4, garbage = 50 })
t:done()
+184
View File
@@ -0,0 +1,184 @@
-- vector/tiled tests: hand-written TMX maps (CSV / base64 zlib / gzip / raw / XML tile data, flip bits, infinite
-- chunks, hexagonal attributes, groups, image layers, every object shape, text, typed properties, embedded and
-- external tilesets with per-tile data) against Tiled's own TMJ export and TMX re-save of them (the same TileMap from
-- all three), a TSX tileset against Tiled's TSJ, our encoder's TMX / TMJ read back by Tiled (tools/fixtures/_ours.luau),
-- round trips in every data encoding, errors, and the fuzz pass. Fixtures: tools/fixtures/tiled.py.
local T = require("@tests/T")
local Tiled = require("@formats/vector/tiled")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/tiled")
local Ours = require("@tests/gen/tiled_ours")
local t = T.suite("tiled")
local function decode(s: string | buffer): (any, any)
local b = if type(s) == "string" then buffer.fromstring(s) else s
return Tiled.decode(Bytes.reader(b))
end
-- deep comparison of decoded maps, without the fields that only say who wrote the file
local SKIP = { version = true, tiledVersion = true, encoding = true, compression = true, meta = true }
local function same(a: any, b: any, path: string, out: { string })
if #out > 8 then
return
end
if type(a) == "table" and type(b) == "table" then
local keys = {}
for k in pairs(a) do
keys[k] = true
end
for k in pairs(b) do
keys[k] = true
end
for k in pairs(keys) do
if not SKIP[k] then
same(a[k], b[k], path .. "." .. tostring(k), out)
end
end
elseif type(a) == "number" and type(b) == "number" then
if math.abs(a - b) > 1e-9 then
table.insert(out, path .. ": " .. a .. " vs " .. b)
end
elseif a ~= b then
table.insert(out, path .. ": " .. tostring(a) .. " vs " .. tostring(b))
end
end
local function eqMap(a: any, b: any, label: string)
local out = {}
same(a, b, "", out)
t:check(#out == 0, label .. ": " .. table.concat(out, "; "))
end
t:eq(Tiled.name, "tiled", "name")
t:eq(Tiled.category, "vector", "category")
t:check(Tiled.caps.decode and Tiled.caps.encode, "caps")
local samples = {}
local maps = {}
for _, c in Fx.cases do
local m, err = decode(c.tmx)
t:check(m, c.name .. ": tmx: " .. tostring(err))
t:eq(m.kind, "tilemap", c.name .. ": kind")
local j, jerr = decode(c.tmj)
t:check(j, c.name .. ": Tiled's tmj: " .. tostring(jerr))
local x, xerr = decode(c.tiled_tmx)
t:check(x, c.name .. ": Tiled's tmx: " .. tostring(xerr))
eqMap(m, j, c.name .. ": hand TMX = Tiled's TMJ")
eqMap(m, x, c.name .. ": hand TMX = Tiled's TMX")
t:eq(Tiled.sniff(Bytes.reader(buffer.fromstring(c.tmx))), 0.9, c.name .. ": sniff tmx")
t:eq(Tiled.sniff(Bytes.reader(buffer.fromstring(c.tmj))), 0.8, c.name .. ": sniff tmj")
maps[c.name] = m
table.insert(samples, c.tmx)
table.insert(samples, c.tmj)
end
-- details of the orthogonal map
do
local m = maps.ortho
t:eq(m.class, "Level", "map class")
t:eq(m.renderOrder, "left-up", "render order")
t:eq(m.backgroundColor, "#102030", "background (canonical: opaque alpha dropped)")
t:eq(m.properties.title, "\u{dc}n\u{ef}code & more", "string property")
t:eq(m.properties.count, 42, "int property")
t:eq(m.properties.ratio, 1.5, "float property")
t:eq(m.properties.on, true, "bool property")
t:eq(m.propertyTypes.tint, "color", "color type")
t:eq(m.properties.target, 3, "object property")
t:eq(m.properties.notes, "line one\nline two", "multi-line property")
t:eq(#m.tilesets, 2, "tilesets")
t:eq(m.tilesets[1].imageSource, "tiles.png", "tileset image stays a path")
t:eq(m.tilesets[1].tiles[2].class, "Door", "tile class")
t:eq(m.tilesets[2].source, "ext.tsx", "external tileset reference")
t:eq(m.tilesets[2].firstGid, 9, "firstgid")
local L = m.layers
t:eq(L[1].data[4], 0x80000000 + 3, "horizontal flip bit kept")
t:eq(L[1].opacity, 0.75, "opacity")
t:eq(L[1].tintColor, "#ff00ff", "tint")
t:eq(L[2].visible, false, "hidden layer")
t:eq(L[2].data[8], 1, "zlib data")
t:eq(L[3].locked, true, "locked")
t:eq(#L[4].data, 24, "raw base64 data")
t:eq(L[5].type, "group", "group")
t:eq(L[5].layers[1].type, "image", "image layer")
t:eq(L[5].layers[1].imageSource, "sky.png", "image layer path")
t:eq(L[5].layers[1].repeatX, true, "repeatx")
local objs = L[5].layers[2].objects
t:eq(#objs, 7, "objects")
t:check(objs[1].class == "Crate" and objs[1].rotation == 45 and objs[1].properties.weight == 2.25, "rectangle")
t:eq(objs[2].shape, "ellipse", "ellipse")
t:eq(objs[3].shape, "point", "point")
t:check(objs[4].shape == "polygon" and #objs[4].points == 3 and objs[4].points[3][2] == -12.5, "polygon")
t:check(objs[5].shape == "polyline" and objs[5].visible == false, "polyline")
t:check(objs[6].shape == "text" and objs[6].text.text == "Hello <Tiled>" and objs[6].text.bold and objs[6].text.halign == "center", "text")
t:eq(objs[7].gid, 2147483651, "tile object gid with flip")
t:eq(maps.hex.hexSideLength, 14, "hex side")
t:eq(maps.hex.layers[1].data[5], 2, "XML tile data")
t:eq(#maps.infinite.layers[1].chunks, 3, "chunks")
t:eq(maps.infinite.layers[1].chunks[2].x, -16, "chunk position")
end
-- the external tileset, TSX vs Tiled's TSJ
do
local a = decode(Fx.tsx)
local b = decode(Fx.tsj)
t:check(a and a.meta.tileset and b and b.meta.tileset, "tileset files")
local ta, tb = a.tilesets[1], b.tilesets[1]
ta.firstGid, tb.firstGid = nil, nil
eqMap(ta, tb, "TSX = Tiled's TSJ")
t:eq(ta.tiles[1].animation[2].duration, 150, "animation")
t:eq(ta.tiles[2].objectGroup.objects[2].shape, "ellipse", "collision shapes")
t:eq(ta.tileOffset.y, -3, "tile offset")
for _, fmt in { "tsx", "tsj" } do
local back = decode(Tiled.encode(a, { format = fmt }) :: buffer)
back.tilesets[1].firstGid = nil
eqMap(back.tilesets[1], ta, "tileset round trip " .. fmt)
end
end
-- round trips through every flavour and data encoding
for name, m in maps do
for _, o in { { format = "tmx" }, { format = "tmx", encoding = "base64" }, { format = "tmx", encoding = "base64", compression = "zlib" }, { format = "tmx", encoding = "base64", compression = "gzip" }, { format = "tmx", encoding = "xml" }, { format = "tmj" }, { format = "tmj", encoding = "base64", compression = "zlib" }, { format = "json", indent = 0 } } do
local out, err = Tiled.encode(m, o :: any)
local label = name .. " " .. o.format .. " " .. tostring(o.encoding) .. " " .. tostring(o.compression)
t:check(out, label .. ": " .. tostring(err))
local back, berr = decode(out :: buffer)
t:check(back, label .. ": decode: " .. tostring(berr))
eqMap(back, m, label .. ": round trip")
table.insert(samples, buffer.tostring(out :: buffer))
end
end
do
local m = maps.ortho
t:eq(m.meta.source.format, "tmx", "source flavour")
t:eq(string.sub(buffer.tostring(Tiled.encode(m) :: buffer), 1, 5), "<?xml", "default: the source flavour")
local j = decode(Fx.cases[1].tmj)
t:eq(string.sub(buffer.tostring(Tiled.encode(j) :: buffer), 1, 1), "{", "a TMJ source writes TMJ")
end
-- Tiled read our TMX and TMJ (checked when the fixtures were made)
for _, c in Ours.checks do
t:check(c.ok, c.label)
end
-- errors
do
local zstd = string.gsub(Fx.cases[1].tmx, "compression=\"zlib\"", "compression=\"zstd\"")
local _, e = decode(zstd)
t:check(e and e.code == Err.UNSUPPORTED, "zstd: " .. tostring(e))
local _, e2 = decode("<map><layer><data encoding=\"csv\">1,x,2</data></layer></map>")
t:check(e2 and e2.code == Err.CORRUPT, "bad csv: " .. tostring(e2))
local _, e3 = decode("<notmap/>")
t:check(e3 and e3.code == Err.CORRUPT, "not a map")
local _, e4 = decode("{\"type\":\"map\",\"layers\":[{\"type\":\"weird\"}]}")
t:check(e4 and e4.code == Err.CORRUPT, "unknown layer type")
local _, e5 = Tiled.encode(maps.ortho, { format = "png" } :: any)
t:check(e5 and e5.code == Err.ARG, "unknown flavour")
local _, e6 = Tiled.encode({} :: any)
t:check(e6 and e6.code == Err.ARG, "not a TileMap")
end
t:fuzz("decode", function(b: buffer)
return Tiled.decode(Bytes.reader(b))
end, samples, { mutations = 6 })
t:done()