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

+8
View File
@@ -46,6 +46,13 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` |
| data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` |
| data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` |
| vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` |
| vector | tiled | .tmx .tmj .tsx .tsj | yes | yes | tilesets: true, infinite: true | `tests/vector/tiled.luau` |
| layered | aseprite | .aseprite .ase | yes | yes | layers: true, groups: true, animation: true, depths: 8, 16, 32 | `tests/layered/aseprite.luau` |
| layered | psd | .psd .psb | yes | yes | layers: true, groups: true, depths: 1, 8, 16, 32 | `tests/layered/psd.luau` |
| subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` |
| subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` |
| subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` |
| playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` |
| playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` |
| playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` |
@@ -53,6 +60,7 @@ 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/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs
- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
+84
View File
@@ -506,6 +506,90 @@ local list: { Entry } = {
return require("@formats/data/yaml")
end,
},
{
name = "svg",
category = "vector",
path = "vector/svg",
extensions = { "svg" },
mime = { "image/svg+xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend" },
caps = { decode = true, encode = true, rasterize = true, text = false },
load = function()
return require("@formats/vector/svg")
end,
},
{
name = "tiled",
category = "vector",
path = "vector/tiled",
extensions = { "tmx", "tmj", "tsx", "tsj" },
mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" },
deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" },
caps = { decode = true, encode = true, tilesets = true, infinite = true },
load = function()
return require("@formats/vector/tiled")
end,
},
{
name = "aseprite",
category = "layered",
path = "layered/aseprite",
extensions = { "aseprite", "ase" },
mime = { "image/x-aseprite" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" },
caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } },
load = function()
return require("@formats/layered/aseprite")
end,
},
{
name = "psd",
category = "layered",
path = "layered/psd",
extensions = { "psd", "psb" },
mime = { "image/vnd.adobe.photoshop" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" },
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } },
load = function()
return require("@formats/layered/psd")
end,
},
{
name = "ass",
category = "subtitle",
path = "subtitle/ass",
extensions = { "ass", "ssa" },
mime = { "text/x-ssa", "text/x-ass" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = true },
load = function()
return require("@formats/subtitle/ass")
end,
},
{
name = "srt",
category = "subtitle",
path = "subtitle/srt",
extensions = { "srt" },
mime = { "application/x-subrip", "text/srt" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = false },
load = function()
return require("@formats/subtitle/srt")
end,
},
{
name = "vtt",
category = "subtitle",
path = "subtitle/vtt",
extensions = { "vtt", "webvtt" },
mime = { "text/vtt" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = true },
load = function()
return require("@formats/subtitle/vtt")
end,
},
{
name = "m3u",
category = "playlist",
+27 -5
View File
@@ -911,24 +911,40 @@ end
Types.Vector = Vector
-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite)
export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean }
-- blend: a codecs/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group:
-- its layers bottom to top; its image is 0 x 0), clip (clipped to the alpha of the layer below), mask (a grey mask in
-- canvas coordinates; outside its rectangle the mask is `default`).
export type LayerMask = { image: Image, x: number, y: number, default: number, disabled: boolean? }
export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean, children: { Layer }?, clip: boolean?, mask: LayerMask? }
export type Layered = {
kind: "layered",
width: number,
height: number,
layers: { Layer }, -- bottom to top
frames: { { layers: { Layer }, delay: number } }?,
layers: { Layer }, -- bottom to top (a tree: groups have children); animations: frame 1's layers
frames: { { layers: { Layer }, delay: number } }?, -- animations (Aseprite): every frame's layers, delay in seconds
meta: { [string]: any },
}
local Layered = {}
function Layered.new(width: number, height: number): Layered
return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} }
end
-- layer(name, image, x?, y?) -> a visible normal layer at full opacity
function Layered.layer(name: string, image: Image, x: number?, y: number?): Layer
return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true }
end
-- group(name, children) -> a pass-through group layer
function Layered.group(name: string, children: { Layer }): Layer
return { name = name, image = Image.new(0, 0), x = 0, y = 0, opacity = 1, blend = "passThrough", visible = true, children = children }
end
Types.Layered = Layered
-- ------------------------------------------------------------------------------------------------ TileMap (Tiled)
export type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string? }
export type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any } }
-- gids are Tiled's: 0 = empty, the tile's firstGid-relative index, flip / rotation flags in the top bits (kept).
-- Tilesets keep their image as a reference (imageSource: the path as written; image: an Image only if a caller
-- loads it). Extra Tiled fields sit next to these (offsetX / offsetY, parallax, tintColor, class, chunks of infinite
-- maps, objects' shapes, per-tile data, ...: see vector/tiled).
export type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string?, [string]: any }
export type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any }, [string]: any }
export type TileMap = {
kind: "tilemap",
width: number,
@@ -940,7 +956,13 @@ export type TileMap = {
layers: { TileLayer },
properties: { [string]: any },
meta: { [string]: any },
[string]: any,
}
local TileMap = {}
function TileMap.new(width: number, height: number, tileWidth: number, tileHeight: number): TileMap
return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} }
end
Types.TileMap = TileMap
-- ------------------------------------------------------------------------------------------------ Subtitles
export type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds
+371
View File
@@ -0,0 +1,371 @@
--!strict
--!native
-- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
-- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer
-- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the
-- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers.
--
-- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m })
-- Blend.MODES.multiply -> true
--
-- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge
-- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion
-- subtract divide hue saturation color luminosity. Unknown names composite as normal.
local Blend = {}
local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len
local min, max, floor, sqrt, abs = math.min, math.max, math.floor, math.sqrt, math.abs
local IDS: { [string]: number } = {
normal = 0,
dissolve = 1,
darken = 2,
multiply = 3,
colorBurn = 4,
linearBurn = 5,
darkerColor = 6,
lighten = 7,
screen = 8,
colorDodge = 9,
linearDodge = 10,
add = 10,
lighterColor = 11,
overlay = 12,
softLight = 13,
hardLight = 14,
vividLight = 15,
linearLight = 16,
pinLight = 17,
hardMix = 18,
difference = 19,
exclusion = 20,
subtract = 21,
divide = 22,
hue = 23,
saturation = 24,
color = 25,
luminosity = 26,
}
local MODES: { [string]: boolean } = {}
for k in IDS do
MODES[k] = true
end
Blend.MODES = table.freeze(MODES)
local function burn(cb: number, cs: number): number
if cb >= 1 then
return 1
elseif cs <= 0 then
return 0
end
return 1 - min(1, (1 - cb) / cs)
end
local function dodge(cb: number, cs: number): number
if cb <= 0 then
return 0
elseif cs >= 1 then
return 1
end
return min(1, cb / (1 - cs))
end
-- B(cb, cs) of a separable mode
local function sep(m: number, cb: number, cs: number): number
if m == 3 then
return cb * cs
elseif m == 8 then
return cb + cs - cb * cs
elseif m == 2 then
return min(cb, cs)
elseif m == 7 then
return max(cb, cs)
elseif m == 12 then -- overlay = hardLight(cs, cb)
if cb <= 0.5 then
return 2 * cb * cs
end
local c = 2 * cb - 1
return cs + c - cs * c
elseif m == 14 then
if cs <= 0.5 then
return 2 * cb * cs
end
local c = 2 * cs - 1
return cb + c - cb * c
elseif m == 13 then
if cs <= 0.5 then
return cb - (1 - 2 * cs) * cb * (1 - cb)
end
local d = if cb <= 0.25 then ((16 * cb - 12) * cb + 4) * cb else sqrt(cb)
return cb + (2 * cs - 1) * (d - cb)
elseif m == 9 then
return dodge(cb, cs)
elseif m == 4 then
return burn(cb, cs)
elseif m == 5 then
return max(0, cb + cs - 1)
elseif m == 10 then
return min(1, cb + cs)
elseif m == 15 then
if cs <= 0.5 then
return burn(cb, 2 * cs)
end
return dodge(cb, 2 * cs - 1)
elseif m == 16 then
return max(0, min(1, cb + 2 * cs - 1))
elseif m == 17 then
if cs <= 0.5 then
return min(cb, 2 * cs)
end
return max(cb, 2 * cs - 1)
elseif m == 18 then
return if cb + cs >= 1 then 1 else 0
elseif m == 19 then
return abs(cb - cs)
elseif m == 20 then
return cb + cs - 2 * cb * cs
elseif m == 21 then
return max(0, cb - cs)
elseif m == 22 then
if cs <= 0 then
return if cb <= 0 then 0 else 1
end
return min(1, cb / cs)
end
return cs
end
-- non-separable helpers (W3C): lum, clip, setLum, sat, setSat
local function lum(r: number, g: number, b: number): number
return 0.3 * r + 0.59 * g + 0.11 * b
end
local function clipColor(r: number, g: number, b: number): (number, number, number)
local l = lum(r, g, b)
local n = min(r, g, b)
local x = max(r, g, b)
if n < 0 and l - n > 1e-12 then
r, g, b = l + (r - l) * l / (l - n), l + (g - l) * l / (l - n), l + (b - l) * l / (l - n)
end
if x > 1 and x - l > 1e-12 then
r, g, b = l + (r - l) * (1 - l) / (x - l), l + (g - l) * (1 - l) / (x - l), l + (b - l) * (1 - l) / (x - l)
end
return r, g, b
end
local function setLum(r: number, g: number, b: number, l: number): (number, number, number)
local d = l - lum(r, g, b)
return clipColor(r + d, g + d, b + d)
end
local function setSat(r: number, g: number, b: number, s: number): (number, number, number)
local mx = max(r, g, b)
local mn = min(r, g, b)
if mx - mn <= 1e-12 then
return 0, 0, 0
end
local k = s / (mx - mn)
return (r - mn) * k, (g - mn) * k, (b - mn) * k
end
-- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8
-- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask:
-- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default).
local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?)
x, y = floor(x), floor(y)
if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then
return
end
if blen(dst) < dw * dh * 4 or blen(src) < sw * sh * 4 then
return
end
local op = min(1, opacity)
local m = IDS[mode or "normal"] or 0
local clip = opts ~= nil and opts.clip == true
local mask = if opts ~= nil then opts.mask else nil
local mbuf: buffer? = nil
local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1
if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then
mw, mh = floor(mask.width), floor(mask.height)
if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then
mbuf = mask.pixels
end
mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0)
mdef = (tonumber(mask.default) or 255) / 255
elseif type(mask) == "table" then
mdef = (tonumber(mask.default) or 255) / 255
end
local x0, y0 = max(0, x), max(0, y)
local x1, y1 = min(dw, x + sw), min(dh, y + sh)
for py = y0, y1 - 1 do
local so = ((py - y) * sw + (x0 - x)) * 4
local do_ = (py * dw + x0) * 4
for px = x0, x1 - 1 do
local sa8 = readu8(src, so + 3)
if sa8 ~= 0 then
local sa = sa8 / 255 * op
if mbuf ~= nil or mdef ~= 1 then
local mv = mdef
local mxx, myy = px - mx0, py - my0
if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then
mv = readu8(mbuf, myy * mw + mxx) / 255
end
sa *= mv
end
if m == 1 then -- dissolve: a hash threshold per pixel, full alpha where it shows
local h = (px * 73856093 + py * 19349663) % 65536 / 65536
sa = if h < sa then 1 else 0
end
local ba8 = readu8(dst, do_ + 3)
if sa > 0 and not (clip and ba8 == 0) then
local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255
if ba8 == 0 then
-- empty backdrop: the source as it is (alpha scaled)
writeu32(dst, do_, readu32(src, so))
writeu8(dst, do_ + 3, floor(sa * 255 + 0.5))
else
local ba = ba8 / 255
local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255
local mr, mg, mb = sr, sg, sb
if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then
mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb)
elseif m == 6 then
if lum(sr, sg, sb) >= lum(br, bg, bb) then
mr, mg, mb = br, bg, bb
end
elseif m == 11 then
if lum(sr, sg, sb) < lum(br, bg, bb) then
mr, mg, mb = br, bg, bb
end
elseif m == 23 then
local s = max(br, bg, bb) - min(br, bg, bb)
local r1, g1, b1 = setSat(sr, sg, sb, s)
mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb))
elseif m == 24 then
local s = max(sr, sg, sb) - min(sr, sg, sb)
local r1, g1, b1 = setSat(br, bg, bb, s)
mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb))
elseif m == 25 then
mr, mg, mb = setLum(sr, sg, sb, lum(br, bg, bb))
elseif m == 26 then
mr, mg, mb = setLum(br, bg, bb, lum(sr, sg, sb))
end
local orr, og, ob, oa
if clip then
-- source-atop: the backdrop's alpha; the mixed colour where the backdrop is opaque
orr = sa * mr + (1 - sa) * br
og = sa * mg + (1 - sa) * bg
ob = sa * mb + (1 - sa) * bb
oa = ba
else
oa = sa + ba * (1 - sa)
local ws, wm, wb = sa * (1 - ba), sa * ba, (1 - sa) * ba
orr = (ws * sr + wm * mr + wb * br) / oa
og = (ws * sg + wm * mg + wb * bg) / oa
ob = (ws * sb + wm * mb + wb * bb) / oa
end
writeu8(dst, do_, floor(max(0, min(1, orr)) * 255 + 0.5))
writeu8(dst, do_ + 1, floor(max(0, min(1, og)) * 255 + 0.5))
writeu8(dst, do_ + 2, floor(max(0, min(1, ob)) * 255 + 0.5))
writeu8(dst, do_ + 3, floor(max(0, min(1, oa)) * 255 + 0.5))
end
end
end
so += 4
do_ += 4
end
end
end
-- lerp(dst, from, t, n): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity)
local function lerp(dst: buffer, from: buffer, t: number, n: number)
if blen(dst) < n * 4 or blen(from) < n * 4 then
return
end
for i = 0, n * 4 - 1 do
local a = readu8(from, i)
writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5))
end
end
Blend.composite = composite
Blend.lerp = lerp
-- ------------------------------------------------------------------------------------------------ layer trees
local function isImage(v: any): boolean
return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4
end
local function maskOf(l: any): any
local m = l.mask
if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then
return nil
end
local img = m.image
local px = img.pixels
if img.format == "rgba8" then -- use the red channel
local n = img.width * img.height
local g = buffer.create(n)
for i = 0, n - 1 do
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
end
px = g
end
return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 }
end
local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean)
local i = 1
while i <= #layers do
local l = layers[i]
i += 1
if type(l) ~= "table" or (l.visible == false and not hidden) then
-- clipped layers above a hidden base are hidden too
while i <= #layers and type(layers[i]) == "table" and layers[i].clip do
i += 1
end
continue
end
local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1)
local mode = if type(l.blend) == "string" then l.blend else "normal"
-- the layer's own pixels, as an isolated w x h buffer
local src: buffer? = nil
if type(l.children) == "table" then
if mode == "passThrough" then
local before = buffer.create(w * h * 4)
buffer.copy(before, 0, canvas, 0, w * h * 4)
compose(l.children, canvas, w, h, hidden)
if opacity < 1 then
lerp(canvas, before, opacity, w * h)
end
continue
end
src = buffer.create(w * h * 4)
compose(l.children, src :: buffer, w, h, hidden)
elseif isImage(l.image) then
if l.image.width > 0 and l.image.height > 0 then
local b = buffer.create(w * h * 4)
composite(b, w, h, l.image.pixels, l.image.width, l.image.height, tonumber(l.x) or 0, tonumber(l.y) or 0, 1, "normal")
src = b
end
end
-- clipping layers above this one: composited onto it with their alpha limited to it
while i <= #layers and type(layers[i]) == "table" and layers[i].clip do
local c = layers[i]
i += 1
if src and (c.visible ~= false or hidden) and isImage(c.image) then
composite(src :: buffer, w, h, c.image.pixels, c.image.width, c.image.height, tonumber(c.x) or 0, tonumber(c.y) or 0, (tonumber(c.opacity) or 1) * (tonumber(c.fillOpacity) or 1), c.blend, { clip = true, mask = maskOf(c) })
end
end
if src then
composite(canvas, w, h, src :: buffer, w, h, 0, 0, opacity, mode, { mask = maskOf(l) })
end
end
end
-- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas:
-- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group
-- opacity then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks.
-- hidden = true includes invisible layers.
function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean)
if blen(canvas) >= w * h * 4 then
compose(layers, canvas, w, h, hidden)
end
end
return Blend
+89
View File
@@ -0,0 +1,89 @@
--!strict
--!native
-- core/Base64: RFC 4648 base64 (standard alphabet, and the URL-safe one on decode). Tiled map data, data: URIs, ...
-- decode skips whitespace and accepts missing padding; other bad characters fail. Never throws.
--
-- local s = Base64.encode(buf) -- buffer | string -> string
-- local b, err = Base64.decode(s) -- string -> buffer | nil, "message"
local Base64 = {}
local ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
local ENC = buffer.create(64)
buffer.writestring(ENC, 0, ALPHABET)
local DEC = buffer.create(256)
buffer.fill(DEC, 0, 255)
for i = 0, 63 do
buffer.writeu8(DEC, string.byte(ALPHABET, i + 1), i)
end
buffer.writeu8(DEC, string.byte("-"), 62)
buffer.writeu8(DEC, string.byte("_"), 63)
for _, c in { 9, 10, 13, 32 } do
buffer.writeu8(DEC, c, 254) -- whitespace: skipped
end
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- encode(data) -> base64 text with padding
function Base64.encode(data: buffer | string): string
local src: buffer = if type(data) == "string" then buffer.fromstring(data) else data
local n = buffer.len(src)
local out = buffer.create((n + 2) // 3 * 4)
local o = 0
local i = 0
while i + 2 < n do
local v = readu8(src, i) * 65536 + readu8(src, i + 1) * 256 + readu8(src, i + 2)
writeu8(out, o, readu8(ENC, v // 262144))
writeu8(out, o + 1, readu8(ENC, v // 4096 % 64))
writeu8(out, o + 2, readu8(ENC, v // 64 % 64))
writeu8(out, o + 3, readu8(ENC, v % 64))
i += 3
o += 4
end
local rest = n - i
if rest > 0 then
local v = readu8(src, i) * 65536 + (if rest == 2 then readu8(src, i + 1) * 256 else 0)
writeu8(out, o, readu8(ENC, v // 262144))
writeu8(out, o + 1, readu8(ENC, v // 4096 % 64))
writeu8(out, o + 2, if rest == 2 then readu8(ENC, v // 64 % 64) else 61)
writeu8(out, o + 3, 61)
end
return buffer.tostring(out)
end
-- decode(text) -> buffer | nil, message
function Base64.decode(text: string | buffer): (buffer?, string?)
local src: buffer = if type(text) == "string" then buffer.fromstring(text) else text
local n = buffer.len(src)
local out = buffer.create(n // 4 * 3 + 3)
local o = 0
local acc, bits = 0, 0
local pad = false
for i = 0, n - 1 do
local c = readu8(src, i)
local v = readu8(DEC, c)
if v == 254 then
continue
end
if c == 61 then -- '='
pad = true
continue
end
if v == 255 or pad then
return nil, string.format("bad base64 character at %d", i)
end
acc = acc * 64 + v
bits += 6
if bits >= 8 then
bits -= 8
local p = 2 ^ bits
writeu8(out, o, acc // p)
acc %= p
o += 1
end
end
local res = buffer.create(o)
buffer.copy(res, 0, out, 0, o)
return res, nil
end
return Base64
+754
View File
@@ -0,0 +1,754 @@
--!strict
-- layered/aseprite: Aseprite .ase / .aseprite sprites (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA,
-- grayscale and indexed sprites (to rgba8; the transparent index is clear except on background layers); every
-- frame (duration -> delay); layers (normal and group, child levels -> a tree; visibility, blend mode, opacity,
-- flags, UUIDs skipped; a group of normal blend at full opacity is "passThrough"); cels (raw, zlib-compressed, linked: a linked cel shares the Image of the frame it points to
-- and records `link`), cel opacity (-> the leaf's fillOpacity), z-index; the palette (new 0x2019 chunk and the old
-- 0x0004 / 0x0011 ones; entry names), tags (meta.tags, frames 1-based), user data text / colour on layers, cels and
-- tags, the pixel ratio and grid. A Layered value: layers = frame 1's tree, frames[i] = { layers = frame i's tree,
-- delay }.
-- Encode: RGBA (or grayscale / indexed when opts.depth or meta.colorDepth asks and the pixels fit), one layer chunk
-- per node of frame 1's tree, zlib cels, linked cels where a frame reuses an earlier frame's Image at the same place,
-- palette, tags.
-- Not supported: tilemap layers / tilesets (skipped: meta.skipped counts them), slices, external files, colour
-- profiles (sRGB assumed).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Deflate = require("@formats/codecs/Deflate")
-- ------------------------------------------------------------------------------------------------ contract
local Aseprite = {
name = "aseprite",
category = "layered",
extensions = { "aseprite", "ase" },
mime = { "image/x-aseprite" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" },
caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } },
}
export type DecodeOptions = {
maxPixels: number?, -- refuse sprites / cels larger than this (default 2^26)
maxFrames: number?, -- default 65535
}
export type EncodeOptions = {
depth: number?, -- 32 (RGBA), 16 (grayscale) or 8 (indexed, with layered.meta.palette); default meta.colorDepth if
-- the pixels fit it, else 32
level: number?, -- zlib level for the cels (default 6)
}
-- ------------------------------------------------------------------------------------------------ constants
local BLENDS = { [0] = "normal", "multiply", "screen", "overlay", "darken", "lighten", "colorDodge", "colorBurn", "hardLight", "softLight", "difference", "exclusion", "hue", "saturation", "color", "luminosity", "linearDodge", "subtract", "divide" }
local BLEND_IDS: { [string]: number } = {}
for k, v in BLENDS do
BLEND_IDS[v] = k
end
BLEND_IDS.add = 16
BLEND_IDS.passThrough = 0
local DIRECTIONS = { [0] = "forward", "reverse", "pingpong", "pingpongReverse" }
local DIRECTION_IDS = { forward = 0, reverse = 1, pingpong = 2, pingpongReverse = 3 }
-- ------------------------------------------------------------------------------------------------ sniff
function Aseprite.sniff(r: Bytes.Reader): number
if r:peekU8(4) == 0xE0 and r:peekU8(5) == 0xA5 then
local d = r:peekU8(12)
if (d == 32 or d == 16 or d == 8) and r:peekU8(13) == 0 then
return 1
end
return 0.5
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function str(r: Bytes.Reader): string
return r:string(r:u16le())
end
-- cel pixels (depth bytes per pixel) -> rgba8
local function toRGBA(src: buffer, so: number, n: number, depth: number, palette: buffer, transparent: number, background: boolean): buffer
local out = buffer.create(n * 4)
if depth == 32 then
buffer.copy(out, 0, src, so, n * 4)
elseif depth == 16 then
for i = 0, n - 1 do
local v, a = buffer.readu8(src, so + i * 2), buffer.readu8(src, so + i * 2 + 1)
buffer.writeu32(out, i * 4, v + v * 256 + v * 65536 + a * 16777216)
end
else
for i = 0, n - 1 do
local k = buffer.readu8(src, so + i)
local c = buffer.readu32(palette, k * 4)
if k == transparent and not background then
c = 0
end
buffer.writeu32(out, i * 4, c)
end
end
return out
end
type LayerInfo = { name: string, flags: number, type: number, level: number, blend: number, opacity: number, userData: any? }
function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local maxFrames = opts and opts.maxFrames or 65535
if r:size() < 128 then
return nil, Err.new(Err.TRUNCATED, "header needs 128 bytes", r.pos)
end
r:skip(4)
if r:u16le() ~= 0xA5E0 then
return nil, Err.new(Err.CORRUPT, "bad magic", r.pos - 2)
end
local nframes, w, h, depth = r:u16le(), r:u16le(), r:u16le(), r:u16le()
local hflags = r:u32le()
r:skip(2 + 8)
local transparent = r:u8()
r:skip(3)
local ncolors = r:u16le()
local pw, ph = r:u8(), r:u8()
local gx, gy, gw, gh = r:i16le(), r:i16le(), r:u16le(), r:u16le()
r:seek(128)
if depth ~= 32 and depth ~= 16 and depth ~= 8 then
return nil, Err.new(Err.CORRUPT, "bad colour depth " .. depth)
end
if w < 1 or h < 1 then
return nil, Err.new(Err.CORRUPT, "bad size")
end
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the pixel limit", w, h))
end
if nframes > maxFrames then
return nil, Err.new(Err.LIMIT, "too many frames")
end
local bpp = depth // 8
local palette = buffer.create(1024)
local palList: { { number } } = {}
local palNames: { [number]: string } = {}
local infos: { LayerInfo } = {}
local tags: { any } = {}
local frames: { { cels: { [number]: any }, delay: number } } = {}
local skipped = 0
local lastUser: any = nil -- the object the next user data chunk belongs to
local tagUser = 0 -- tags waiting for their user data chunks
for fi = 1, nframes do
local fstart = r.pos
local fbytes = r:u32le()
local fmagic = r:u16le()
local oldChunks = r:u16le()
local duration = r:u16le()
r:skip(2)
local newChunks = r:u32le()
if r.err then
return nil, r.err
end
if fmagic ~= 0xF1FA then
return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": bad magic", fstart + 4)
end
if fbytes < 16 or fstart + fbytes > r.limit then
return nil, Err.new(Err.TRUNCATED, "frame " .. fi .. " runs past the end", fstart)
end
local nchunks = if newChunks ~= 0 then newChunks else oldChunks
local frame = { cels = {}, delay = duration / 1000 }
frames[fi] = frame
local fr = Bytes.reader(r.buf, r.pos, fstart + fbytes - r.pos)
for _ = 1, nchunks do
if fr:remaining() < 6 then
break
end
local cstart = fr.pos
local csize = fr:u32le()
local ctype = fr:u16le()
if csize < 6 or cstart + csize > fr.limit then
return nil, Err.new(Err.CORRUPT, string.format("frame %d: chunk 0x%04x size %d", fi, ctype, csize), cstart)
end
local c = Bytes.reader(fr.buf, cstart + 6, csize - 6)
fr.pos = cstart + csize
if ctype == 0x2004 then
local info: LayerInfo = { flags = c:u16le(), type = c:u16le(), level = c:u16le(), name = "", blend = 0, opacity = 255 }
c:skip(4)
info.blend = c:u16le()
info.opacity = c:u8()
c:skip(3)
info.name = str(c)
if c.err then
return nil, c.err
end
if info.type == 2 then
skipped += 1
end
table.insert(infos, info)
lastUser = info
elseif ctype == 0x2005 then
local li = c:u16le()
local x, y = c:i16le(), c:i16le()
local op = c:u8()
local ctyp = c:u16le()
local z = c:i16le()
c:skip(5)
if c.err then
return nil, c.err
end
local cel: any = { x = x, y = y, opacity = op, z = z }
if ctyp == 0 or ctyp == 2 then
local cw, ch = c:u16le(), c:u16le()
if c.err then
return nil, c.err
end
if cw * ch > maxPixels then
return nil, Err.new(Err.LIMIT, "cel over the pixel limit")
end
local n = cw * ch
local raw: buffer, ro: number
if ctyp == 0 then
if not c:need(n * bpp) then
return nil, c.err
end
raw, ro = c.buf, c.pos
else
local z2, zerr = Deflate.zlib(c.buf, c.pos, c.limit - c.pos, n * bpp)
if not z2 then
-- some writers leave padding after the stream: inflate without the exact size
local loose = Deflate.zlib(c.buf, c.pos, c.limit - c.pos)
if not loose or buffer.len(loose) < n * bpp then
return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": cel data: " .. tostring(zerr and zerr.message), c.pos)
end
z2 = loose
end
raw, ro = z2 :: buffer, 0
end
cel.w, cel.h, cel.raw, cel.ro = cw, ch, raw, ro
elseif ctyp == 1 then
cel.link = c:u16le() + 1
else
cel.skip = true -- tilemap cel
end
frame.cels[li + 1] = cel
lastUser = cel
elseif ctype == 0x2018 then
local n = c:u16le()
c:skip(8)
tagUser = 0
for _ = 1, n do
local from, to = c:u16le(), c:u16le()
local dir = c:u8()
local rep = c:u16le()
c:skip(6)
local cr, cg, cb = c:u8(), c:u8(), c:u8()
c:skip(1)
local name = str(c)
if c.err then
return nil, c.err
end
table.insert(tags, { name = name, from = from + 1, to = to + 1, direction = DIRECTIONS[dir] or "forward", ["repeat"] = rep, color = { cr, cg, cb } })
tagUser += 1
end
lastUser = nil
elseif ctype == 0x2019 then
local size = c:u32le()
local first, last = c:u32le(), c:u32le()
c:skip(8)
if first > last or last > 255 or size > 256 then
return nil, Err.new(Err.CORRUPT, "bad palette range", cstart)
end
for k = first, last do
local f = c:u16le()
local cr, cg, cb, ca = c:u8(), c:u8(), c:u8(), c:u8()
if bit32.band(f, 1) ~= 0 then
palNames[k + 1] = str(c)
end
buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + ca * 16777216)
palList[k + 1] = { cr, cg, cb, ca }
end
for k = #palList + 1, size do
palList[k] = { 0, 0, 0, 255 }
end
if c.err then
return nil, c.err
end
elseif (ctype == 0x0004 or ctype == 0x0011) and #palList == 0 then
-- old palettes (used when there is no 0x2019 chunk): packets of (skip, count) entries of RGB
local packets = c:u16le()
local k = 0
for _ = 1, packets do
k += c:u8()
local n = c:u8()
if n == 0 then
n = 256
end
for _ = 1, n do
local cr, cg, cb = c:u8(), c:u8(), c:u8()
if ctype == 0x0011 then
cr, cg, cb = cr * 255 // 63, cg * 255 // 63, cb * 255 // 63
end
if k < 256 then
buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + 0xFF000000)
end
k += 1
end
end
if c.err then
return nil, c.err
end
for i = 0, math.min(k, 256) - 1 do
local v = buffer.readu32(palette, i * 4)
palList[i + 1] = { v % 256, v // 256 % 256, v // 65536 % 256, 255 }
end
palList = table.move(palList, 1, math.min(k, 256), 1, {})
elseif ctype == 0x2020 then
local f = c:u32le()
local ud: any = {}
if bit32.band(f, 1) ~= 0 then
ud.text = str(c)
end
if bit32.band(f, 2) ~= 0 then
ud.color = { c:u8(), c:u8(), c:u8(), c:u8() }
end
if not c.err then
if tagUser > 0 then
-- after a tags chunk, user data chunks follow for each tag in order
local t = tags[#tags - tagUser + 1]
if t then
t.userData = ud
end
tagUser -= 1
elseif lastUser then
lastUser.userData = ud
end
end
end
-- others (colour profile, slices, tilesets, external files, cel extras, masks, paths) are skipped
end
r.pos = fstart + fbytes
end
local _ = ncolors
-- the layer tree of one frame
local function build(fi: number): { Types.Layer }
local root: { Types.Layer } = {}
local stack: { { Types.Layer } } = { root } -- stack[level + 1] = the children list at that level
for li, info in infos do
local level = math.min(info.level, #stack - 1)
local list = stack[level + 1]
local l: any = {
name = info.name,
x = 0,
y = 0,
opacity = if bit32.band(hflags, 1) ~= 0 or info.type ~= 0 then info.opacity / 255 else 1,
blend = BLENDS[info.blend] or "normal",
visible = bit32.band(info.flags, 1) ~= 0,
flags = info.flags,
}
if info.userData then
l.userData = info.userData
end
if info.type == 1 then
l.image = Types.Image.new(0, 0)
l.children = {}
-- Aseprite renders a group straight onto the backdrop unless it has its own blend mode / opacity (then
-- into a buffer of its own): pass-through vs isolated
if bit32.band(hflags, 2) == 0 or (info.blend == 0 and info.opacity == 255) then
l.blend = "passThrough"
l.opacity = 1
end
table.insert(list, l)
-- deeper layers go into this group
for k = #stack, level + 2, -1 do
stack[k] = nil
end
stack[level + 2] = l.children
else
for k = #stack, level + 2, -1 do
stack[k] = nil
end
l.image = Types.Image.new(0, 0)
if info.type == 2 then
l.tilemap = true
end
local cel = frames[fi].cels[li]
local guard = 0
while cel and cel.link and guard < 8 do -- follow links (one hop in valid files)
l.link = cel.link
local target = frames[cel.link]
cel = if target then target.cels[li] else nil
guard += 1
end
if cel and cel.image then
l.image = cel.image
l.x, l.y = cel.x, cel.y
if cel.opacity < 255 then
l.fillOpacity = cel.opacity / 255
end
if cel.z ~= 0 then
l.zIndex = cel.z
end
if cel.userData then
l.celUserData = cel.userData
end
end
table.insert(list, l)
end
end
return root
end
-- cel images (shared by linked cels)
for _, f in frames do
for li, cel in pairs(f.cels) do -- sparse: pairs, not ipairs-style iteration
if cel.raw then
local info = infos[li]
local img = Types.Image.new(cel.w, cel.h)
img.pixels = toRGBA(cel.raw, cel.ro, cel.w * cel.h, depth, palette, transparent, info ~= nil and bit32.band(info.flags, 8) ~= 0)
cel.image = img
cel.raw = nil
end
end
end
local layered = Types.Layered.new(w, h)
local list = {}
for fi = 1, nframes do
list[fi] = { layers = build(fi), delay = frames[fi].delay }
end
if nframes > 0 then
layered.layers = list[1].layers
end
layered.frames = list
if #palList > 0 then
layered.meta.palette = palList
if next(palNames) then
layered.meta.paletteNames = palNames
end
end
layered.meta.tags = tags
layered.meta.colorDepth = depth
layered.meta.transparentIndex = transparent
layered.meta.pixelRatio = { if pw == 0 then 1 else pw, if ph == 0 then 1 else ph }
layered.meta.grid = { gx, gy, gw, gh }
if skipped > 0 then
layered.meta.skipped = skipped
end
layered.meta.source = { format = "aseprite", bitDepth = depth, colorType = if depth == 32 then "rgba" elseif depth == 16 then "graya" else "indexed" }
return layered, nil
end
-- ------------------------------------------------------------------------------------------------ encode
type Node = { layer: any, level: number }
local function isImage(v: any): boolean
return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and v.width < 65536 and v.height < 65536 and buffer.len(v.pixels) >= v.width * v.height * 4
end
-- the nodes of a tree in file order (a group, then its children one level deeper)
local function nodes(layers: { any }, level: number, out: { Node }): boolean
for _, l in layers do
if type(l) ~= "table" or level > 64 then
return false
end
table.insert(out, { layer = l, level = level })
if type(l.children) == "table" then
if not nodes(l.children, level + 1, out) then
return false
end
end
end
return true
end
local function writeStr(w: Bytes.Writer, s: string)
local n = math.min(#s, 65535)
w:u16le(n)
w:string(string.sub(s, 1, n))
end
function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then
return nil, Err.new(Err.ARG, "needs a Layered value")
end
local W, H = math.floor(layered.width), math.floor(layered.height)
if W < 1 or H < 1 or W > 65535 or H > 65535 then
return nil, Err.new(Err.ARG, "bad sprite size")
end
local meta: any = if type(layered.meta) == "table" then layered.meta else {}
local level = opts and opts.level or 6
-- frames: the layered frames, or one frame of the layers
local frameList: { any } = if type(layered.frames) == "table" and #layered.frames > 0 then layered.frames else { { layers = layered.layers, delay = 0.1 } }
local struct: { Node } = {}
if not nodes(frameList[1].layers, 0, struct) then
return nil, Err.new(Err.ARG, "bad layer tree")
end
if #struct > 65535 or #frameList > 65535 then
return nil, Err.new(Err.ARG, "too many layers / frames")
end
local perFrame: { { Node } } = {}
for fi, f in frameList do
if type(f) ~= "table" or type(f.layers) ~= "table" then
return nil, Err.new(Err.ARG, "frame " .. fi .. ": no layers")
end
local ns: { Node } = {}
if not nodes(f.layers, 0, ns) or #ns ~= #struct then
return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's")
end
for k, n in ns do
if (type(n.layer.children) == "table") ~= (type(struct[k].layer.children) == "table") then
return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's")
end
if type(n.layer.children) ~= "table" and not isImage(n.layer.image) then
return nil, Err.new(Err.ARG, "frame " .. fi .. ": layer " .. tostring(n.layer.name) .. " needs an rgba8 image")
end
end
perFrame[fi] = ns
end
-- the colour depth: requested, or the source's when every pixel fits
local depth = opts and opts.depth or meta.colorDepth or 32
local explicit = opts ~= nil and opts.depth ~= nil
if depth ~= 32 and depth ~= 16 and depth ~= 8 then
return nil, Err.new(Err.ARG, "depth must be 32, 16 or 8")
end
local palette: { { number } } = if type(meta.palette) == "table" then meta.palette else {}
local transparent = if type(meta.transparentIndex) == "number" then meta.transparentIndex else 0
local index: { [number]: number } = {}
for k = #palette, 1, -1 do
local c = palette[k]
if type(c) == "table" then
index[(c[1] or 0) + (c[2] or 0) * 256 + (c[3] or 0) * 65536 + (c[4] or 255) * 16777216] = k - 1
end
end
if depth ~= 32 then
local fits = depth ~= 8 or #palette > 0
for _, ns in perFrame do
for _, n in ns do
local img = n.layer.image
if fits and type(n.layer.children) ~= "table" then
local px = img.pixels
for i = 0, img.width * img.height - 1 do
local v = buffer.readu32(px, i * 4)
if depth == 16 then
local r, g, b = v % 256, v // 256 % 256, v // 65536 % 256
if r ~= g or g ~= b then
fits = false
break
end
elseif v // 16777216 ~= 0 and index[v] == nil then
fits = false
break
end
end
end
end
end
if not fits then
if explicit then
return nil, Err.new(Err.ARG, "the pixels do not fit depth " .. depth .. (if depth == 8 then " with meta.palette" else ""))
end
depth = 32
end
end
local bpp = depth // 8
local function pixels(n: any): buffer
local img = n.layer.image
local count = img.width * img.height
if depth == 32 then
return img.pixels
end
local out = buffer.create(count * bpp)
local px = img.pixels
for i = 0, count - 1 do
local v = buffer.readu32(px, i * 4)
if depth == 16 then
buffer.writeu8(out, i * 2, v % 256)
buffer.writeu8(out, i * 2 + 1, v // 16777216)
else
local k = if v // 16777216 == 0 and bit32.band(tonumber(n.layer.flags) or 0, 8) == 0 then transparent else index[v] or transparent
buffer.writeu8(out, i, k)
end
end
return out
end
local out = Bytes.writer(65536)
-- header (file size patched at the end)
out:u32le(0)
out:u16le(0xA5E0)
out:u16le(#frameList)
out:u16le(W)
out:u16le(H)
out:u16le(depth)
out:u32le(3) -- layer opacity and group opacity / blend valid
out:u16le(100)
out:u32le(0)
out:u32le(0)
out:u8(if depth == 8 then transparent else 0)
out:fill(0, 3)
out:u16le(if #palette > 0 and #palette < 256 then #palette else 0)
local ratio = if type(meta.pixelRatio) == "table" then meta.pixelRatio else { 1, 1 }
out:u8(math.clamp(tonumber(ratio[1]) or 1, 0, 255))
out:u8(math.clamp(tonumber(ratio[2]) or 1, 0, 255))
local grid = if type(meta.grid) == "table" then meta.grid else { 0, 0, 16, 16 }
out:i16le(tonumber(grid[1]) or 0)
out:i16le(tonumber(grid[2]) or 0)
out:u16le(math.clamp(tonumber(grid[3]) or 16, 0, 65535))
out:u16le(math.clamp(tonumber(grid[4]) or 16, 0, 65535))
out:fill(0, 84)
local function chunk(fw: Bytes.Writer, ctype: number, body: Bytes.Writer)
local b = body:finish()
fw:u32le(buffer.len(b) + 6)
fw:u16le(ctype)
fw:bytes(b)
end
local function userData(fw: Bytes.Writer, ud: any): number
if type(ud) ~= "table" then
return 0
end
local c = Bytes.writer(64)
local f = (if type(ud.text) == "string" then 1 else 0) + (if type(ud.color) == "table" then 2 else 0)
c:u32le(f)
if type(ud.text) == "string" then
writeStr(c, ud.text)
end
if type(ud.color) == "table" then
for k = 1, 4 do
c:u8(math.clamp(tonumber(ud.color[k]) or 0, 0, 255))
end
end
chunk(fw, 0x2020, c)
return 1
end
-- where each (layer, frame) cel's image was first written: linked cels
local firstAt: { [number]: { [any]: { frame: number, x: number, y: number, fill: number } } } = {}
for fi, f in frameList do
local fw = Bytes.writer(4096)
local count = 0
if fi == 1 then
-- colour profile: sRGB
local cp = Bytes.writer(16)
cp:u16le(1)
cp:u16le(0)
cp:u32le(0)
cp:fill(0, 8)
chunk(fw, 0x2007, cp)
count += 1
if #palette > 0 then
local p = Bytes.writer(#palette * 6 + 20)
local n = math.min(#palette, 256)
p:u32le(n)
p:u32le(0)
p:u32le(n - 1)
p:fill(0, 8)
local names = if type(meta.paletteNames) == "table" then meta.paletteNames else {}
for k = 1, n do
local c = palette[k]
local nm = names[k]
p:u16le(if type(nm) == "string" then 1 else 0)
p:u8(c[1] or 0)
p:u8(c[2] or 0)
p:u8(c[3] or 0)
p:u8(c[4] or 255)
if type(nm) == "string" then
writeStr(p, nm)
end
end
chunk(fw, 0x2019, p)
count += 1
end
for _, n in struct do
local l = n.layer
local c = Bytes.writer(64)
local isGroup = type(l.children) == "table"
local flags = tonumber(l.flags) or 3
flags = bit32.band(flags, bit32.bnot(1)) + (if l.visible == false then 0 else 1)
c:u16le(flags)
c:u16le(if isGroup then 1 else 0)
c:u16le(n.level)
c:u16le(0)
c:u16le(0)
c:u16le(BLEND_IDS[l.blend] or 0)
c:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255))
c:fill(0, 3)
writeStr(c, tostring(l.name or "Layer"))
chunk(fw, 0x2004, c)
count += 1
count += userData(fw, l.userData)
end
local tags = if type(meta.tags) == "table" then meta.tags else {}
if #tags > 0 then
local c = Bytes.writer(64)
c:u16le(#tags)
c:fill(0, 8)
for _, t in tags do
c:u16le(math.clamp((tonumber(t.from) or 1) - 1, 0, 65535))
c:u16le(math.clamp((tonumber(t.to) or 1) - 1, 0, 65535))
c:u8(DIRECTION_IDS[t.direction] or 0)
c:u16le(math.clamp(tonumber(t["repeat"]) or 0, 0, 65535))
c:fill(0, 6)
local col = if type(t.color) == "table" then t.color else { 0, 0, 0 }
c:u8(col[1] or 0)
c:u8(col[2] or 0)
c:u8(col[3] or 0)
c:u8(0)
writeStr(c, tostring(t.name or "Tag"))
end
chunk(fw, 0x2018, c)
count += 1
for _, t in tags do
if type(t.userData) == "table" then
count += userData(fw, t.userData)
else
local e = Bytes.writer(4)
e:u32le(0)
chunk(fw, 0x2020, e)
count += 1
end
end
end
end
for li, n in perFrame[fi] do
local l = n.layer
if type(l.children) == "table" or l.image.width == 0 or l.image.height == 0 then
continue
end
local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0)
local fill = math.clamp(math.floor((tonumber(l.fillOpacity) or 1) * 255 + 0.5), 0, 255)
local c = Bytes.writer(256)
c:u16le(li - 1)
c:i16le(x)
c:i16le(y)
c:u8(fill)
local seen = firstAt[li] and firstAt[li][l.image]
if seen and seen.x == x and seen.y == y and seen.fill == fill then
c:u16le(1)
c:i16le(tonumber(l.zIndex) or 0)
c:fill(0, 5)
c:u16le(seen.frame - 1)
else
c:u16le(2)
c:i16le(tonumber(l.zIndex) or 0)
c:fill(0, 5)
c:u16le(l.image.width)
c:u16le(l.image.height)
local z = Deflate.zlibCompress(pixels(n), { level = level })
if not z then
return nil, Err.new(Err.ARG, "cel compression failed")
end
c:bytes(z)
firstAt[li] = firstAt[li] or {}
firstAt[li][l.image] = { frame = fi, x = x, y = y, fill = fill }
end
chunk(fw, 0x2005, c)
count += 1
count += userData(fw, l.celUserData)
end
local body = fw:finish()
out:u32le(buffer.len(body) + 16)
out:u16le(0xF1FA)
out:u16le(math.min(count, 0xFFFF))
out:u16le(math.clamp(math.floor((tonumber(f.delay) or 0.1) * 1000 + 0.5), 0, 65535))
out:u16le(0)
out:u32le(count)
out:bytes(body)
end
out:setU32le(0, out:tell())
return out:finish(), nil
end
return Aseprite
+394
View File
@@ -0,0 +1,394 @@
--!strict
--!native
-- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a
-- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the
-- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section".
-- Never throws: every read is range-checked first; failures return nil, "message".
local Deflate = require("@formats/codecs/Deflate")
local Channels = {}
local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32
local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.writef32, buffer.create, buffer.copy, buffer.len, buffer.fill
local floor, min, max = math.floor, math.min, math.max
local byteswap = bit32.byteswap
-- rowBytes(w, depth) -> bytes per row of one channel
function Channels.rowBytes(w: number, depth: number): number
if depth == 1 then
return (w + 7) // 8
end
return w * (depth // 8)
end
-- packbits(src, p, limit, dst, d, n) -> the source offset after decoding n bytes into dst at d | nil
local function packbits(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): number?
local e = d + n
while d < e do
if p >= limit then
return nil
end
local h = readu8(src, p)
p += 1
if h < 128 then
local c = h + 1
if p + c > limit or d + c > e then
return nil
end
bcopy(dst, d, src, p, c)
p += c
d += c
elseif h > 128 then
local c = 257 - h
if p >= limit or d + c > e then
return nil
end
bfill(dst, d, readu8(src, p), c)
p += 1
d += c
end
end
return p
end
-- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil
function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number)
local size = if psb then 4 else 2
if rows < 0 or p + rows * size > limit then
return nil, p
end
local counts = table.create(rows)
for i = 1, rows do
if psb then
counts[i] = byteswap(readu32(src, p))
else
counts[i] = readu8(src, p) * 256 + readu8(src, p + 1)
end
p += size
end
return counts, p
end
-- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message
function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?)
for i = 0, rows - 1 do
local c = counts[first + i] or 0
if p + c > limit then
return nil, "RLE row past the end"
end
local q = packbits(src, p, p + c, dst, d + i * rowBytes, rowBytes)
if q == nil then
-- a short or overlong row: keep what decoded, zero the rest (Photoshop is lenient too)
return nil, "bad RLE row"
end
p += c
end
return p, nil
end
-- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place
local function unpredict(plane: buffer, w: number, h: number, depth: number)
if depth == 8 then
for y = 0, h - 1 do
local o = y * w
local acc = readu8(plane, o)
for x = 1, w - 1 do
acc = (acc + readu8(plane, o + x)) % 256
writeu8(plane, o + x, acc)
end
end
elseif depth == 16 then
for y = 0, h - 1 do
local o = y * w * 2
local acc = readu8(plane, o) * 256 + readu8(plane, o + 1)
for x = 1, w - 1 do
local q = o + x * 2
acc = (acc + readu8(plane, q) * 256 + readu8(plane, q + 1)) % 65536
writeu8(plane, q, acc // 256)
writeu8(plane, q + 1, acc % 256)
end
end
elseif depth == 32 then
-- byte deltas over the row, then the row is 4 byte planes (all high bytes first)
local rb = w * 4
local tmp = bcreate(rb)
for y = 0, h - 1 do
local o = y * rb
local acc = readu8(plane, o)
for x = 1, rb - 1 do
acc = (acc + readu8(plane, o + x)) % 256
writeu8(plane, o + x, acc)
end
for x = 0, w - 1 do
writeu8(tmp, x * 4, readu8(plane, o + x))
writeu8(tmp, x * 4 + 1, readu8(plane, o + w + x))
writeu8(tmp, x * 4 + 2, readu8(plane, o + 2 * w + x))
writeu8(tmp, x * 4 + 3, readu8(plane, o + 3 * w + x))
end
bcopy(plane, o, tmp, 0, rb)
end
end
end
-- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the
-- 2-byte compression code and the data of one layer channel.
function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?)
local rb = Channels.rowBytes(w, depth)
local plane = bcreate(rb * h)
if w == 0 or h == 0 then
return plane, nil
end
if p + 2 > limit then
return nil, "channel data past the end"
end
local comp = readu8(src, p) * 256 + readu8(src, p + 1)
p += 2
if comp == 0 then
if p + rb * h > limit then
return nil, "raw channel data past the end"
end
bcopy(plane, 0, src, p, rb * h)
elseif comp == 1 then
local counts, q = Channels.rleCounts(src, p, limit, h, psb)
if not counts then
return nil, "RLE row counts past the end"
end
local ok, err = Channels.rle(src, q, limit, counts, 1, h, rb, plane, 0)
if not ok then
return nil, err
end
elseif comp == 2 or comp == 3 then
local out, err = Deflate.zlib(src, p, limit - p, rb * h)
if not out then
return nil, "ZIP channel: " .. tostring(err)
end
plane = out
if comp == 3 then
unpredict(plane, w, h, depth)
end
else
return nil, "unknown channel compression " .. comp
end
return plane, nil
end
-- sample8(plane, i, depth) -> sample i as 0..255
local function sample8(plane: buffer, i: number, depth: number): number
if depth == 8 then
return readu8(plane, i)
elseif depth == 16 then
return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5)
elseif depth == 32 then
local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller
if f ~= f then
return 0
end
return floor(max(0, min(1, f)) * 255 + 0.5)
end
-- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black
return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255
end
-- swap32(plane): big-endian f32 samples to native order, in place
function Channels.swap32(plane: buffer)
for i = 0, blen(plane) // 4 - 1 do
writeu32(plane, i * 4, byteswap(readu32(plane, i * 4)))
end
end
-- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white)
local function srgb(c: number): number
c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055
return floor(max(0, min(1, c)) * 255 + 0.5)
end
local function lab(l8: number, a8: number, b8: number): (number, number, number)
local L = l8 * 100 / 255
local a, b = a8 - 128, b8 - 128
local fy = (L + 16) / 116
local fx = fy + a / 500
local fz = fy - b / 200
local function f(t: number): number
return if t > 6 / 29 then t * t * t else 3 * (6 / 29) ^ 2 * (t - 4 / 29)
end
local X, Y, Z = 0.95047 * f(fx), f(fy), 1.08883 * f(fz)
local r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z
local g = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z
local bl = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z
return srgb(r), srgb(g), srgb(bl)
end
-- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? }
-- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab)
function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer
local n = w * h
local out = bcreate(n * 4)
local c1, c2, c3, c4 = planes[1], planes[2], planes[3], planes[4]
local alpha = planes.alpha
local bitmapW = (w + 7) // 8
if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then
-- the common case, without a call per sample
local g8 = if mode == 3 and c2 and blen(c2) >= n then c2 else c1
local b8 = if mode == 3 and c3 and blen(c3) >= n then c3 else c1
local a8 = if alpha and blen(alpha) >= n then alpha else nil
for i = 0, n - 1 do
local a = if a8 then readu8(a8, i) else 255
writeu32(out, i * 4, readu8(c1, i) + readu8(g8, i) * 256 + readu8(b8, i) * 65536 + a * 16777216)
end
return out
end
for i = 0, n - 1 do
local r, g, b = 0, 0, 0
if mode == 3 then
r = if c1 then sample8(c1, i, depth) else 0
g = if c2 then sample8(c2, i, depth) else r
b = if c3 then sample8(c3, i, depth) else r
elseif mode == 4 then
local cc = if c1 then sample8(c1, i, depth) else 255
local mm = if c2 then sample8(c2, i, depth) else 255
local yy = if c3 then sample8(c3, i, depth) else 255
local kk = if c4 then sample8(c4, i, depth) else 255
r, g, b = floor(cc * kk / 255 + 0.5), floor(mm * kk / 255 + 0.5), floor(yy * kk / 255 + 0.5)
elseif mode == 2 then
local k = if c1 then readu8(c1, i) else 0
if palette and blen(palette) >= 768 then
r, g, b = readu8(palette, k), readu8(palette, 256 + k), readu8(palette, 512 + k)
else
r, g, b = k, k, k
end
elseif mode == 0 then
local y, x = i // w, i % w
local bit = if c1 then readu8(c1, y * bitmapW + x // 8) // 2 ^ (7 - x % 8) % 2 else 0
r = if bit == 1 then 0 else 255
g, b = r, r
elseif mode == 9 then
local L = if c1 then sample8(c1, i, depth) else 0
local A = if c2 then sample8(c2, i, depth) else 128
local B = if c3 then sample8(c3, i, depth) else 128
r, g, b = lab(L, A, B)
else -- grey, duotone, multichannel: the first channel as grey
r = if c1 then sample8(c1, i, depth) else 0
g, b = r, r
end
local a = if alpha then sample8(alpha, i, depth) else 255
writeu32(out, i * 4, r + g * 256 + b * 65536 + a * 16777216)
end
return out
end
-- gray8(plane, w, h, depth) -> 1 byte per pixel
function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer
local n = w * h
local out = bcreate(n)
for i = 0, n - 1 do
writeu8(out, i, sample8(plane, i, depth))
end
return out
end
-- unmatte(rgba, n): Photoshop stores a transparent merged image matted with white (C * a + 255 * (1 - a)): undo it
function Channels.unmatte(rgba: buffer, n: number)
for i = 0, n - 1 do
local o = i * 4
local a = readu8(rgba, o + 3)
if a == 0 then
writeu32(rgba, o, 0)
elseif a < 255 then
local f = a / 255
for k = 0, 2 do
local v = (readu8(rgba, o + k) - 255 * (1 - f)) / f
writeu8(rgba, o + k, floor(max(0, min(255, v)) + 1e-6))
end
end
end
end
-- matte(rgba, n) -> a copy matted with white (the writer's merged image)
function Channels.matte(rgba: buffer, n: number): buffer
local out = bcreate(n * 4)
bcopy(out, 0, rgba, 0, n * 4)
for i = 0, n - 1 do
local o = i * 4
local a = readu8(out, o + 3)
if a < 255 then
local f = a / 255
for k = 0, 2 do
writeu8(out, o + k, floor(readu8(out, o + k) * f + 255 * (1 - f) + 0.5))
end
end
end
return out
end
-- ------------------------------------------------------------------------------------------------ writer helpers
-- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1)
function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number
local start = d
local i = 0
while i < n do
-- a run of at least 3 equal bytes?
local v = readu8(src, o + i)
local run = 1
while i + run < n and run < 128 and readu8(src, o + i + run) == v do
run += 1
end
if run >= 3 then
writeu8(out, d, 257 - run)
writeu8(out, d + 1, v)
d += 2
i += run
else
-- literals up to the next run of 3
local j = i
while j < n and j - i < 128 do
if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then
break
end
j += 1
end
local c = j - i
writeu8(out, d, c - 1)
bcopy(out, d + 1, src, o + i, c)
d += c + 1
i = j
end
end
return d - start
end
-- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each)
function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer)
local n = w * h
local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n)
if blen(rgba) < n * 4 then
return r, g, b, a
end
for i = 0, n - 1 do
local v = readu32(rgba, i * 4)
writeu8(r, i, v % 256)
writeu8(g, i, v // 256 % 256)
writeu8(b, i, v // 65536 % 256)
writeu8(a, i, v // 16777216)
end
return r, g, b, a
end
-- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code
function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer
local cs = if psb then 4 else 2
local out = bcreate(h * cs + h * (w + w // 128 + 2))
local d = h * cs
for y = 0, h - 1 do
local n = Channels.packRow(plane, y * w, w, out, d)
if psb then
writeu32(out, y * 4, byteswap(n))
else
writeu16(out, y * 2, byteswap(n) // 65536)
end
d += n
end
local res = bcreate(d)
bcopy(res, 0, out, 0, d)
return res
end
return Channels
+758
View File
@@ -0,0 +1,758 @@
--!strict
-- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of
-- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers
-- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode,
-- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct /
-- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image
-- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8.
-- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/Blend
-- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks,
-- clipping, opacity / fill, hidden flags and Unicode names.
-- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer
-- effects, vector masks, colour management, 16 / 32-bit or non-RGB output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Blend = require("@formats/codecs/Blend")
local Channels = require("@formats/layered/psd/Channels")
-- ------------------------------------------------------------------------------------------------ contract
local Psd = {
name = "psd",
category = "layered",
extensions = { "psd", "psb" },
mime = { "image/vnd.adobe.photoshop" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" },
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } },
}
export type DecodeOptions = {
layers: boolean?, -- read the layers (default true; false reads only the merged image)
maxPixels: number?, -- refuse documents / layers larger than this (default 2^26)
maxLayers: number?, -- default 10000
}
export type EncodeOptions = {
composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/Blend)
}
-- ------------------------------------------------------------------------------------------------ constants
local BLEND_KEYS: { [string]: string } = {
norm = "normal",
diss = "dissolve",
dark = "darken",
["mul "] = "multiply",
idiv = "colorBurn",
lbrn = "linearBurn",
dkCl = "darkerColor",
lite = "lighten",
scrn = "screen",
["div "] = "colorDodge",
lddg = "linearDodge",
lgCl = "lighterColor",
over = "overlay",
sLit = "softLight",
hLit = "hardLight",
vLit = "vividLight",
lLit = "linearLight",
pLit = "pinLight",
hMix = "hardMix",
diff = "difference",
smud = "exclusion",
fsub = "subtract",
fdiv = "divide",
["hue "] = "hue",
["sat "] = "saturation",
colr = "color",
["lum "] = "luminosity",
pass = "passThrough",
}
local BLEND_NAMES: { [string]: string } = {}
for k, v in BLEND_KEYS do
BLEND_NAMES[v] = k
end
BLEND_NAMES.add = "lddg"
-- colour channels per mode (the rest are alpha / spot channels)
local COLOR_CHANNELS = { [0] = 1, [1] = 1, [2] = 1, [3] = 3, [4] = 4, [7] = 1, [8] = 1, [9] = 3 }
local MODE_NAMES = { [0] = "bitmap", [1] = "gray", [2] = "indexed", [3] = "rgb", [4] = "cmyk", [7] = "multichannel", [8] = "duotone", [9] = "lab" }
-- additional layer info keys with 8-byte lengths in PSB
local LONG_KEYS = { LMsk = true, Lr16 = true, Lr32 = true, Layr = true, Mt16 = true, Mt32 = true, Mtrn = true, Alph = true, FMsk = true, lnk2 = true, FEid = true, FXid = true, PxSD = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Psd.sniff(r: Bytes.Reader): number
local h = r:peek(6)
if string.sub(h, 1, 4) == "8BPS" and (string.sub(h, 5, 6) == "\0\1" or string.sub(h, 5, 6) == "\0\2") then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Ctx = { psb: boolean, depth: number, mode: number, maxPixels: number, maxLayers: number }
local function len(r: Bytes.Reader, psb: boolean): number
return if psb then r:u64be() else r:u32be()
end
local function utf16be(s: string): string
local out = {}
local i = 1
while i + 1 <= #s do
local c = string.byte(s, i) * 256 + string.byte(s, i + 1)
i += 2
if c >= 0xD800 and c < 0xDC00 and i + 1 <= #s then
local c2 = string.byte(s, i) * 256 + string.byte(s, i + 1)
if c2 >= 0xDC00 and c2 < 0xE000 then
c = 0x10000 + (c - 0xD800) * 1024 + (c2 - 0xDC00)
i += 2
end
end
if c ~= 0 then
table.insert(out, utf8.char(c))
end
end
return table.concat(out)
end
-- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err
local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Err?)
local count = r:i16be()
local absAlpha = count < 0
count = math.abs(count)
if r.err then
return nil, absAlpha, r.err
end
if count > c.maxLayers then
return nil, absAlpha, Err.new(Err.LIMIT, "over " .. c.maxLayers .. " layers")
end
local recs = {}
for li = 1, count do
local top, left, bottom, right = r:i32be(), r:i32be(), r:i32be(), r:i32be()
local nch = r:u16be()
if r.err then
return nil, absAlpha, r.err
end
if nch > 56 then
return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": " .. nch .. " channels", r.pos)
end
local chans = {}
for k = 1, nch do
chans[k] = { id = r:i16be(), size = len(r, c.psb) }
end
if r:string(4) ~= "8BIM" and not r.err then
return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad blend mode signature", r.pos - 4)
end
local key = r:string(4)
local opacity, clipping, flags = r:u8(), r:u8(), r:u8()
r:skip(1)
local extraLen = r:u32be()
if r.err then
return nil, absAlpha, r.err
end
local ex = r:slice(extraLen)
local rec: { [string]: any } = {
top = top,
left = left,
bottom = bottom,
right = right,
chans = chans,
blend = BLEND_KEYS[key] or "normal",
blendKey = key,
opacity = opacity / 255,
clip = clipping ~= 0,
hidden = bit32.band(flags, 2) ~= 0,
flags = flags,
}
-- mask data
local ml = ex:u32be()
if ml > 0 then
local mr = ex:slice(ml)
if ml >= 18 then
rec.mask = { top = mr:i32be(), left = mr:i32be(), bottom = mr:i32be(), right = mr:i32be(), default = mr:u8(), flags = mr:u8() }
end
end
-- blending ranges
ex:skip(ex:u32be())
-- name: Pascal string padded to 4
local nl = ex:u8()
rec.name = ex:string(nl)
ex:skip((4 - (nl + 1) % 4) % 4)
-- additional layer info
while ex:remaining() >= 12 do
local sig = ex:string(4)
if sig ~= "8BIM" and sig ~= "8B64" then
break
end
local k = ex:string(4)
local l = if c.psb and LONG_KEYS[k] then ex:u64be() else ex:u32be()
if ex.err then
break
end
local d = ex:slice(l)
if k == "luni" then
local n = d:u32be()
local s = d:string(math.min(n * 2, d:remaining()))
rec.name = utf16be(s)
elseif k == "lsct" or k == "lsdk" then
rec.section = d:u32be()
if d:remaining() >= 8 and d:string(4) == "8BIM" then
rec.sectionBlend = d:string(4)
end
elseif k == "iOpa" then
rec.fill = d:u8() / 255
elseif k == "lyid" then
rec.id = d:u32be()
end
end
if r.err then
return nil, absAlpha, r.err
end
recs[li] = rec
end
-- channel image data
local b = r.buf
for li, rec in recs do
local w, h = rec.right - rec.left, rec.bottom - rec.top
if w < 0 or h < 0 or w > 300000 or h > 300000 then
return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad bounds", r.pos)
end
if w * h > c.maxPixels then
return nil, absAlpha, Err.new(Err.LIMIT, string.format("layer %d: %d x %d is over the pixel limit", li, w, h))
end
local planes: { [any]: buffer } = {}
for _, ch in rec.chans do
local p = r.pos
if ch.size < 0 or p + ch.size > r.limit then
return nil, absAlpha, Err.new(Err.TRUNCATED, "layer " .. li .. ": channel data past the end", p)
end
r.pos = p + ch.size
local cw, chh = w, h
if ch.id == -2 or ch.id == -3 then
local m = rec.mask
if not m then
continue
end
cw, chh = m.right - m.left, m.bottom - m.top
if cw < 0 or chh < 0 or cw * chh > c.maxPixels then
continue
end
end
if ch.size < 2 then
continue -- an empty channel
end
local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb)
if not plane then
return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. " channel " .. ch.id .. ": " .. tostring(perr), p)
end
if c.depth == 32 then
Channels.swap32(plane)
end
if ch.id == -1 then
planes.alpha = plane
elseif ch.id == -2 then
rec.maskPlane = Channels.gray8(plane, cw, chh, c.depth)
elseif ch.id >= 0 and ch.id < 56 then
planes[ch.id + 1] = plane
end
end
local img = Types.Image.new(w, h)
if w > 0 and h > 0 then
img.pixels = Channels.toRGBA(planes, w, h, c.depth, c.mode, nil)
end
rec.image = img
end
return recs, absAlpha, nil
end
-- records (bottom to top) -> a layer tree
local function tree(recs: { any }): { Types.Layer }
local root: { Types.Layer } = {}
local stack: { { Types.Layer } } = {}
local cur = root
local function layerOf(rec: any): Types.Layer
local l: any = {
name = rec.name,
image = rec.image,
x = rec.left,
y = rec.top,
opacity = rec.opacity,
blend = rec.blend,
visible = not rec.hidden,
}
if rec.clip then
l.clip = true
end
if rec.fill and rec.fill < 1 then
l.fillOpacity = rec.fill
end
if rec.id then
l.id = rec.id
end
if rec.mask and rec.maskPlane then
local m = rec.mask
local mi = Types.Image.new(m.right - m.left, m.bottom - m.top, "gray8")
mi.pixels = rec.maskPlane
l.mask = { image = mi, x = m.left, y = m.top, default = m.default, disabled = bit32.band(m.flags, 2) ~= 0 }
end
return l
end
for _, rec in recs do
local s = rec.section
if s == 3 then
table.insert(stack, cur)
cur = {}
elseif s == 1 or s == 2 then
local g = layerOf(rec)
g.image = Types.Image.new(0, 0)
g.children = cur
if rec.sectionBlend and BLEND_KEYS[rec.sectionBlend] then
g.blend = BLEND_KEYS[rec.sectionBlend]
end
;(g :: any).collapsed = s == 2
cur = table.remove(stack) or root
table.insert(cur, g)
else
table.insert(cur, layerOf(rec))
end
end
-- unbalanced dividers: splice the open groups' layers back in
while #stack > 0 do
local parent = table.remove(stack) :: { Types.Layer }
for _, l in cur do
table.insert(parent, l)
end
cur = parent
end
return cur
end
function Psd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?)
local o: DecodeOptions = opts or {}
local c: Ctx = { psb = false, depth = 8, mode = 3, maxPixels = o.maxPixels or 2 ^ 26, maxLayers = o.maxLayers or 10000 }
if Psd.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not a PSD (bad signature)", r.pos)
end
r:skip(4)
local version = r:u16be()
r:skip(6)
local nch, h, w, depth, mode = r:u16be(), r:u32be(), r:u32be(), r:u16be(), r:u16be()
if r.err then
return nil, r.err
end
c.psb, c.depth, c.mode = version == 2, depth, mode
if nch < 1 or nch > 56 then
return nil, Err.new(Err.CORRUPT, "bad channel count " .. nch)
end
local maxSide = if c.psb then 300000 else 30000
if w < 1 or h < 1 or w > maxSide or h > maxSide then
return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h))
end
if not (depth == 1 or depth == 8 or depth == 16 or depth == 32) then
return nil, Err.new(Err.CORRUPT, "bad depth " .. depth)
end
if COLOR_CHANNELS[mode] == nil then
return nil, Err.new(Err.CORRUPT, "bad colour mode " .. mode)
end
if (mode == 0) ~= (depth == 1) then
return nil, Err.new(Err.UNSUPPORTED, "1-bit data outside bitmap mode")
end
if w * h > c.maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, c.maxPixels))
end
local layered = Types.Layered.new(w, h)
-- colour mode data
local cm = r:slice(r:u32be())
local palette: buffer? = nil
if mode == 2 and cm:size() >= 768 then
palette = cm:bytes(768)
local pal = {}
for i = 0, 255 do
pal[i + 1] = { buffer.readu8(palette :: buffer, i), buffer.readu8(palette :: buffer, 256 + i), buffer.readu8(palette :: buffer, 512 + i), 255 }
end
layered.meta.palette = pal
end
-- image resources
local rr = r:slice(r:u32be())
if r.err then
return nil, r.err
end
local resources = {}
while rr:remaining() >= 12 and rr:string(4) == "8BIM" do
local id = rr:u16be()
local nl = rr:u8()
local name = rr:string(nl)
rr:skip((nl + 1) % 2)
local size = rr:u32be()
if rr.err or size > rr:remaining() then
break
end
local data = rr:bytes(size)
rr:skip(size % 2)
table.insert(resources, { id = id, name = name, data = data })
if id == 0x040F then
layered.meta.icc = data
end
end
layered.meta.resources = resources
-- layer and mask information
local lm = r:slice(len(r, c.psb))
if r.err then
return nil, r.err
end
local recs: { any }? = nil
local absAlpha = false
if o.layers ~= false and lm:size() > 0 then
local liLen = len(lm, c.psb)
local li = lm:slice(liLen)
if lm.err then
return nil, lm.err
end
if liLen > 0 then
local list, aa, lerr = layerRecords(li, c)
if not list then
return nil, lerr
end
recs, absAlpha = list, aa
end
-- global layer mask info, then additional info (16 / 32-bit layers live in Lr16 / Lr32)
lm:skip(lm:u32be())
while not lm.err and lm:remaining() >= 12 do
local sig = lm:string(4)
if sig ~= "8BIM" and sig ~= "8B64" then
break
end
local k = lm:string(4)
local l = if c.psb and LONG_KEYS[k] then lm:u64be() else lm:u32be()
if lm.err then
break
end
local d = lm:slice(l)
if (k == "Lr16" or k == "Lr32" or k == "Layr") and recs == nil then
local list, aa, lerr = layerRecords(d, c)
if not list then
return nil, lerr
end
recs, absAlpha = list, aa
end
lm:align(4)
end
end
if recs then
layered.layers = tree(recs)
end
-- the merged image
local comp = r:u16be()
if r.err then
return nil, r.err
end
local cc = COLOR_CHANNELS[mode]
if mode == 7 then
cc = math.min(nch, 3)
end
local useAlpha = nch > cc and (absAlpha or recs == nil) and mode ~= 7
local nread = math.min(nch, cc + (if useAlpha then 1 else 0))
local rb = Channels.rowBytes(w, depth)
local planes: { [any]: buffer } = {}
local b = r.buf
if comp == 0 then
for k = 1, nread do
local p = r.pos + (k - 1) * rb * h
if p + rb * h > r.limit then
return nil, Err.new(Err.TRUNCATED, "merged image past the end", p)
end
local plane = buffer.create(rb * h)
buffer.copy(plane, 0, b, p, rb * h)
planes[k] = plane
end
elseif comp == 1 then
local counts, q = Channels.rleCounts(b, r.pos, r.limit, h * nch, c.psb)
if not counts then
return nil, Err.new(Err.TRUNCATED, "merged image row counts past the end", r.pos)
end
local p: number = q
for k = 1, nread do
local plane = buffer.create(rb * h)
local np, perr = Channels.rle(b, p, r.limit, counts, (k - 1) * h + 1, h, rb, plane, 0)
if not np then
return nil, Err.new(Err.CORRUPT, "merged image: " .. tostring(perr), p)
end
p = np
planes[k] = plane
end
elseif comp == 2 or comp == 3 then
-- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream
local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb)
if not all then
return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos)
end
for k = 1, nread do
local plane = buffer.create(rb * h)
buffer.copy(plane, 0, all, (k - 1) * rb * h, rb * h)
planes[k] = plane
end
else
return nil, Err.new(Err.CORRUPT, "bad merged image compression " .. comp)
end
if useAlpha then
planes.alpha = planes[cc + 1]
planes[cc + 1] = nil :: any
end
if depth == 32 then
for _, p in planes do
Channels.swap32(p)
end
end
local composite = Types.Image.new(w, h)
composite.pixels = Channels.toRGBA(planes, w, h, depth, mode, palette)
if planes.alpha then
Channels.unmatte(composite.pixels, w * h)
end
composite.meta.source = { format = "psd", bitDepth = depth, colorType = MODE_NAMES[mode] }
layered.meta.composite = composite
layered.meta.source = { format = "psd", version = version, bitDepth = depth, colorMode = MODE_NAMES[mode], channels = nch, psb = c.psb }
return layered, nil
end
-- ------------------------------------------------------------------------------------------------ encode
type Rec = { layer: any, section: number?, name: string }
local function isImage(v: any): boolean
return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and buffer.len(v.pixels) >= v.width * v.height * 4
end
local function pascal(name: string): string
local s = string.gsub(name, "[\128-\255]", "?")
s = string.sub(s, 1, 255)
local pad = (4 - (#s + 1) % 4) % 4
return string.char(#s) .. s .. string.rep("\0", pad)
end
local function block(w: Bytes.Writer, key: string, data: string)
w:string("8BIM")
w:string(key)
local pad = (4 - #data % 4) % 4 -- additional info is padded to 4
w:u32be(#data + pad)
w:string(data)
w:fill(0, pad)
end
local function u32s(v: number): string
return string.char(v // 16777216 % 256, v // 65536 % 256, v // 256 % 256, v % 256)
end
local function luni(name: string): string
local out = {}
local n = 0
for _, cp in utf8.codes(name) do
if cp >= 0x10000 then
local v = cp - 0x10000
local hi, lo = 0xD800 + v // 1024, 0xDC00 + v % 1024
table.insert(out, string.char(hi // 256, hi % 256, lo // 256, lo % 256))
n += 2
else
table.insert(out, string.char(cp // 256, cp % 256))
n += 1
end
end
return u32s(n) .. table.concat(out)
end
function Psd.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then
return nil, Err.new(Err.ARG, "needs a Layered value")
end
local W, H = math.floor(layered.width), math.floor(layered.height)
if W < 1 or H < 1 or W > 300000 or H > 300000 then
return nil, Err.new(Err.ARG, "bad document size")
end
local psb = W > 30000 or H > 30000
-- the records, bottom to top
local recs: { Rec } = {}
local bad: string? = nil
local function walk(list: { any }, depth: number)
for _, l in list do
if type(l) ~= "table" then
bad = "a layer is not a table"
return
end
if type(l.children) == "table" then
if depth > 64 then
bad = "groups nested too deep"
return
end
table.insert(recs, { layer = l, section = 3, name = "</Layer group>" })
walk(l.children, depth + 1)
table.insert(recs, { layer = l, section = if l.collapsed then 2 else 1, name = tostring(l.name or "Group") })
else
if not isImage(l.image) then
bad = "layer " .. tostring(l.name) .. ": needs an rgba8 image"
return
end
table.insert(recs, { layer = l, name = tostring(l.name or "Layer") })
end
end
end
walk(layered.layers, 0)
if bad then
return nil, Err.new(Err.ARG, bad :: string)
end
if #recs > 32767 then
return nil, Err.new(Err.ARG, "too many layers")
end
local function lenW(w: Bytes.Writer, v: number)
if psb then
w:u64be(v)
else
w:u32be(v)
end
end
-- layer records and channel data
local info = Bytes.writer(4096)
local data = Bytes.writer(65536)
info:i16be(-#recs) -- negative: the merged image's first alpha channel is its transparency
for _, rec in recs do
local l = rec.layer
local img = if rec.section then nil else l.image
local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0)
local w, h = if img then img.width else 0, if img then img.height else 0
if rec.section then
x, y = 0, 0
end
info:i32be(y)
info:i32be(x)
info:i32be(y + h)
info:i32be(x + w)
local chans: { { id: number, data: buffer } } = {}
if img and w > 0 and h > 0 then
local pr, pg, pb, pa = Channels.planes8(img.pixels, w, h)
chans = {
{ id = -1, data = Channels.rleChannel(pa, w, h, psb) },
{ id = 0, data = Channels.rleChannel(pr, w, h, psb) },
{ id = 1, data = Channels.rleChannel(pg, w, h, psb) },
{ id = 2, data = Channels.rleChannel(pb, w, h, psb) },
}
else
chans = { { id = -1, data = buffer.create(0) }, { id = 0, data = buffer.create(0) }, { id = 1, data = buffer.create(0) }, { id = 2, data = buffer.create(0) } }
end
-- the mask
local m = if rec.section == nil and type(l.mask) == "table" and type(l.mask.image) == "table" and type(l.mask.image.pixels) == "buffer" then l.mask else nil
local mw, mh = 0, 0
if m then
local mi = m.image
mw, mh = mi.width, mi.height
local plane = mi.pixels
if mi.format == "rgba8" then
plane = (Channels.planes8(mi.pixels, mw, mh))
elseif mi.format ~= "gray8" and mi.format ~= "alpha8" then
return nil, Err.new(Err.ARG, "mask images are gray8 / alpha8 / rgba8")
end
if buffer.len(plane) < mw * mh then
return nil, Err.new(Err.ARG, "bad mask image")
end
table.insert(chans, { id = -2, data = Channels.rleChannel(plane, mw, mh, psb) })
end
info:u16be(#chans)
for _, ch in chans do
info:i16be(ch.id)
lenW(info, buffer.len(ch.data) + 2)
data:u16be(if buffer.len(ch.data) > 0 then 1 else 0)
data:bytes(ch.data)
end
info:string("8BIM")
local blend = if type(l.blend) == "string" then l.blend else "normal"
local key = BLEND_NAMES[blend] or "norm"
if rec.section and rec.section ~= 3 then
key = if blend == "passThrough" then "pass" else key
end
info:string(key)
info:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255))
info:u8(if l.clip and rec.section == nil then 1 else 0)
local flags = 8 -- bit 3: bit 4 is meaningful
if l.visible == false and rec.section ~= 3 then
flags += 2
end
if rec.section then
flags += 16 -- pixel data irrelevant to the appearance
end
info:u8(flags)
info:u8(0)
local ex = Bytes.writer(256)
if m then
ex:u32be(20)
local mx, my = math.floor(tonumber(m.x) or 0), math.floor(tonumber(m.y) or 0)
ex:i32be(my)
ex:i32be(mx)
ex:i32be(my + mh)
ex:i32be(mx + mw)
ex:u8(math.clamp(math.floor(tonumber(m.default) or 0), 0, 255))
ex:u8(if m.disabled then 2 else 0)
ex:u16be(0)
else
ex:u32be(0)
end
ex:u32be(0) -- blending ranges
ex:string(pascal(rec.name))
block(ex, "luni", luni(rec.name))
if rec.section then
block(ex, "lsct", u32s(rec.section) .. (if rec.section ~= 3 then "8BIM" .. key else ""))
end
local fill = tonumber(l.fillOpacity)
if fill and fill < 1 and rec.section == nil then
block(ex, "iOpa", string.char(math.clamp(math.floor(fill * 255 + 0.5), 0, 255)) .. "\0\0\0")
end
local exb = ex:finish()
info:u32be(buffer.len(exb))
info:bytes(exb)
end
info:bytes(data:finish())
if info:tell() % 2 == 1 then
info:u8(0)
end
local infoB = info:finish()
-- the merged image
local comp: Types.Image? = opts and opts.composite
if comp ~= nil and (not isImage(comp) or comp.width ~= W or comp.height ~= H) then
return nil, Err.new(Err.ARG, "opts.composite must be a " .. W .. " x " .. H .. " rgba8 Image")
end
local merged: buffer
if comp then
merged = comp.pixels
else
merged = buffer.create(W * H * 4)
Blend.flatten(layered.layers, merged, W, H, false)
end
local out = Bytes.writer(buffer.len(infoB) + W * H * 4 + 1024)
out:string("8BPS")
out:u16be(if psb then 2 else 1)
out:fill(0, 6)
out:u16be(4)
out:u32be(H)
out:u32be(W)
out:u16be(8)
out:u16be(3)
out:u32be(0) -- colour mode data
out:u32be(0) -- image resources
local lmLen = (if psb then 8 else 4) + buffer.len(infoB) + 4
lenW(out, lmLen)
lenW(out, buffer.len(infoB))
out:bytes(infoB)
out:u32be(0) -- global layer mask info
-- merged: RLE, all row counts first
out:u16be(1)
local pr, pg, pb, pa = Channels.planes8(Channels.matte(merged, W * H), W, H)
local cs = if psb then 4 else 2
local parts = {}
for k, plane in { pr, pg, pb, pa } do
local ch = Channels.rleChannel(plane, W, H, psb)
parts[k] = ch
out:bytes(ch, 0, H * cs)
end
for k = 1, 4 do
out:bytes(parts[k], H * cs)
end
return out:finish(), nil
end
return Psd
+101
View File
@@ -0,0 +1,101 @@
--!strict
-- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an
-- rgba8 Image with the blend modes of codecs/Blend, opacity, groups (isolated, or pass-through), clipping layers and
-- grey layer masks; every frame as an animated Image; walking the leaves.
--
-- local LayerOps = require("@formats/ops/LayerOps")
-- local img = LayerOps.flatten(layered) -- frame 1 / the layers
-- local img3 = LayerOps.flatten(layered, { frame = 3 })
-- local anim = LayerOps.flattenFrames(layered) -- an Image with frames (delays from the Layered frames)
-- for layer, depth in LayerOps.leaves(layered.layers) do ... end
--
-- Never throws: bad values return nil, Err.ARG.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Blend = require("@formats/codecs/Blend")
local LayerOps = {}
export type FlattenOptions = {
frame: number?, -- 1-based animation frame (default: layered.layers, which is frame 1)
hidden: boolean?, -- include hidden layers (default false)
background: { number }?, -- r, g, b, a 0..255 under everything (default transparent)
}
-- flatten(layered, opts?) -> rgba8 Image (layered.width x layered.height) | nil, Err
function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?)
if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" or type(layered.layers) ~= "table" then
return nil, Err.new(Err.ARG, "flatten: needs a Layered value")
end
local o: FlattenOptions = opts or {}
local w, h = math.floor(layered.width), math.floor(layered.height)
if w < 0 or h < 0 or w * h > 2 ^ 28 then
return nil, Err.new(Err.ARG, "flatten: bad size")
end
local layers = layered.layers
if o.frame then
local f = if type(layered.frames) == "table" then layered.frames[o.frame] else nil
if f == nil and o.frame ~= 1 then
return nil, Err.new(Err.ARG, "flatten: no frame " .. tostring(o.frame))
end
if f then
layers = f.layers
end
end
local img = Types.Image.new(w, h)
local bg = o.background
if type(bg) == "table" then
local v = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216
for i = 0, w * h - 1 do
buffer.writeu32(img.pixels, i * 4, v)
end
end
Blend.flatten(layers, img.pixels, w, h, o.hidden == true)
return img, nil
end
-- flattenFrames(layered, opts?) -> an rgba8 Image whose frames are every flattened frame (frame 1 is the image)
function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?)
local first, err = LayerOps.flatten(layered, opts)
if not first then
return nil, err
end
local frames = if type(layered.frames) == "table" then layered.frames else {}
if #frames == 0 then
return first, nil
end
local list: { Types.Frame } = {}
for i, f in frames do
local o: FlattenOptions = table.clone(opts or {}) :: any
o.frame = i
local img = if i == 1 then first else LayerOps.flatten(layered, o)
if not img then
return nil, Err.new(Err.ARG, "flatten: frame " .. i)
end
list[i] = { image = img, delay = tonumber(f.delay) or 0.1, x = 0, y = 0, dispose = "none", blend = "source" }
end
first.frames = list
return first, nil
end
-- leaves(layers) -> iterator of (layer, depth) over the non-group layers of a tree, bottom to top
function LayerOps.leaves(layers: { Types.Layer }): () -> (Types.Layer?, number?)
local stack: { { any } } = { { layers, 0, 0 } }
return function(): (Types.Layer?, number?)
while #stack > 0 do
local top = stack[#stack]
top[2] += 1
local l = top[1][top[2]]
if l == nil then
table.remove(stack)
elseif type(l.children) == "table" then
table.insert(stack, { l.children, 0, top[3] + 1 })
else
return l, top[3]
end
end
return nil, nil
end
end
return LayerOps
+459
View File
@@ -0,0 +1,459 @@
--!strict
-- subtitle/ass: Advanced SubStation Alpha (v4.00+) and SubStation Alpha (v4.00) scripts (the de-facto spec of
-- Aegisub / libass / ffmpeg). Supports: [Script Info] (meta.scriptInfo, in order), the [V4+ Styles] / [V4 Styles]
-- Format + Style lines (subs.styles[name] = { field = value } as strings, meta.styleFormat / meta.styleOrder), the
-- [Events] Format + Dialogue lines (cues with layer, name, margins, effect; Comment lines in meta.comments), any
-- other section kept verbatim (meta.sections: [Fonts], [Graphics], [Aegisub Project Garbage], ...), H:MM:SS.cc times.
-- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become
-- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw.
-- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it,
-- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Ass = {
name = "ass",
category = "subtitle",
extensions = { "ass", "ssa" },
mime = { "text/x-ssa", "text/x-ass" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
}
export type EncodeOptions = {
crlf: boolean?, -- CRLF line ends (default false)
}
-- ------------------------------------------------------------------------------------------------ constants
local STYLE_FORMAT = { "Name", "Fontname", "Fontsize", "PrimaryColour", "SecondaryColour", "OutlineColour", "BackColour", "Bold", "Italic", "Underline", "StrikeOut", "ScaleX", "ScaleY", "Spacing", "Angle", "BorderStyle", "Outline", "Shadow", "Alignment", "MarginL", "MarginR", "MarginV", "Encoding" }
local STYLE_DEFAULT: { [string]: string } = {
Name = "Default",
Fontname = "Arial",
Fontsize = "16",
PrimaryColour = "&Hffffff",
SecondaryColour = "&Hffffff",
OutlineColour = "&H0",
TertiaryColour = "&H0",
BackColour = "&H0",
Bold = "0",
Italic = "0",
Underline = "0",
StrikeOut = "0",
ScaleX = "100",
ScaleY = "100",
Spacing = "0",
Angle = "0",
BorderStyle = "1",
Outline = "1",
Shadow = "0",
Alignment = "2",
MarginL = "10",
MarginR = "10",
MarginV = "10",
AlphaLevel = "0",
Encoding = "0",
}
local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" }
-- event fields -> cue keys (the rest keep their field name)
local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" }
local function trim(s: string): string
return (string.match(s, "^%s*(.-)%s*$")) :: string
end
local function fields(s: string): { string }
local out = {}
for _, f in string.split(s, ",") do
table.insert(out, trim(f))
end
return out
end
-- H:MM:SS.cc (also more / fewer fraction digits) -> seconds | nil
local function time(s: string): number?
local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$")
if not h then
return nil
end
local fr = if f ~= "" then (tonumber(f) :: number) / 10 ^ #(f :: string) else 0
return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + fr
end
-- ASS text -> the shared markup
local TAGS = { i = "i", b = "b", u = "u", s = "s" }
function Ass.toMarkup(raw: string): string
local open: { [string]: boolean } = {}
local out = string.gsub(raw, "{([^}]*)}", function(block: string): string
local acc = {}
for tag, arg in string.gmatch(block, "\\(%a+)([^\\]*)") do
local t = TAGS[tag]
if t then
local on = arg == "" or (tonumber(arg) or 0) ~= 0
if arg == "" then
on = not open[t]
end
if on and not open[t] then
table.insert(acc, "<" .. t .. ">")
open[t] = true
elseif not on and open[t] then
table.insert(acc, "</" .. t .. ">")
open[t] = false
end
elseif tag == "r" then
for _, k in { "s", "u", "b", "i" } do
if open[k] then
table.insert(acc, "</" .. k .. ">")
open[k] = false
end
end
end
end
return table.concat(acc)
end)
out = string.gsub(out, "\\[Nn]", "\n")
out = string.gsub(out, "\\h", "\194\160")
for _, k in { "s", "u", "b", "i" } do
if open[k] then
out ..= "</" .. k .. ">"
end
end
return out
end
-- the shared markup -> ASS text
function Ass.fromMarkup(text: string): string
local s = string.gsub(text, "\r\n?", "\n")
s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close: string, tag: string): string
local t = TAGS[string.lower(tag)]
if not t then
return ""
end
return "{\\" .. t .. (if close == "/" then "0" else "1") .. "}"
end)
s = string.gsub(s, "\n", "\\N")
return s
end
-- ------------------------------------------------------------------------------------------------ sniff
function Ass.sniff(r: Bytes.Reader): number
local head = r:peek(64)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
if string.match(head, "^%s*%[[Ss]cript [Ii]nfo%]") then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 26
if r.limit - r.base > maxBytes then
return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit")
end
if Ass.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "missing [Script Info]", r.base)
end
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
if string.find(s, "\0", 1, true) then
return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format")
end
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
s = string.gsub(s, "\r\n", "\n")
s = string.gsub(s, "\r", "\n")
local subs = Types.Subtitles.new()
local info: { [string]: string } = {}
local infoOrder: { string } = {}
local styleFormat: { string }? = nil
local styleOrder: { string } = {}
local eventFormat: { string } = EVENT_FORMAT
local comments = {}
local sections: { { name: string, lines: { string } } } = {}
local section = ""
local stylesName: string? = nil
for _, line in string.split(s, "\n") do
local name = string.match(line, "^%s*%[(.-)%]%s*$")
if name then
section = string.lower(name)
if section == "v4+ styles" or section == "v4 styles" or section == "v4 styles+" then
stylesName = name
section = "styles"
elseif section ~= "script info" and section ~= "events" then
table.insert(sections, { name = name, lines = {} })
end
continue
end
if section == "script info" then
if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then
table.insert(infoOrder, line) -- a comment line, kept in place
else
local k, v = string.match(line, "^([^:]+):%s?(.*)$")
if k then
k = trim(k)
if info[k] == nil then
table.insert(infoOrder, k)
end
info[k] = v :: string
end
end
elseif section == "styles" then
local k, v = string.match(line, "^%s*(%a+):%s*(.*)$")
if k == "Format" then
styleFormat = fields(v :: string)
elseif k == "Style" then
local fmt = styleFormat or STYLE_FORMAT
local vals = string.split(v :: string, ",")
local st: { [string]: string } = {}
for fi, f in fmt do
st[f] = trim(vals[fi] or "")
end
local sname = st.Name or ""
if subs.styles[sname] == nil then
table.insert(styleOrder, sname)
end
subs.styles[sname] = st
end
elseif section == "events" then
local k, v = string.match(line, "^%s*(%a+):%s?(.*)$")
if k == "Format" then
eventFormat = fields(v :: string)
elseif k == "Dialogue" or k == "Comment" then
local vals: { string } = {}
local rest = v :: string
for fi = 1, #eventFormat do
if fi == #eventFormat then
vals[fi] = rest
else
local c = string.find(rest, ",", 1, true)
if not c then
vals[fi] = rest
rest = ""
else
vals[fi] = string.sub(rest, 1, c - 1)
rest = string.sub(rest, c + 1)
end
end
end
local cue: { [string]: any } = { text = "", start = 0, stop = 0 }
local ok = true
for fi, f in eventFormat do
local val = vals[fi] or ""
if f == "Start" or f == "End" then
local t = time(val)
if not t then
ok = false
else
cue[if f == "Start" then "start" else "stop"] = t
end
elseif f == "Text" then
cue.raw = val
cue.text = Ass.toMarkup(val)
elseif f == "Style" then
cue.style = trim(val)
elseif f == "Layer" then
cue.layer = tonumber(trim(val)) or 0
else
cue[EVENT_KEY[f] or f] = trim(val)
end
end
if ok then
if k == "Comment" then
cue.after = #subs.cues -- written back after that many dialogue lines
table.insert(comments, cue)
else
table.insert(subs.cues, cue :: any)
end
end
end
elseif section ~= "" then
table.insert(sections[#sections].lines, line)
end
end
subs.meta.scriptInfo = info
subs.meta.scriptInfoOrder = infoOrder
subs.meta.styleFormat = styleFormat
subs.meta.styleOrder = styleOrder
subs.meta.stylesSection = stylesName
subs.meta.eventFormat = eventFormat
if #comments > 0 then
subs.meta.comments = comments
end
if #sections > 0 then
-- drop trailing blank lines (the writer adds its own)
for _, sec in sections do
while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do
table.remove(sec.lines)
end
end
subs.meta.sections = sections
end
subs.meta.source = { format = "ass", scriptType = info.ScriptType }
return subs, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function stamp(t: number): string
local cs = math.floor(t * 100 + 0.5)
return string.format("%d:%02d:%02d.%02d", cs // 360000, cs // 6000 % 60, cs // 100 % 60, cs % 100)
end
local function field(v: any): string
return (string.gsub(tostring(v), "[\r\n,]", " "))
end
function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(subs) ~= "table" or type(subs.cues) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Subtitles value")
end
local meta: any = if type(subs.meta) == "table" then subs.meta else {}
local out = { "[Script Info]" }
local info: any = if type(meta.scriptInfo) == "table" then meta.scriptInfo else {}
local order = if type(meta.scriptInfoOrder) == "table" then meta.scriptInfoOrder else {}
local written: { [string]: boolean } = {}
if info.ScriptType == nil then
table.insert(out, "ScriptType: v4.00+")
end
for _, k in order do
if type(k) == "string" and (string.sub(k, 1, 1) == ";" or string.sub(k, 1, 1) == "!") then
table.insert(out, k)
elseif info[k] ~= nil and not written[k] then
table.insert(out, k .. ": " .. tostring(info[k]))
written[k] = true
end
end
local rest = {}
for k, v in info do
if not written[k] and type(k) == "string" then
table.insert(rest, k .. ": " .. string.gsub(tostring(v), "[\r\n]", " "))
end
end
table.sort(rest)
table.move(rest, 1, #rest, #out + 1, out)
-- styles
local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00"
local sfmt: { string } = if type(meta.styleFormat) == "table" then meta.styleFormat else STYLE_FORMAT
table.insert(out, "")
table.insert(out, "[" .. (if type(meta.stylesSection) == "string" then meta.stylesSection elseif ssa then "V4 Styles" else "V4+ Styles") .. "]")
table.insert(out, "Format: " .. table.concat(sfmt, ", "))
local names: { string } = {}
local seen: { [string]: boolean } = {}
if type(meta.styleOrder) == "table" then
for _, nm in meta.styleOrder do
if type(nm) == "string" and type(subs.styles) == "table" and subs.styles[nm] ~= nil and not seen[nm] then
table.insert(names, nm)
seen[nm] = true
end
end
end
local extra = {}
if type(subs.styles) == "table" then
for nm, st in subs.styles do
if type(nm) == "string" and type(st) == "table" and not seen[nm] then
table.insert(extra, nm)
end
end
end
table.sort(extra)
table.move(extra, 1, #extra, #names + 1, names)
if #names == 0 then
names = { "Default" }
end
for _, nm in names do
local st = if type(subs.styles) == "table" and type(subs.styles[nm]) == "table" then subs.styles[nm] else {}
local vals = {}
for fi, f in sfmt do
local v = if f == "Name" then nm else st[f]
vals[fi] = field(if v ~= nil then v else (STYLE_DEFAULT[f] or "0"))
end
table.insert(out, "Style: " .. table.concat(vals, ","))
end
-- events
local efmt: { string } = if type(meta.eventFormat) == "table" then meta.eventFormat else EVENT_FORMAT
if efmt[#efmt] ~= "Text" then
return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text")
end
table.insert(out, "")
table.insert(out, "[Events]")
table.insert(out, "Format: " .. table.concat(efmt, ", "))
local function event(kind: string, c: any, i: number): Err.Err?
if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then
return Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string")
end
local vals = {}
for fi, f in efmt do
local v: any
if f == "Start" then
v = stamp(c.start)
elseif f == "End" then
v = stamp(c.stop)
elseif f == "Style" then
v = field(c.style or names[1])
elseif f == "Text" then
if type(c.raw) == "string" and Ass.toMarkup(c.raw) == c.text then
v = string.gsub(c.raw, "[\r\n]", " ")
else
v = Ass.fromMarkup(c.text)
end
elseif f == "Layer" then
v = tostring(tonumber(c.layer) or 0)
elseif f == "Marked" then
v = field(c.marked or "Marked=0")
else
local key = EVENT_KEY[f] or f
local x = c[key]
v = field(if x ~= nil then x elseif string.sub(f, 1, 6) == "Margin" then "0" else "")
end
vals[fi] = v
end
table.insert(out, kind .. ": " .. table.concat(vals, ","))
return nil
end
local comments = if type(meta.comments) == "table" then meta.comments else {}
local function commentsAfter(n: number?): Err.Err?
for i, c in comments do
if (type(c) == "table" and c.after == n) or (n == nil and (type(c) ~= "table" or type(c.after) ~= "number" or c.after > #subs.cues)) then
local e = event("Comment", c, i)
if e then
return e
end
end
end
return nil
end
for i = 0, #subs.cues do
local e = (if i > 0 then event("Dialogue", subs.cues[i], i) else nil) or commentsAfter(i)
if e then
return nil, e
end
end
local e = commentsAfter(nil)
if e then
return nil, e
end
if type(meta.sections) == "table" then
for _, sec in meta.sections do
if type(sec) == "table" and type(sec.name) == "string" and type(sec.lines) == "table" then
table.insert(out, "")
table.insert(out, "[" .. sec.name .. "]")
for _, l in sec.lines do
table.insert(out, tostring(l))
end
end
end
end
table.insert(out, "")
local nl = if opts and opts.crlf then "\r\n" else "\n"
return buffer.fromstring(table.concat(out, nl)), nil
end
return Ass
+181
View File
@@ -0,0 +1,181 @@
--!strict
-- subtitle/srt: SubRip text (the de-facto format; matches ffmpeg's srt demuxer / muxer). Supports: numbered or
-- unnumbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm` timings (also `.` decimals and 1..3 fraction digits), the trailing
-- `X1:.. Y1:..` coordinates (kept in cue.settings), multi-line text with blank lines inside a cue (a blank line ends
-- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> /
-- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text.
-- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Srt = {
name = "srt",
category = "subtitle",
extensions = { "srt" },
mime = { "application/x-subrip", "text/srt" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = false },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
}
export type EncodeOptions = {
crlf: boolean?, -- CRLF line ends (default false: LF)
}
-- ------------------------------------------------------------------------------------------------ constants
local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$"
-- text of the reader's range: BOM stripped, line ends normalised to LF; nil when it holds NUL bytes (binary)
local function text(r: Bytes.Reader): string?
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
if string.find(s, "\0", 1, true) then
return nil
end
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
s = string.gsub(s, "\r\n", "\n")
s = string.gsub(s, "\r", "\n")
return s
end
local function frac(digits: string): number
return (tonumber(digits) :: number) / 10 ^ #digits
end
-- timing(line) -> start, stop, settings | nil
local function timing(line: string): (number?, number?, string?)
local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING)
if not h1 then
return nil, nil, nil
end
local a = tonumber(h1) :: number * 3600 + tonumber(m1) :: number * 60 + tonumber(s1) :: number + frac(f1 :: string)
local b = tonumber(h2) :: number * 3600 + tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string)
return a, b, rest
end
-- ------------------------------------------------------------------------------------------------ sniff
function Srt.sniff(r: Bytes.Reader): number
local head = r:peek(512)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
head = string.gsub(head, "\r", "\n")
local first, second = string.match(head, "^%s*([^\n]*)\n([^\n]*)")
if first and string.match(first, "^%d+%s*$") and second and timing(second) then
return 0.9
end
if first and timing(first) then
return 0.6
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 26
if r.limit - r.base > maxBytes then
return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit")
end
local s = text(r)
if not s then
return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format")
end
local lines = string.split(s, "\n")
local n = #lines
local subs = Types.Subtitles.new()
local i = 1
local function isStart(k: number): boolean -- a cue starts at line k (index + timing, or a timing)
local l = lines[k]
if l == nil then
return false
end
if timing(l) then
return true
end
return string.match(l, "^%s*%d+%s*$") ~= nil and lines[k + 1] ~= nil and timing(lines[k + 1]) ~= nil
end
while i <= n do
local line = lines[i]
local a, b, settings = timing(line)
if a then
local id: string? = nil
if i > 1 then
local prev = string.match(lines[i - 1], "^%s*(%d+)%s*$")
id = prev
end
i += 1
local body = {}
while i <= n do
local l = lines[i]
if string.match(l, "^%s*$") then
-- blank: the end of the cue unless more text follows before the next cue
local k = i
while k <= n and string.match(lines[k], "^%s*$") do
k += 1
end
if k > n or isStart(k) then
break
end
for _ = i, k - 1 do
table.insert(body, "")
end
i = k
elseif timing(l) then
break -- a cue without the blank separator
else
table.insert(body, l)
i += 1
end
end
-- an index line right before the next timing belongs to the next cue
if #body > 0 and i <= n and timing(lines[i]) and string.match(body[#body], "^%s*%d+%s*$") then
table.remove(body)
end
local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(body, "\n"), id = id }
if settings and settings ~= "" then
cue.settings = settings
end
table.insert(subs.cues, cue)
else
i += 1
end
end
if #subs.cues == 0 and string.find(s, "%S") then
return nil, Err.new(Err.CORRUPT, "no cues (no `-->` timing line)")
end
subs.meta.source = { format = "srt" }
return subs, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function stamp(t: number): string
local ms = math.floor(t * 1000 + 0.5)
return string.format("%02d:%02d:%02d,%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000)
end
function Srt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(subs) ~= "table" or type(subs.cues) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Subtitles value")
end
local nl = if opts and opts.crlf then "\r\n" else "\n"
local out = table.create(#subs.cues)
for i, c in subs.cues do
if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then
return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string")
end
-- blank lines inside the text are fine: the decoder ends a cue at a blank line only before the next cue
local body = string.gsub(c.text, "\r\n?", "\n")
local settings = if type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") then " " .. c.settings else ""
out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl
end
return buffer.fromstring(table.concat(out, nl) .. nl), nil
end
return Srt
+212
View File
@@ -0,0 +1,212 @@
--!strict
-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the WEBVTT header (its trailing text and header lines kept in
-- meta.header), cue identifiers, `[hh:]mm:ss.ttt` timings, cue settings (cue.settings, as written), NOTE comments
-- (meta.notes), STYLE blocks (meta.css) and REGION blocks (meta.regions); BOM, CRLF / CR line ends. Cue text is kept
-- as written (<i> / <b> / <c.class> / <v Name> spans, timestamps, entities).
-- Encode: the header, STYLE / REGION blocks, then the cues (times to the millisecond); blank lines inside cue text
-- are dropped and `-->` escaped (WebVTT cue text cannot hold them).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Vtt = {
name = "vtt",
category = "subtitle",
extensions = { "vtt", "webvtt" },
mime = { "text/vtt" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
}
export type EncodeOptions = {}
-- ------------------------------------------------------------------------------------------------ constants
local function frac(digits: string): number
return (tonumber(digits) :: number) / 10 ^ #digits
end
-- one timestamp at the start of s: seconds, the rest | nil
local function timestamp(s: string): (number?, string)
local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$")
if h then
return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + frac(f :: string), rest :: string
end
local m2, s2, f2, rest2 = string.match(s, "^(%d+):(%d%d)%.(%d+)(.*)$")
if m2 then
return tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string), rest2 :: string
end
return nil, s
end
-- timing(line) -> start, stop, settings | nil
local function timing(line: string): (number?, number?, string?)
local a, rest = timestamp((string.gsub(line, "^%s+", "")))
if not a then
return nil, nil, nil
end
local after = string.match(rest, "^%s*%-%->%s*(.*)$")
if not after then
return nil, nil, nil
end
local b, rest2 = timestamp(after)
if not b then
return nil, nil, nil
end
local settings = string.match(rest2, "^%s*(.-)%s*$") or ""
return a, b, settings
end
-- ------------------------------------------------------------------------------------------------ sniff
function Vtt.sniff(r: Bytes.Reader): number
local head = r:peek(10)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
if string.sub(head, 1, 6) == "WEBVTT" then
local c = string.sub(head, 7, 7)
if c == "" or c == " " or c == "\t" or c == "\n" or c == "\r" then
return 1
end
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 26
if r.limit - r.base > maxBytes then
return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit")
end
if Vtt.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "missing the WEBVTT signature", r.base)
end
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
if string.find(s, "\0", 1, true) then
return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format")
end
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
s = string.gsub(s, "\r\n", "\n")
s = string.gsub(s, "\r", "\n")
local lines = string.split(s, "\n")
local n = #lines
local subs = Types.Subtitles.new()
-- the header block: WEBVTT[ text] + lines up to the first blank
local header = { (string.match(lines[1], "^WEBVTT[ \t]*(.*)$")) or "" }
local i = 2
while i <= n and lines[i] ~= "" do
table.insert(header, lines[i])
i += 1
end
if #header > 1 or header[1] ~= "" then
subs.meta.header = table.concat(header, "\n")
end
local notes, css, regions = {}, {}, {}
while i <= n do
if lines[i] == "" then
i += 1
continue
end
-- a block: lines up to the next blank
local first = i
while i <= n and lines[i] ~= "" do
i += 1
end
local block = table.move(lines, first, i - 1, 1, {})
local head = block[1]
if string.match(head, "^NOTE[ \t]") or head == "NOTE" then
table.insert(notes, (string.gsub(table.concat(block, "\n"), "^NOTE[ \t]?", "")))
elseif (head == "STYLE" or string.match(head, "^STYLE[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then
table.insert(css, table.concat(block, "\n", 2))
elseif (head == "REGION" or string.match(head, "^REGION[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then
table.insert(regions, table.concat(block, "\n", 2))
else
local k, id = 1, nil
local a, b, settings = timing(block[1])
if not a and block[2] then
id = block[1]
k = 2
a, b, settings = timing(block[2])
end
if a then
local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(block, "\n", k + 1), id = id }
if settings and settings ~= "" then
cue.settings = settings
end
table.insert(subs.cues, cue)
end
-- a block with no timing is skipped (the spec's parser ignores it)
end
end
if #notes > 0 then
subs.meta.notes = notes
end
if #css > 0 then
subs.meta.css = css
end
if #regions > 0 then
subs.meta.regions = regions
end
subs.meta.source = { format = "vtt" }
return subs, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function stamp(t: number): string
local ms = math.floor(t * 1000 + 0.5)
return string.format("%02d:%02d:%02d.%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000)
end
-- one block's text: no blank lines (they end a block), no `-->`
local function clean(s: string): string
s = string.gsub(s, "\r\n?", "\n")
s = string.gsub(s, "\n[ \t]*\n", "\n")
s = string.gsub(s, "\n[ \t]*\n", "\n")
s = string.gsub(s, "^\n+", "")
s = string.gsub(s, "%-%->", "--&gt;")
return s
end
function Vtt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(subs) ~= "table" or type(subs.cues) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Subtitles value")
end
local meta: any = if type(subs.meta) == "table" then subs.meta else {}
local out = {}
local header = if type(meta.header) == "string" and meta.header ~= "" then meta.header else nil
if header then
local h = string.gsub(clean(header), "%-%-&gt;", "")
table.insert(out, "WEBVTT " .. h .. "\n")
else
table.insert(out, "WEBVTT\n")
end
for _, key in { "regions", "css" } do
local list = meta[key]
if type(list) == "table" then
for _, b in list do
if type(b) == "string" then
table.insert(out, (if key == "css" then "STYLE\n" else "REGION\n") .. clean(b) .. "\n")
end
end
end
end
for i, c in subs.cues do
if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then
return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string")
end
local id = if type(c.id) == "string" and c.id ~= "" and not string.find(c.id, "-->", 1, true) then (string.gsub(c.id, "[\r\n]", " ")) .. "\n" else ""
local settings = if type(c.settings) == "string" and c.settings ~= "" then " " .. (string.gsub(c.settings, "[\r\n]", " ")) else ""
local body = clean(c.text)
table.insert(out, id .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. "\n" .. body .. (if body ~= "" then "\n" else ""))
end
return buffer.fromstring(table.concat(out, "\n")), nil
end
return Vtt
+758
View File
@@ -0,0 +1,758 @@
--!strict
-- vector/svg/Parse: an SVG document (a codecs/Xml tree) to a Types.Vector: the cascade (presentation attributes,
-- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space
-- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into
-- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a
-- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>.
-- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported.
-- Never throws.
local Xml = require("@formats/codecs/Xml")
local Types = require("@formats/Types")
local Style = require("@formats/vector/svg/Style")
local PathData = require("@formats/vector/svg/PathData")
local Parse = {}
type Node = Types.XmlNode
type M = { number }
local IDENTITY = { 1, 0, 0, 1, 0, 0 }
local mul = Style.multiply
-- properties that inherit, and their initial values
local INHERITED: { [string]: string } = {
fill = "black",
["fill-opacity"] = "1",
["fill-rule"] = "nonzero",
stroke = "none",
["stroke-width"] = "1",
["stroke-opacity"] = "1",
["stroke-linecap"] = "butt",
["stroke-linejoin"] = "miter",
["stroke-miterlimit"] = "4",
["stroke-dasharray"] = "none",
["stroke-dashoffset"] = "0",
["clip-rule"] = "nonzero",
visibility = "visible",
color = "black",
["font-size"] = "16",
}
-- not inherited (reset per element)
local LOCAL: { [string]: boolean } = {
opacity = true,
["clip-path"] = true,
display = true,
["stop-color"] = true,
["stop-opacity"] = true,
mask = true,
filter = true,
}
local UNSUPPORTED = { text = true, image = true, pattern = true, mask = true, marker = true, filter = true, foreignObject = true, textPath = true, tspan = true }
local CONTAINERS = { g = true, a = true, switch = true }
local SHAPES = { path = true, rect = true, circle = true, ellipse = true, line = true, polyline = true, polygon = true }
type Ctx = {
ids: { [string]: Node },
rules: { Style.Rule },
vector: Types.Vector,
groups: { any },
clips: { any },
unsupported: { [string]: number },
vw: number, -- the current viewport (for percentages)
vh: number,
depth: number,
useDepth: number,
}
local function local_(n: Node): string
return Xml.localName(n.name)
end
local function attr(n: Node, k: string): string?
local a = n.attrs :: any
return a[k]
end
local function href(n: Node): string?
local h = attr(n, "href") or attr(n, "xlink:href")
if h == nil then
for k, v in pairs(n.attrs :: any) do
if type(k) == "string" and Xml.localName(k) == "href" then
return v
end
end
end
return h
end
local function refId(s: string?): string?
if s == nil then
return nil
end
return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)")
end
-- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style=""
local function specified(n: Node, ctx: Ctx): { [string]: string }
local out: { [string]: string } = {}
for k, v in pairs(n.attrs :: any) do
if type(k) == "string" and type(v) == "string" and (INHERITED[k] or LOCAL[k]) then
out[k] = v
end
end
if #ctx.rules > 0 then
local classes: { [string]: boolean } = {}
for c in string.gmatch(attr(n, "class") or "", "%S+") do
classes[c] = true
end
local hits = {}
for _, r in ctx.rules do
if Style.matches(r.selector, local_(n), attr(n, "id"), classes) then
table.insert(hits, r)
end
end
table.sort(hits, function(a: any, b: any): boolean
if a.selector.specificity ~= b.selector.specificity then
return a.selector.specificity < b.selector.specificity
end
return a.order < b.order
end)
for _, r in hits do
for k, v in pairs(r.decls) do
out[k] = v
end
end
end
local st = attr(n, "style")
if st then
for k, v in pairs(Style.declarations(st)) do
out[k] = v
end
end
return out
end
-- computed(parent, n) -> the element's computed property strings
local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string }
local out: { [string]: string } = {}
for k in pairs(INHERITED) do
out[k] = parent[k]
end
for k, v in pairs(specified(n, ctx)) do
if v == "inherit" then
out[k] = parent[k]
elseif INHERITED[k] or LOCAL[k] then
out[k] = v
end
end
return out
end
local function len(s: string?, ref: number, st: { [string]: string }, default: number?): number?
local fs = Style.length(st["font-size"], 16) or 16
local v = Style.length(s, ref, fs)
if v == nil then
return default
end
return v
end
-- ------------------------------------------------------------------------------------------------ paints
local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number } }
local list = {}
local parentStyle = computed(INHERITED, g, ctx)
for _, s in Xml.children(g) do
if local_(s) == "stop" then
local st = computed(parentStyle, s, ctx)
local off = attr(s, "offset") or "0"
local o = tonumber(string.match(off, "^%s*([%d.eE+-]+)%s*%%%s*$") or "")
local offset = if o then o / 100 else (tonumber(off) or 0)
offset = math.clamp(offset, 0, 1)
if #list > 0 and offset < list[#list][1] then
offset = list[#list][1]
end
local col = Style.color(st["stop-color"] or "black", Style.color(st.color or "black")) or { 0, 0, 0, 255 }
if col == "none" then
col = { 0, 0, 0, 0 }
end
local op = math.clamp(tonumber(st["stop-opacity"] or "1") or 1, 0, 1)
table.insert(list, { offset, col[1], col[2], col[3], math.floor(col[4] * op + 0.5) })
end
end
if #list == 0 then
local h = refId(href(g))
local other = if h then ctx.ids[h] else nil
if other and not seen[other] then
seen[other] = true
return stops(other, ctx, seen)
end
end
return list
end
-- a gradient attribute, looked up through href templates
local function gattr(g: Node, k: string, ctx: Ctx): string?
local cur: Node? = g
local guard = 0
while cur and guard < 16 do
local v = attr(cur, k)
if v ~= nil then
return v
end
local h = refId(href(cur))
cur = if h then ctx.ids[h] else nil
guard += 1
end
return nil
end
local function gradient(g: Node, opacity: number, ctx: Ctx): any
local kind = local_(g)
local units = gattr(g, "gradientUnits", ctx) or "objectBoundingBox"
local obb = units ~= "userSpaceOnUse"
local list = stops(g, ctx, { [g] = true })
if #list == 0 then
return "none"
end
if #list == 1 then
local s = list[1]
return { type = "color", color = { s[2], s[3], s[4], math.floor(s[5] * opacity + 0.5) } }
end
local function coord(k: string, default: string, ref: number): number
local v = gattr(g, k, ctx) or default
local pct = string.match(v, "^%s*([%d.eE+-]+)%s*%%%s*$")
if pct then
local x = tonumber(pct) or 0
return if obb then x / 100 else x / 100 * ref
end
return Style.length(v, ref) or 0
end
local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2)
local p: any = {
type = if kind == "linearGradient" then "linear" else "radial",
units = if obb then "objectBoundingBox" else "userSpaceOnUse",
spread = gattr(g, "spreadMethod", ctx) or "pad",
stops = list,
opacity = opacity,
}
local t = gattr(g, "gradientTransform", ctx)
if t then
p.transform = Style.transform(t)
end
if p.type == "linear" then
p.x1, p.y1 = coord("x1", "0%", ctx.vw), coord("y1", "0%", ctx.vh)
p.x2, p.y2 = coord("x2", "100%", ctx.vw), coord("y2", "0%", ctx.vh)
else
p.cx, p.cy = coord("cx", "50%", ctx.vw), coord("cy", "50%", ctx.vh)
p.r = coord("r", "50%", diag)
p.fx = if gattr(g, "fx", ctx) then coord("fx", "50%", ctx.vw) else p.cx
p.fy = if gattr(g, "fy", ctx) then coord("fy", "50%", ctx.vh) else p.cy
p.fr = coord("fr", "0%", diag)
end
return p
end
-- paint(value, opacity, st) -> Paint | nil (none)
local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any
if value == nil then
return nil
end
local id = string.match(value, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)%s*(.*)$")
if id then
local fallback = string.match(value, "%)%s*(.-)%s*$")
local g = ctx.ids[id]
if g and (local_(g) == "linearGradient" or local_(g) == "radialGradient") then
local p = gradient(g, opacity, ctx)
return if p == "none" then nil else p
end
if g and local_(g) == "pattern" then
ctx.unsupported.pattern = (ctx.unsupported.pattern or 0) + 1
end
if fallback and fallback ~= "" then
return paint(fallback, opacity, st, ctx)
end
return nil
end
local c = Style.color(value, Style.color(st.color or "black") :: any)
if c == nil or c == "none" then
return nil
end
return { type = "color", color = { c[1], c[2], c[3], math.floor(c[4] * opacity + 0.5) } }
end
-- ------------------------------------------------------------------------------------------------ shapes
local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cmd }?
local kind = local_(n)
local vw, vh = ctx.vw, ctx.vh
local diag = math.sqrt((vw * vw + vh * vh) / 2)
if kind == "path" then
local d = attr(n, "d")
if d == nil then
return nil
end
local cmds = PathData.parse(d)
return cmds
elseif kind == "rect" then
local x, y = len(attr(n, "x"), vw, st, 0) :: number, len(attr(n, "y"), vh, st, 0) :: number
local w, h = len(attr(n, "width"), vw, st, 0) :: number, len(attr(n, "height"), vh, st, 0) :: number
if w <= 0 or h <= 0 then
return nil
end
local rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st)
if rx and rx < 0 then
rx = nil
end
if ry and ry < 0 then
ry = nil
end
rx = rx or ry or 0
ry = ry or rx
rx, ry = math.min(rx :: number, w / 2), math.min(ry :: number, h / 2)
if rx <= 0 or ry <= 0 then
return { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } }
end
local out: { PathData.Cmd } = { { op = "M", x + rx, y }, { op = "L", x + w - rx, y } }
PathData.arc(x + w - rx, y, rx, ry, 0, false, true, x + w, y + ry, out)
table.insert(out, { op = "L", x + w, y + h - ry })
PathData.arc(x + w, y + h - ry, rx, ry, 0, false, true, x + w - rx, y + h, out)
table.insert(out, { op = "L", x + rx, y + h })
PathData.arc(x + rx, y + h, rx, ry, 0, false, true, x, y + h - ry, out)
table.insert(out, { op = "L", x, y + ry })
PathData.arc(x, y + ry, rx, ry, 0, false, true, x + rx, y, out)
table.insert(out, { op = "Z" })
return out
elseif kind == "circle" or kind == "ellipse" then
local cx, cy = len(attr(n, "cx"), vw, st, 0) :: number, len(attr(n, "cy"), vh, st, 0) :: number
local rx, ry
if kind == "circle" then
rx = len(attr(n, "r"), diag, st, 0) :: number
ry = rx
else
rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st)
rx = rx or ry or 0
ry = ry or rx
end
if (rx :: number) <= 0 or (ry :: number) <= 0 then
return nil
end
local out: { PathData.Cmd } = { { op = "M", cx + rx, cy } }
PathData.arc(cx + rx, cy, rx, ry, 0, false, true, cx, cy + ry, out)
PathData.arc(cx, cy + ry, rx, ry, 0, false, true, cx - rx, cy, out)
PathData.arc(cx - rx, cy, rx, ry, 0, false, true, cx, cy - ry, out)
PathData.arc(cx, cy - ry, rx, ry, 0, false, true, cx + rx, cy, out)
table.insert(out, { op = "Z" })
return out
elseif kind == "line" then
local x1, y1 = len(attr(n, "x1"), vw, st, 0) :: number, len(attr(n, "y1"), vh, st, 0) :: number
local x2, y2 = len(attr(n, "x2"), vw, st, 0) :: number, len(attr(n, "y2"), vh, st, 0) :: number
return { { op = "M", x1, y1 }, { op = "L", x2, y2 } }
elseif kind == "polyline" or kind == "polygon" then
local v = Style.numbers(attr(n, "points"))
if #v < 4 then
return nil
end
local out: { PathData.Cmd } = { { op = "M", v[1], v[2] } }
for i = 3, #v - 1, 2 do
table.insert(out, { op = "L", v[i], v[i + 1] })
end
if kind == "polygon" then
table.insert(out, { op = "Z" })
end
return out
end
return nil
end
-- ------------------------------------------------------------------------------------------------ clip paths
local function transformOf(n: Node): M
local t = attr(n, "transform")
if t then
return Style.transform(t) or IDENTITY
end
return IDENTITY
end
-- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox.
local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number?
local cp = ctx.ids[ref]
if cp == nil or local_(cp) ~= "clipPath" then
return nil
end
local base = mul(ctm, transformOf(cp))
if attr(cp, "clipPathUnits") == "objectBoundingBox" then
if not bbox then
return nil
end
base = mul(base, { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] })
end
local cpStyle = computed(st, cp, ctx)
local paths = {}
local function add(n: Node, parentStyle: { [string]: string }, m: M, depth: number)
if depth > 8 then
return
end
local s = computed(parentStyle, n, ctx)
if s.display == "none" or s.visibility == "hidden" then
return
end
local k = local_(n)
local tm = mul(m, transformOf(n))
if SHAPES[k] then
local cmds = shape(n, s, ctx)
if cmds and #cmds > 0 then
table.insert(paths, { d = cmds, transform = tm, rule = s["clip-rule"] or "nonzero" })
end
elseif k == "use" then
local h = refId(href(n))
local target = if h then ctx.ids[h] else nil
if target then
local x, y = len(attr(n, "x"), ctx.vw, s, 0) :: number, len(attr(n, "y"), ctx.vh, s, 0) :: number
add(target, s, mul(tm, { 1, 0, 0, 1, x, y }), depth + 1)
end
end
end
for _, c in Xml.children(cp) do
add(c, cpStyle, base, 0)
end
table.insert(ctx.clips, { paths = paths })
return #ctx.clips
end
-- ------------------------------------------------------------------------------------------------ the walk
local walk: (n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) -> ()
local function bboxOf(cmds: { PathData.Cmd }): { number }?
local x0, y0, x1, y1 = PathData.bounds(cmds)
if not x0 then
return nil
end
return { x0 :: number, y0 :: number, x1 :: number, y1 :: number }
end
local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx)
if st.visibility == "hidden" or st.visibility == "collapse" then
return
end
local cmds = shape(n, st, ctx)
if not cmds or #cmds == 0 then
return
end
local tm = mul(ctm, transformOf(n))
local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1)
local fill = paint(st.fill, math.clamp(tonumber(st["fill-opacity"]) or 1, 0, 1), st, ctx)
local stroke = paint(st.stroke, math.clamp(tonumber(st["stroke-opacity"]) or 1, 0, 1), st, ctx)
local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2)
local sw = len(st["stroke-width"], diag, st, 1) :: number
if sw <= 0 then
stroke = nil
end
if fill == nil and stroke == nil then
return
end
if local_(n) == "line" then
fill = nil -- a line has no inside
end
local clipRef = refId(st["clip-path"])
local clipId: number? = nil
if clipRef then
clipId = clip(clipRef, tm, bboxOf(cmds), st, ctx)
if clipId == nil and ctx.ids[clipRef] then
return -- a broken clip reference (bad units): nothing shows
end
end
-- opacity on a shape with both a fill and a stroke: a group, so the overlap is not counted twice
local g = group
if opacity < 1 and fill and stroke then
table.insert(ctx.groups, { opacity = opacity, parent = group })
g = #ctx.groups
opacity = 1
end
local p: any = {
d = cmds,
fill = fill,
fillRule = if st["fill-rule"] == "evenodd" then "evenodd" else "nonzero",
stroke = stroke,
strokeWidth = sw,
transform = tm,
opacity = opacity,
group = g,
clip = clipId,
id = attr(n, "id"),
}
if stroke then
p.strokeLineJoin = st["stroke-linejoin"]
p.strokeLineCap = st["stroke-linecap"]
p.strokeMiterLimit = tonumber(st["stroke-miterlimit"]) or 4
local dash = st["stroke-dasharray"]
if dash and dash ~= "none" then
local list = {}
local ok = true
for part in string.gmatch(dash, "[^,%s]+") do
local v = len(part, diag, st)
if v == nil or v < 0 then
ok = false
end
table.insert(list, v or 0)
end
local sum = 0
for _, v in list do
sum += v
end
if ok and sum > 0 then
if #list % 2 == 1 then
table.move(list, 1, #list, #list + 1, list)
end
p.strokeDashArray = list
p.strokeDashOffset = len(st["stroke-dashoffset"], diag, st, 0)
end
end
end
table.insert(ctx.vector.paths, p)
end
-- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y)
function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M
if vb == nil or vb[3] <= 0 or vb[4] <= 0 then
return { 1, 0, 0, 1, x, y }
end
local sx, sy = w / vb[3], h / vb[4]
local align, mode = "xmidymid", "meet"
if par then
local a, m = string.match(string.lower(par), "^%s*([%w]+)%s*(%a*)")
if a == "defer" then
a, m = string.match(string.lower(par), "^%s*defer%s+([%w]+)%s*(%a*)")
end
align = a or align
if m and m ~= "" then
mode = m
end
end
if align == "none" then
return { sx, 0, 0, sy, x - vb[1] * sx, y - vb[2] * sy }
end
local s = if mode == "slice" then math.max(sx, sy) else math.min(sx, sy)
local tx, ty = x - vb[1] * s, y - vb[2] * s
local ax, ay = string.match(align, "^x(%a%a%a)y(%a%a%a)$")
if ax == "mid" then
tx += (w - vb[3] * s) / 2
elseif ax == "max" then
tx += w - vb[3] * s
end
if ay == "mid" then
ty += (h - vb[4] * s) / 2
elseif ay == "max" then
ty += h - vb[4] * s
end
return { s, 0, 0, s, tx, ty }
end
local function viewBox(n: Node): { number }?
local v = Style.numbers(attr(n, "viewBox"))
if #v == 4 and v[3] > 0 and v[4] > 0 then
return v
end
return nil
end
local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?)
-- a layer for opacity / clip-path
local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1)
local clipRef = refId(st["clip-path"])
local g = group
if opacity < 1 or clipRef then
local clipId: number? = nil
if clipRef then
local bbox: { number }? = nil
local cp = ctx.ids[clipRef]
if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then
-- the group's bounding box in its user space: walk once into a scratch vector
local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips
local scratch = Types.Vector.new(0, 0)
ctx.vector, ctx.groups, ctx.clips = scratch, {}, {}
for _, c in children or Xml.children(n) do
walk(c, st, IDENTITY, nil, ctx)
end
ctx.vector, ctx.groups, ctx.clips = saveV, saveG, saveC
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
for _, p in scratch.paths do
local b = bboxOf(p.d)
if b then
local m = p.transform or IDENTITY
for _, corner in { { b[1], b[2] }, { b[3], b[2] }, { b[1], b[4] }, { b[3], b[4] } } do
local px = m[1] * corner[1] + m[3] * corner[2] + m[5]
local py = m[2] * corner[1] + m[4] * corner[2] + m[6]
x0, y0, x1, y1 = math.min(x0, px), math.min(y0, py), math.max(x1, px), math.max(y1, py)
end
end
end
if x0 <= x1 then
bbox = { x0, y0, x1, y1 }
end
end
clipId = clip(clipRef, ctm, bbox, st, ctx)
if clipId == nil and cp then
return
end
end
table.insert(ctx.groups, { opacity = opacity, parent = group, clip = clipId })
g = #ctx.groups
end
if local_(n) == "switch" then
-- the first child that renders (conditional attributes are not evaluated)
for _, c in children or Xml.children(n) do
if UNSUPPORTED[local_(c)] == nil then
walk(c, st, ctm, g, ctx)
return
end
end
return
end
for _, c in children or Xml.children(n) do
walk(c, st, ctm, g, ctx)
end
end
-- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own
local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number?
local ov = attr(n, "overflow")
if ov == "visible" or ov == "auto" then
return group
end
local rect = { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } }
table.insert(ctx.clips, { paths = { { d = rect, transform = m, rule = "nonzero" } } })
table.insert(ctx.groups, { opacity = 1, parent = group, clip = #ctx.clips })
return #ctx.groups
end
walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx)
if ctx.depth > 200 then
return
end
local kind = local_(n)
if kind == "defs" or kind == "clipPath" or kind == "linearGradient" or kind == "radialGradient" or kind == "symbol" or kind == "style" or kind == "title" or kind == "desc" or kind == "metadata" then
return
end
local st = computed(parentStyle, n, ctx)
if st.display == "none" then
return
end
if UNSUPPORTED[kind] then
ctx.unsupported[kind] = (ctx.unsupported[kind] or 0) + 1
return
end
ctx.depth += 1
if CONTAINERS[kind] then
container(n, st, mul(ctm, transformOf(n)), group, ctx)
elseif SHAPES[kind] then
emitShape(n, st, ctm, group, ctx)
elseif kind == "use" then
local h = refId(href(n))
local target = if h then ctx.ids[h] else nil
if target and ctx.useDepth < 16 then
ctx.useDepth += 1
local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number
local m = mul(mul(ctm, transformOf(n)), { 1, 0, 0, 1, x, y })
local tk = local_(target)
if tk == "symbol" or tk == "svg" then
local w = len(attr(n, "width") or attr(target, "width") or "100%", ctx.vw, st, ctx.vw) :: number
local h2 = len(attr(n, "height") or attr(target, "height") or "100%", ctx.vh, st, ctx.vh) :: number
local vb = viewBox(target)
local inner = mul(m, Parse.viewTransform(vb, attr(target, "preserveAspectRatio"), 0, 0, w, h2))
local saveW, saveH = ctx.vw, ctx.vh
if vb then
ctx.vw, ctx.vh = vb[3], vb[4]
end
local tst = computed(st, target, ctx)
-- the use element's own opacity applies to the symbol's content too
local uo = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1)
if uo < 1 then
tst.opacity = tostring(uo * math.clamp(tonumber(tst.opacity or "1") or 1, 0, 1))
end
if tst["clip-path"] == nil then
tst["clip-path"] = st["clip-path"]
end
-- the symbol's children as a group of the use element, clipped to its viewport
local vg = viewportGroup(target, m, 0, 0, w, h2, group, ctx)
container(n, tst, mul(inner, transformOf(target)), vg, ctx, Xml.children(target))
ctx.vw, ctx.vh = saveW, saveH
else
-- the referenced element as if it were the use element's only child
container(n, st, m, group, ctx, { target })
end
ctx.useDepth -= 1
end
elseif kind == "svg" then
local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number
local w = len(attr(n, "width") or "100%", ctx.vw, st, ctx.vw) :: number
local h = len(attr(n, "height") or "100%", ctx.vh, st, ctx.vh) :: number
local vb = viewBox(n)
local m = mul(ctm, Parse.viewTransform(vb, attr(n, "preserveAspectRatio"), x, y, w, h))
local saveW, saveH = ctx.vw, ctx.vh
if vb then
ctx.vw, ctx.vh = vb[3], vb[4]
else
ctx.vw, ctx.vh = w, h
end
container(n, st, m, viewportGroup(n, ctm, x, y, w, h, group, ctx), ctx)
ctx.vw, ctx.vh = saveW, saveH
end
ctx.depth -= 1
end
-- ------------------------------------------------------------------------------------------------ entry
-- document(doc, opts) -> Vector | nil, message
function Parse.document(doc: any): (Types.Vector?, string?)
local root = doc.root
if root == nil or Xml.localName(root.name) ~= "svg" then
return nil, "the root element is not <svg>"
end
local ids: { [string]: Node } = {}
local rules: { Style.Rule } = {}
local count = 0
local function index(n: Node)
count += 1
if count > 1000000 then
return
end
local id = attr(n, "id")
if id and ids[id] == nil then
ids[id] = n
end
if local_(n) == "style" then
Style.css(Xml.text(n), rules)
end
for _, c in Xml.children(n) do
index(c)
end
end
index(root)
local vb = viewBox(root)
local w = Style.length(attr(root, "width") or "100%", if vb then vb[3] else 100) or 100
local h = Style.length(attr(root, "height") or "100%", if vb then vb[4] else 100) or 100
if w <= 0 or h <= 0 then
w, h = 100, 100
end
local v = Types.Vector.new(w, h)
v.viewBox = vb or { 0, 0, w, h }
local ctx: Ctx = {
ids = ids,
rules = rules,
vector = v,
groups = {},
clips = {},
unsupported = {},
vw = v.viewBox[3],
vh = v.viewBox[4],
depth = 0,
useDepth = 0,
}
local st = computed(INHERITED, root, ctx)
container(root, st, IDENTITY, nil, ctx)
v.meta.preserveAspectRatio = attr(root, "preserveAspectRatio")
v.meta.groups = ctx.groups
v.meta.clips = ctx.clips
if next(ctx.unsupported) then
v.meta.unsupported = ctx.unsupported
end
return v, nil
end
return Parse
+377
View File
@@ -0,0 +1,377 @@
--!strict
-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands
-- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the
-- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a
-- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the
-- commands so far are kept, as the spec's error handling says).
local PathData = {}
export type Cmd = { op: string, [number]: number }
local byte, sub, find = string.byte, string.sub, string.find
local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math.sin, math.atan2, math.ceil, math.pi
local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 }
-- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out
local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd })
if x1 == x2 and y1 == y2 then
return
end
rx, ry = abs(rx), abs(ry)
if rx == 0 or ry == 0 then
table.insert(out, { op = "L", x2, y2 })
return
end
local phi = phiDeg % 360 * pi / 180
local cp, sp = cos(phi), sin(phi)
local dx, dy = (x1 - x2) / 2, (y1 - y2) / 2
local x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy
local lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry)
if lambda > 1 then
local s = sqrt(lambda)
rx, ry = rx * s, ry * s
end
local num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
local den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
local coef = if den == 0 then 0 else sqrt(math.max(0, num / den))
if fa == fs then
coef = -coef
end
local cxp, cyp = coef * rx * y1p / ry, -coef * ry * x1p / rx
local cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2
local function angle(ux: number, uy: number, vx: number, vy: number): number
return atan2(ux * vy - uy * vx, ux * vx + uy * vy)
end
local ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry
local vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry
local t1 = angle(1, 0, ux, uy)
local dt = angle(ux, uy, vx, vy)
if not fs and dt > 0 then
dt -= 2 * pi
elseif fs and dt < 0 then
dt += 2 * pi
end
local n = math.max(1, ceil(abs(dt) / (pi / 2) - 1e-9))
local step = dt / n
local k = 4 / 3 * math.tan(step / 4)
local px, py = x1, y1
for i = 1, n do
local a0 = t1 + (i - 1) * step
local a1 = t1 + i * step
local c0, s0, c1, s1 = cos(a0), sin(a0), cos(a1), sin(a1)
-- the unit-circle segment's control points, scaled by the radii, rotated by phi, moved to the centre
local e1x, e1y = c0 - k * s0, s0 + k * c0
local e2x, e2y = c1 + k * s1, s1 - k * c1
local ex, ey = c1, s1
local function map(x: number, y: number): (number, number)
x, y = x * rx, y * ry
return cp * x - sp * y + cx, sp * x + cp * y + cy
end
local ax, ay = map(e1x, e1y)
local bx, by = map(e2x, e2y)
local qx, qy = map(ex, ey)
if i == n then
qx, qy = x2, y2
end
table.insert(out, { op = "C", ax, ay, bx, by, qx, qy })
px, py = qx, qy
end
local _ = px + py
end
PathData.arc = arc
-- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing)
function PathData.parse(d: string): ({ Cmd }, boolean)
local out: { Cmd } = {}
local i, n = 1, #d
local cx, cy = 0, 0 -- current point
local sx, sy = 0, 0 -- subpath start
local lcx, lcy = 0, 0 -- last control point (for S / T)
local last = "" -- previous command letter (upper case)
local cmd: string? = nil
local rel = false
local nums: { number } = table.create(7)
local function ws()
while i <= n do
local c = byte(d, i)
if c == 32 or c == 9 or c == 10 or c == 13 or c == 12 then
i += 1
else
break
end
end
end
local function comma()
ws()
if i <= n and byte(d, i) == 44 then
i += 1
ws()
end
end
local function digits(): boolean
local any = false
while i <= n do
local c = byte(d, i)
if c >= 48 and c <= 57 then
i += 1
any = true
else
break
end
end
return any
end
-- an SVG number: sign? (digits ("." digits?)? | "." digits) exponent?; "1.5.5" is 1.5 then .5
local function number(): number?
ws()
local s = i
local c = byte(d, i)
if c == 43 or c == 45 then
i += 1
end
local whole = digits()
local frac = false
if i <= n and byte(d, i) == 46 then
i += 1
frac = digits()
end
if not whole and not frac then
i = s
return nil
end
c = byte(d, i)
if c == 101 or c == 69 then
local save = i
i += 1
c = byte(d, i)
if c == 43 or c == 45 then
i += 1
end
if not digits() then
i = save
end
end
return tonumber(sub(d, s, i - 1))
end
local function flag(): number?
ws()
local c = byte(d, i)
if c == 48 or c == 49 then
i += 1
return c - 48
end
return nil
end
while true do
ws()
if i > n then
break
end
local c = sub(d, i, i)
local up = string.upper(c)
if ARGS[up] ~= nil and find(c, "%a") then
cmd = up
rel = c ~= up
i += 1
if up == "Z" then
table.insert(out, { op = "Z" })
cx, cy = sx, sy
last = "Z"
cmd = nil
continue
end
elseif cmd == nil then
return out, false
end
local c2 = cmd :: string
local na = ARGS[c2]
for k = 1, na do
local v = if c2 == "A" and (k == 4 or k == 5) then flag() else number()
if v == nil then
return out, false
end
nums[k] = v
if k < na then
comma()
end
end
comma()
local ox, oy = if rel then cx else 0, if rel then cy else 0
if c2 == "M" then
cx, cy = nums[1] + ox, nums[2] + oy
sx, sy = cx, cy
table.insert(out, { op = "M", cx, cy })
cmd = "L" -- further pairs are line-tos
elseif c2 == "L" then
cx, cy = nums[1] + ox, nums[2] + oy
table.insert(out, { op = "L", cx, cy })
elseif c2 == "H" then
cx = nums[1] + ox
table.insert(out, { op = "L", cx, cy })
elseif c2 == "V" then
cy = nums[1] + (if rel then cy else 0)
table.insert(out, { op = "L", cx, cy })
elseif c2 == "C" then
local x1, y1, x2, y2 = nums[1] + ox, nums[2] + oy, nums[3] + ox, nums[4] + oy
cx, cy = nums[5] + ox, nums[6] + oy
table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy })
lcx, lcy = x2, y2
elseif c2 == "S" then
local x1, y1 = cx, cy
if last == "C" or last == "S" then
x1, y1 = 2 * cx - lcx, 2 * cy - lcy
end
local x2, y2 = nums[1] + ox, nums[2] + oy
cx, cy = nums[3] + ox, nums[4] + oy
table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy })
lcx, lcy = x2, y2
elseif c2 == "Q" then
local x1, y1 = nums[1] + ox, nums[2] + oy
cx, cy = nums[3] + ox, nums[4] + oy
table.insert(out, { op = "Q", x1, y1, cx, cy })
lcx, lcy = x1, y1
elseif c2 == "T" then
local x1, y1 = cx, cy
if last == "Q" or last == "T" then
x1, y1 = 2 * cx - lcx, 2 * cy - lcy
end
cx, cy = nums[1] + ox, nums[2] + oy
table.insert(out, { op = "Q", x1, y1, cx, cy })
lcx, lcy = x1, y1
elseif c2 == "A" then
local x2, y2 = nums[6] + ox, nums[7] + oy
arc(cx, cy, nums[1], nums[2], nums[3], nums[4] ~= 0, nums[5] ~= 0, x2, y2, out)
cx, cy = x2, y2
end
last = if c2 == "M" then "M" else c2
end
return out, true
end
-- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box
-- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves
function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?)
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
local px, py = 0, 0
for _, c in cmds do
local op = c.op
if op == "C" then
-- the curve's exact extrema
local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6]
for axis = 1, 2 do
local p0 = if axis == 1 then px else py
local p1 = if axis == 1 then ax else ay
local p2 = if axis == 1 then bx else by
local p3 = if axis == 1 then ex else ey
local a = -p0 + 3 * p1 - 3 * p2 + p3
local b = 2 * (p0 - 2 * p1 + p2)
local cc = p1 - p0
local ts = {}
if abs(a) < 1e-12 then
if abs(b) > 1e-12 then
table.insert(ts, -cc / b)
end
else
local disc = b * b - 4 * a * cc
if disc >= 0 then
local s = sqrt(disc)
table.insert(ts, (-b + s) / (2 * a))
table.insert(ts, (-b - s) / (2 * a))
end
end
for _, t in ts do
if t > 0 and t < 1 then
local mt = 1 - t
local v = mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3
if axis == 1 then
x0, x1 = math.min(x0, v), math.max(x1, v)
else
y0, y1 = math.min(y0, v), math.max(y1, v)
end
end
end
end
px, py = ex, ey
elseif op == "Q" then
local ax, ay, ex, ey = c[1], c[2], c[3], c[4]
for axis = 1, 2 do
local p0 = if axis == 1 then px else py
local p1 = if axis == 1 then ax else ay
local p2 = if axis == 1 then ex else ey
local den = p0 - 2 * p1 + p2
if abs(den) > 1e-12 then
local t = (p0 - p1) / den
if t > 0 and t < 1 then
local mt = 1 - t
local v = mt * mt * p0 + 2 * mt * t * p1 + t * t * p2
if axis == 1 then
x0, x1 = math.min(x0, v), math.max(x1, v)
else
y0, y1 = math.min(y0, v), math.max(y1, v)
end
end
end
end
px, py = ex, ey
elseif op == "M" or op == "L" then
px, py = c[1], c[2]
end
if op ~= "Z" then
x0, x1 = math.min(x0, px), math.max(x1, px)
y0, y1 = math.min(y0, py), math.max(y1, py)
end
end
if x0 > x1 then
return nil, nil, nil, nil
end
return x0, y0, x1, y1
end
-- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros)
local function num(v: number): string
if v ~= v or v == math.huge or v == -math.huge then
return "0"
end
local r = math.floor(v * 10000 + 0.5) / 10000
if r == math.floor(r) and abs(r) < 1e15 then
return string.format("%d", r)
end
local s = string.format("%.4f", r)
s = string.gsub(s, "0+$", "")
return s
end
PathData.num = num
-- serialize(cmds) -> path data text
function PathData.serialize(cmds: { Cmd }): string
local out = {}
for _, c in cmds do
local k = ARGS[c.op]
if k ~= nil then
local parts = { c.op }
local cnt = if c.op == "C" then 6 elseif c.op == "Q" then 4 elseif c.op == "Z" then 0 else 2
for j = 1, cnt do
table.insert(parts, num(tonumber(c[j]) or 0))
end
table.insert(out, table.concat(parts, " "))
end
end
return table.concat(out, " ")
end
-- toRaster(cmds) -> the codecs/Raster command list (moveTo / lineTo / quadTo / cubicTo / close)
local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" }
function PathData.toRaster(cmds: { Cmd }): { any }
local out = table.create(#cmds)
for i, c in cmds do
local r: any = { op = RASTER[c.op] or "close" }
for j = 1, #c do
r[j] = c[j]
end
out[i] = r
end
return out
end
return PathData
+427
View File
@@ -0,0 +1,427 @@
--!strict
-- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/Raster (antialiased coverage, nonzero / even-odd,
-- the stroker) and codecs/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and
-- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat,
-- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox
-- maps onto the image by meta.preserveAspectRatio. Never throws.
local Types = require("@formats/Types")
local Raster = require("@formats/codecs/Raster")
local Blend = require("@formats/codecs/Blend")
local PathData = require("@formats/vector/svg/PathData")
local Parse = require("@formats/vector/svg/Parse")
local Render = {}
type M = { number }
local function mul(m: M, n: M): M
return Raster.multiply(m, n)
end
-- ------------------------------------------------------------------------------------------------ gradients
local function stopColor(stops: { { number } }, t: number): (number, number, number, number)
local n = #stops
if t <= stops[1][1] then
local s = stops[1]
return s[2], s[3], s[4], s[5]
end
if t >= stops[n][1] then
local s = stops[n]
return s[2], s[3], s[4], s[5]
end
for i = 2, n do
local b = stops[i]
if t <= b[1] then
local a = stops[i - 1]
local span = b[1] - a[1]
local f = if span > 0 then (t - a[1]) / span else 1
return a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f, a[4] + (b[4] - a[4]) * f, a[5] + (b[5] - a[5]) * f
end
end
local s = stops[n]
return s[2], s[3], s[4], s[5]
end
-- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds
local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))?
local stops = p.stops
if type(stops) ~= "table" or #stops == 0 then
return nil
end
local g: M = { 1, 0, 0, 1, 0, 0 }
if p.units ~= "userSpaceOnUse" then
if not bbox or bbox[3] - bbox[1] <= 0 or bbox[4] - bbox[2] <= 0 then
return nil -- a zero-size box: the gradient is not rendered
end
g = { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] }
end
if type(p.transform) == "table" then
g = mul(g, p.transform)
end
local inv = Raster.invert(mul(device, g))
if not inv then
return nil
end
local a, b, c, d, e, f = inv[1], inv[2], inv[3], inv[4], inv[5], inv[6]
local spread = p.spread
local opacity = tonumber(p.opacity) or 1
local function wrap(t: number): number
if spread == "repeat" then
return t - math.floor(t)
elseif spread == "reflect" then
local r = t % 2
return if r > 1 then 2 - r else r
end
return t
end
if p.type == "linear" then
local x1, y1, x2, y2 = p.x1 or 0, p.y1 or 0, p.x2 or 1, p.y2 or 0
local dx, dy = x2 - x1, y2 - y1
local dd = dx * dx + dy * dy
if dd == 0 then
local r, gg, bb, aa = stopColor(stops, 1)
return function(): (number, number, number, number)
return r, gg, bb, aa * opacity
end
end
return function(x: number, y: number): (number, number, number, number)
local gx, gy = a * x + c * y + e, b * x + d * y + f
local t = wrap(((gx - x1) * dx + (gy - y1) * dy) / dd)
local r, gg, bb, aa = stopColor(stops, t)
return r, gg, bb, aa * opacity
end
end
local cx, cy, r = p.cx or 0.5, p.cy or 0.5, p.r or 0.5
local fx, fy = p.fx or cx, p.fy or cy
if r <= 0 then
local rr, gg, bb, aa = stopColor(stops, 1)
return function(): (number, number, number, number)
return rr, gg, bb, aa * opacity
end
end
-- SVG 1.1: a focal point outside the circle moves onto it
local fdx, fdy = fx - cx, fy - cy
local fd = math.sqrt(fdx * fdx + fdy * fdy)
if fd > r * 0.999 then
local k = r * 0.999 / fd
fx, fy = cx + fdx * k, cy + fdy * k
end
return function(x: number, y: number): (number, number, number, number)
local gx, gy = a * x + c * y + e, b * x + d * y + f
local dx, dy = gx - fx, gy - fy
local t
if dx == 0 and dy == 0 then
t = 0
else
-- the ray from the focus through the point meets the circle at s: t = 1 / s
local ox, oy = fx - cx, fy - cy
local qa = dx * dx + dy * dy
local qb = 2 * (dx * ox + dy * oy)
local qc = ox * ox + oy * oy - r * r
local disc = qb * qb - 4 * qa * qc
local s = (-qb + math.sqrt(math.max(0, disc))) / (2 * qa)
t = if s > 0 then 1 / s else 1
end
local rr, gg, bb, aa = stopColor(stops, wrap(t))
return rr, gg, bb, aa * opacity
end
end
-- ------------------------------------------------------------------------------------------------ dashes
-- subpaths of a command list with their closed flag
local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } }
local out = {}
local cur: { any }? = nil
for _, c in cmds do
if c.op == "M" then
cur = { c }
table.insert(out, { cmds = cur, closed = false })
elseif c.op == "Z" then
if cur then
out[#out].closed = true
-- a new subpath starts at the same point if more segments follow
local first = (cur :: { any })[1]
cur = { { op = "M", first[1], first[2] } }
table.insert(out, { cmds = cur, closed = false })
end
elseif cur then
table.insert(cur, c)
end
end
return out
end
-- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol)
local function polyline(cmds: { any }, tol: number): { number }
local pts: { number } = {}
local px, py = 0, 0
for _, c in cmds do
local op = c.op
if op == "M" or op == "L" then
px, py = c[1], c[2]
table.insert(pts, px)
table.insert(pts, py)
elseif op == "Q" or op == "C" then
local len = 0
local lx, ly = px, py
for k = 1, #c - 1, 2 do
len += math.sqrt((c[k] - lx) ^ 2 + (c[k + 1] - ly) ^ 2)
lx, ly = c[k], c[k + 1]
end
local steps = math.clamp(math.ceil(math.sqrt(len / math.max(tol, 1e-4))), 1, 512)
for i = 1, steps do
local t = i / steps
local mt = 1 - t
local x, y
if op == "Q" then
x = mt * mt * px + 2 * mt * t * c[1] + t * t * c[3]
y = mt * mt * py + 2 * mt * t * c[2] + t * t * c[4]
else
x = mt * mt * mt * px + 3 * mt * mt * t * c[1] + 3 * mt * t * t * c[3] + t * t * t * c[5]
y = mt * mt * mt * py + 3 * mt * mt * t * c[2] + 3 * mt * t * t * c[4] + t * t * t * c[6]
end
table.insert(pts, x)
table.insert(pts, y)
end
px, py = c[#c - 1], c[#c]
end
end
return pts
end
local function dashed(cmds: { any }, dashes: { number }, offset: number, tol: number): { any }
local out = {}
local total = 0
for _, v in dashes do
total += v
end
if total <= 0 then
return cmds
end
for _, sp in subpaths(cmds) do
if #sp.cmds < 2 then
continue
end
local pts = polyline(sp.cmds, tol)
if #pts < 4 then
continue
end
if sp.closed then
table.insert(pts, pts[1])
table.insert(pts, pts[2])
end
-- dash state at the start (offset wraps through the pattern)
local idx, left = 1, 0
local o = offset % total
if o < 0 then
o += total
end
while o > 0 do
if o >= dashes[idx] then
o -= dashes[idx]
idx = idx % #dashes + 1
else
break
end
end
left = dashes[idx] - o
local on = idx % 2 == 1
local cur: { any }? = nil
if on then
cur = { { op = "M", pts[1], pts[2] } }
end
for i = 1, #pts - 3, 2 do
local x0, y0, x1, y1 = pts[i], pts[i + 1], pts[i + 2], pts[i + 3]
local seg = math.sqrt((x1 - x0) ^ 2 + (y1 - y0) ^ 2)
local pos = 0
local guard = 0
while seg - pos > left and guard < 100000 do
guard += 1
pos += left
local t = pos / seg
local x, y = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t
if on then
table.insert(cur :: { any }, { op = "L", x, y })
for _, c in cur :: { any } do
table.insert(out, c)
end
cur = nil
else
cur = { { op = "M", x, y } }
end
on = not on
idx = idx % #dashes + 1
left = dashes[idx]
end
left -= seg - pos
if on and cur then
table.insert(cur, { op = "L", x1, y1 })
end
end
if on and cur and #cur > 1 then
for _, c in cur do
table.insert(out, c)
end
end
end
return out
end
-- ------------------------------------------------------------------------------------------------ rendering
export type Options = {
background: { number }?, -- r, g, b, a under the drawing (default transparent)
tolerance: number?, -- curve flattening in device pixels (default 0.1)
}
-- the device transform scale (for stroke flattening tolerances)
local function scaleOf(m: M): number
return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3]))
end
-- rasterize(v, w, h, opts?) -> rgba8 Image
function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image
local o: Options = opts or {}
local img = Types.Image.new(w, h)
local px = img.pixels
local n = w * h
local bg = o.background
if type(bg) == "table" then
local val = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216
for i = 0, n - 1 do
buffer.writeu32(px, i * 4, val)
end
end
local meta: any = if type(v.meta) == "table" then v.meta else {}
local view = Parse.viewTransform(v.viewBox, meta.preserveAspectRatio, 0, 0, w, h)
local groups: { any } = if type(meta.groups) == "table" then meta.groups else {}
local clips: { any } = if type(meta.clips) == "table" then meta.clips else {}
local tol = o.tolerance or 0.1
local clipCache: { [number]: buffer } = {}
-- a clip's coverage over the whole image (1 byte per pixel)
local function clipMask(id: number): buffer?
if clipCache[id] then
return clipCache[id]
end
local c = clips[id]
if type(c) ~= "table" then
return nil
end
local mask = buffer.create(n)
for _, cp in (if type(c.paths) == "table" then c.paths else {}) do
local m = Raster.mask(PathData.toRaster(cp.d), { transform = mul(view, cp.transform or Raster.IDENTITY), rule = cp.rule, clip = { 0, 0, w, h }, tolerance = tol })
if m then
for y = 0, m.height - 1 do
for x = 0, m.width - 1 do
local cv = buffer.readu8(m.coverage, y * m.width + x)
if cv > 0 then
local i = (m.y + y) * w + m.x + x
local old = buffer.readu8(mask, i)
buffer.writeu8(mask, i, math.min(255, old + cv - math.floor(old * cv / 255 + 0.5)))
end
end
end
end
end
clipCache[id] = mask
return mask
end
-- the layer stack: { group id, image }
local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } }
local function chain(g: number?): { number }
local out = {}
local guard = 0
while g ~= nil and guard < 256 do
table.insert(out, 1, g)
local gr = groups[g]
g = if type(gr) == "table" then gr.parent else nil
guard += 1
end
return out
end
local function pop()
local top = table.remove(stack) :: any
local below = stack[#stack].img
local gr = groups[top.id] or {}
local mask: any = nil
if gr.clip then
local cm = clipMask(gr.clip)
mask = if cm then { pixels = cm, width = w, height = h, x = 0, y = 0, default = 0 } else { default = 0 }
end
Blend.composite(below.pixels, w, h, top.img.pixels, w, h, 0, 0, math.clamp(tonumber(gr.opacity) or 1, 0, 1), "normal", { mask = mask })
end
local function draw(target: Types.Image, cmds: { any }, paint: any, device: M, rule: string?, opacity: number, bbox: { number }?)
local fill: any
if paint.type == "color" then
fill = paint.color
else
fill = gradientFn(paint, device, bbox)
if not fill then
return
end
end
Raster.fill(target, cmds, fill, { transform = device, rule = rule, opacity = opacity, tolerance = tol })
end
for _, p in v.paths do
if type(p) ~= "table" or type(p.d) ~= "table" then
continue
end
-- groups: pop the layers this path is not in, push the ones it needs
local want = chain(p.group)
local keep = 1
while keep < #stack and stack[keep + 1].id == want[keep] do
keep += 1
end
while #stack > keep do
pop()
end
for k = keep, #want do
table.insert(stack, { id = want[k], img = Types.Image.new(w, h) })
end
local device = mul(view, p.transform or Raster.IDENTITY)
local target = stack[#stack].img
local clipMaskBuf: buffer? = nil
if p.clip then
clipMaskBuf = clipMask(p.clip)
if not clipMaskBuf then
continue
end
target = Types.Image.new(w, h)
end
local opacity = math.clamp(tonumber(p.opacity) or 1, 0, 1)
local rcmds = PathData.toRaster(p.d)
local bbox: { number }? = nil
if (p.fill and p.fill.type ~= "color") or (p.stroke and p.stroke.type ~= "color") then
local x0, y0, x1, y1 = PathData.bounds(p.d)
if x0 then
bbox = { x0 :: number, y0 :: number, x1 :: number, y1 :: number }
end
end
if type(p.fill) == "table" then
draw(target, rcmds, p.fill, device, p.fillRule, opacity, bbox)
end
if type(p.stroke) == "table" and (tonumber(p.strokeWidth) or 1) > 0 then
local scale = math.max(scaleOf(device), 1e-6)
local src = p.d
if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then
src = dashed(p.d, p.strokeDashArray, tonumber(p.strokeDashOffset) or 0, tol / scale)
end
local outline = Raster.stroke(PathData.toRaster(src), {
width = tonumber(p.strokeWidth) or 1,
join = p.strokeLineJoin,
cap = p.strokeLineCap,
miterLimit = p.strokeMiterLimit,
tolerance = tol / scale,
})
draw(target, outline, p.stroke, device, "nonzero", opacity, bbox)
end
if clipMaskBuf then
Blend.composite(stack[#stack].img.pixels, w, h, target.pixels, w, h, 0, 0, 1, "normal", { mask = { pixels = clipMaskBuf, width = w, height = h, x = 0, y = 0, default = 0 } })
end
end
while #stack > 1 do
pop()
end
return img
end
return Render
+389
View File
@@ -0,0 +1,389 @@
--!strict
-- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba /
-- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor),
-- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated
-- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped).
-- Never throws.
local Style = {}
local NAMED: { [string]: number } = {
aliceblue = 0xf0f8ff, antiquewhite = 0xfaebd7, aqua = 0x00ffff, aquamarine = 0x7fffd4, azure = 0xf0ffff,
beige = 0xf5f5dc, bisque = 0xffe4c4, black = 0x000000, blanchedalmond = 0xffebcd, blue = 0x0000ff,
blueviolet = 0x8a2be2, brown = 0xa52a2a, burlywood = 0xdeb887, cadetblue = 0x5f9ea0, chartreuse = 0x7fff00,
chocolate = 0xd2691e, coral = 0xff7f50, cornflowerblue = 0x6495ed, cornsilk = 0xfff8dc, crimson = 0xdc143c,
cyan = 0x00ffff, darkblue = 0x00008b, darkcyan = 0x008b8b, darkgoldenrod = 0xb8860b, darkgray = 0xa9a9a9,
darkgreen = 0x006400, darkgrey = 0xa9a9a9, darkkhaki = 0xbdb76b, darkmagenta = 0x8b008b, darkolivegreen = 0x556b2f,
darkorange = 0xff8c00, darkorchid = 0x9932cc, darkred = 0x8b0000, darksalmon = 0xe9967a, darkseagreen = 0x8fbc8f,
darkslateblue = 0x483d8b, darkslategray = 0x2f4f4f, darkslategrey = 0x2f4f4f, darkturquoise = 0x00ced1,
darkviolet = 0x9400d3, deeppink = 0xff1493, deepskyblue = 0x00bfff, dimgray = 0x696969, dimgrey = 0x696969,
dodgerblue = 0x1e90ff, firebrick = 0xb22222, floralwhite = 0xfffaf0, forestgreen = 0x228b22, fuchsia = 0xff00ff,
gainsboro = 0xdcdcdc, ghostwhite = 0xf8f8ff, gold = 0xffd700, goldenrod = 0xdaa520, gray = 0x808080,
grey = 0x808080, green = 0x008000, greenyellow = 0xadff2f, honeydew = 0xf0fff0, hotpink = 0xff69b4,
indianred = 0xcd5c5c, indigo = 0x4b0082, ivory = 0xfffff0, khaki = 0xf0e68c, lavender = 0xe6e6fa,
lavenderblush = 0xfff0f5, lawngreen = 0x7cfc00, lemonchiffon = 0xfffacd, lightblue = 0xadd8e6, lightcoral = 0xf08080,
lightcyan = 0xe0ffff, lightgoldenrodyellow = 0xfafad2, lightgray = 0xd3d3d3, lightgreen = 0x90ee90,
lightgrey = 0xd3d3d3, lightpink = 0xffb6c1, lightsalmon = 0xffa07a, lightseagreen = 0x20b2aa,
lightskyblue = 0x87cefa, lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xb0c4de,
lightyellow = 0xffffe0, lime = 0x00ff00, limegreen = 0x32cd32, linen = 0xfaf0e6, magenta = 0xff00ff,
maroon = 0x800000, mediumaquamarine = 0x66cdaa, mediumblue = 0x0000cd, mediumorchid = 0xba55d3,
mediumpurple = 0x9370db, mediumseagreen = 0x3cb371, mediumslateblue = 0x7b68ee, mediumspringgreen = 0x00fa9a,
mediumturquoise = 0x48d1cc, mediumvioletred = 0xc71585, midnightblue = 0x191970, mintcream = 0xf5fffa,
mistyrose = 0xffe4e1, moccasin = 0xffe4b5, navajowhite = 0xffdead, navy = 0x000080, oldlace = 0xfdf5e6,
olive = 0x808000, olivedrab = 0x6b8e23, orange = 0xffa500, orangered = 0xff4500, orchid = 0xda70d6,
palegoldenrod = 0xeee8aa, palegreen = 0x98fb98, paleturquoise = 0xafeeee, palevioletred = 0xdb7093,
papayawhip = 0xffefd5, peachpuff = 0xffdab9, peru = 0xcd853f, pink = 0xffc0cb, plum = 0xdda0dd,
powderblue = 0xb0e0e6, purple = 0x800080, rebeccapurple = 0x663399, red = 0xff0000, rosybrown = 0xbc8f8f,
royalblue = 0x4169e1, saddlebrown = 0x8b4513, salmon = 0xfa8072, sandybrown = 0xf4a460, seagreen = 0x2e8b57,
seashell = 0xfff5ee, sienna = 0xa0522d, silver = 0xc0c0c0, skyblue = 0x87ceeb, slateblue = 0x6a5acd,
slategray = 0x708090, slategrey = 0x708090, snow = 0xfffafa, springgreen = 0x00ff7f, steelblue = 0x4682b4,
tan = 0xd2b48c, teal = 0x008080, thistle = 0xd8bfd8, tomato = 0xff6347, turquoise = 0x40e0d0, violet = 0xee82ee,
wheat = 0xf5deb3, white = 0xffffff, whitesmoke = 0xf5f5f5, yellow = 0xffff00, yellowgreen = 0x9acd32,
}
local function clamp255(v: number): number
return math.clamp(math.floor(v + 0.5), 0, 255)
end
local function hue(p: number, q: number, t: number): number
t %= 1
if t < 1 / 6 then
return p + (q - p) * 6 * t
elseif t < 1 / 2 then
return q
elseif t < 2 / 3 then
return p + (q - p) * (2 / 3 - t) * 6
end
return p
end
-- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value
function Style.color(s: string, current: { number }?): any
s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1")))
if s == "none" then
return "none"
elseif s == "transparent" then
return { 0, 0, 0, 0 }
elseif s == "currentcolor" then
return current or { 0, 0, 0, 255 }
end
local hex = string.match(s, "^#(%x+)$")
if hex then
local n = #hex
if n == 3 or n == 4 then
local v = {}
for k = 1, n do
v[k] = (tonumber(string.sub(hex, k, k), 16) :: number) * 17
end
return { v[1], v[2], v[3], v[4] or 255 }
elseif n == 6 or n == 8 then
local v = {}
for k = 1, n // 2 do
v[k] = tonumber(string.sub(hex, k * 2 - 1, k * 2), 16) :: number
end
return { v[1], v[2], v[3], v[4] or 255 }
end
return nil
end
local fn, args = string.match(s, "^(%a+)%s*%((.*)%)$")
if fn then
local parts = {}
for p in string.gmatch(args :: string, "[^,%s/]+") do
table.insert(parts, p)
end
local function comp(p: string?, scale: number): number?
if p == nil then
return nil
end
local pct = string.match(p, "^([%d.eE+-]+)%%$")
if pct then
local v = tonumber(pct)
return if v then v / 100 * scale else nil
end
return tonumber(p)
end
local function alpha(p: string?): number
if p == nil then
return 255
end
local v = comp(p, 1)
return clamp255((v or 1) * 255)
end
if fn == "rgb" or fn == "rgba" then
local r, g, b = comp(parts[1], 255), comp(parts[2], 255), comp(parts[3], 255)
if not (r and g and b) then
return nil
end
return { clamp255(r :: number), clamp255(g :: number), clamp255(b :: number), alpha(parts[4]) }
elseif fn == "hsl" or fn == "hsla" then
local h = tonumber((string.gsub(parts[1] or "", "deg$", "")))
local sat, l = comp(parts[2], 1), comp(parts[3], 1)
if not (h and sat and l) then
return nil
end
local hh = (h :: number) / 360
local ss, ll = math.clamp(sat :: number, 0, 1), math.clamp(l :: number, 0, 1)
local q = if ll < 0.5 then ll * (1 + ss) else ll + ss - ll * ss
local p = 2 * ll - q
return { clamp255(hue(p, q, hh + 1 / 3) * 255), clamp255(hue(p, q, hh) * 255), clamp255(hue(p, q, hh - 1 / 3) * 255), alpha(parts[4]) }
end
return nil
end
local v = NAMED[s]
if v then
return { v // 65536, v // 256 % 256, v % 256, 255 }
end
return nil
end
-- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil
local function scan(s: string, i: number): (number?, number)
local n = #s
local st = i
local c = string.byte(s, i)
if c == 43 or c == 45 then
i += 1
end
local any = false
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
any = true
else
break
end
end
if i <= n and string.byte(s, i) == 46 then
i += 1
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
any = true
else
break
end
end
end
if not any then
return nil, st
end
c = string.byte(s, i)
if c == 101 or c == 69 then
local save = i
i += 1
c = string.byte(s, i)
if c == 43 or c == 45 then
i += 1
end
local e = false
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
e = true
else
break
end
end
if not e then
i = save
end
end
return tonumber(string.sub(s, st, i - 1)), i
end
-- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100)
local UNITS = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 }
function Style.length(s: string?, ref: number?, fontSize: number?): number?
if s == nil then
return nil
end
local t = string.match(s, "^%s*(.-)%s*$") :: string
local x, j = scan(t, 1)
if x == nil then
return nil
end
local u = string.lower(string.sub(t, j))
if u == "" then
return x
elseif u == "%" then
return x / 100 * (ref or 100)
elseif u == "em" then
return x * (fontSize or 16)
elseif u == "ex" then
return x * (fontSize or 16) / 2
end
local k = UNITS[u]
return if k then x * k else nil
end
-- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else
function Style.numbers(s: string?): { number }
local out = {}
if s == nil then
return out
end
local i, n = 1, #s
while i <= n do
local c = string.byte(s, i)
if c == 32 or c == 44 or c == 9 or c == 10 or c == 13 then
i += 1
else
local v, j = scan(s, i)
if v == nil then
break
end
table.insert(out, v)
i = j
end
end
return out
end
-- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error
local function mul(m: { number }, n: { number }): { number }
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
Style.multiply = mul
function Style.transform(s: string): { number }?
local m = { 1, 0, 0, 1, 0, 0 }
local rest = s
while true do
rest = string.gsub(rest, "^[%s,]+", "")
if rest == "" then
break
end
local name, args, after = string.match(rest, "^(%a+)%s*(%b())(.*)$")
if not name then
return nil
end
rest = after :: string
local v = Style.numbers(string.sub(args :: string, 2, -2))
local t: { number }
if name == "matrix" and #v == 6 then
t = v
elseif name == "translate" and (#v == 1 or #v == 2) then
t = { 1, 0, 0, 1, v[1], v[2] or 0 }
elseif name == "scale" and (#v == 1 or #v == 2) then
t = { v[1], 0, 0, v[2] or v[1], 0, 0 }
elseif name == "rotate" and (#v == 1 or #v == 3) then
local r = v[1] * math.pi / 180
local c, sn = math.cos(r), math.sin(r)
t = { c, sn, -sn, c, 0, 0 }
if #v == 3 then
t = mul(mul({ 1, 0, 0, 1, v[2], v[3] }, t), { 1, 0, 0, 1, -v[2], -v[3] })
end
elseif name == "skewX" and #v == 1 then
t = { 1, 0, math.tan(v[1] * math.pi / 180), 1, 0, 0 }
elseif name == "skewY" and #v == 1 then
t = { 1, math.tan(v[1] * math.pi / 180), 0, 1, 0, 0 }
else
return nil
end
m = mul(m, t)
end
return m
end
-- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped)
function Style.declarations(s: string): { [string]: string }
local out: { [string]: string } = {}
for decl in string.gmatch(s, "[^;]+") do
local k, v = string.match(decl, "^%s*([%w-]+)%s*:%s*(.-)%s*$")
if k and v then
v = string.gsub(v :: string, "%s*!important$", "")
out[string.lower(k :: string)] = v :: string
end
end
return out
end
-- ------------------------------------------------------------------------------------------------ CSS
export type Selector = { tag: string?, id: string?, classes: { string }, specificity: number }
export type Rule = { selector: Selector, decls: { [string]: string }, order: number }
local function selector(s: string): Selector?
s = string.gsub(s, "^%s*(.-)%s*$", "%1")
if s == "" or string.find(s, "[%s>+~%[:]") then
return nil -- combinators, attribute and pseudo selectors: not supported
end
local sel: Selector = { classes = {}, specificity = 0 }
local tag = string.match(s, "^([%a_][%w_-]*)")
if tag then
sel.tag = tag
sel.specificity += 1
s = string.sub(s, #tag + 1)
elseif string.sub(s, 1, 1) == "*" then
s = string.sub(s, 2)
end
while s ~= "" do
local kind, name, rest = string.match(s, "^([.#])([%w_-]+)(.*)$")
if not kind then
return nil
end
if kind == "." then
table.insert(sel.classes, name :: string)
sel.specificity += 100
else
sel.id = name
sel.specificity += 10000
end
s = rest :: string
end
return sel
end
-- css(text, rules?) -> rules (appended to the list given)
function Style.css(text: string, rules: { Rule }?): { Rule }
local out: { Rule } = rules or {}
text = string.gsub(text, "/%*.-%*/", "")
text = string.gsub(text, "<!%-%-", "")
text = string.gsub(text, "%-%->", "")
-- drop @rules with blocks (@media { ... { } }) and simple ones (@import ...;)
local guard = 0
while guard < 100 do
guard += 1
local s, e = string.find(text, "@[%w-]+[^{;]*%b{}")
if not s then
break
end
text = string.sub(text, 1, s - 1) .. string.sub(text, e + 1)
end
text = string.gsub(text, "@[%w-]+[^;{]*;", "")
for sels, body in string.gmatch(text, "([^{}]+)(%b{})") do
local decls = Style.declarations(string.sub(body, 2, -2))
for one in string.gmatch(sels, "[^,]+") do
local sel = selector(one)
if sel then
table.insert(out, { selector = sel, decls = decls, order = #out + 1 })
end
end
end
return out
end
-- matches(sel, tag, id, classes) -> boolean
function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean
if sel.tag and sel.tag ~= tag then
return false
end
if sel.id and sel.id ~= id then
return false
end
for _, c in sel.classes do
if not classes[c] then
return false
end
end
return true
end
return Style
+203
View File
@@ -0,0 +1,203 @@
--!strict
-- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients
-- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...>
-- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message.
local Xml = require("@formats/codecs/Xml")
local Types = require("@formats/Types")
local PathData = require("@formats/vector/svg/PathData")
local Write = {}
local num = PathData.num
local function el(name: string, attrs: { { any } }, children: { any }?): any
local o = Types.object()
for _, kv in attrs do
if kv[2] ~= nil then
Types.set(o, kv[1], if type(kv[2]) == "number" then num(kv[2]) else tostring(kv[2]))
end
end
return Xml.element(name, o :: any, children)
end
local function hex(c: { number }): string
return string.format("#%02x%02x%02x", math.clamp(math.floor(c[1] or 0), 0, 255), math.clamp(math.floor(c[2] or 0), 0, 255), math.clamp(math.floor(c[3] or 0), 0, 255))
end
local function matrix(m: any): string?
if type(m) ~= "table" or #m < 6 then
return nil
end
if m[1] == 1 and m[2] == 0 and m[3] == 0 and m[4] == 1 then
if m[5] == 0 and m[6] == 0 then
return nil
end
return "translate(" .. num(m[5]) .. " " .. num(m[6]) .. ")"
end
local parts = {}
for k = 1, 6 do
parts[k] = num(tonumber(m[k]) or 0)
end
return "matrix(" .. table.concat(parts, " ") .. ")"
end
-- write(v) -> SVG text | nil, message
function Write.vector(v: Types.Vector): (string?, string?)
if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then
return nil, "needs a Vector value"
end
local meta: any = if type(v.meta) == "table" then v.meta else {}
local groups: { any } = if type(meta.groups) == "table" then meta.groups else {}
local clips: { any } = if type(meta.clips) == "table" then meta.clips else {}
local defs = {}
local gradients = 0
-- paints -> attribute values (gradients go to defs)
local function paintAttrs(p: any, which: string): { { any } }
if type(p) ~= "table" then
return { { which, "none" } }
end
if p.type == "color" and type(p.color) == "table" then
local a = p.color[4] or 255
return { { which, hex(p.color) }, { which .. "-opacity", if a < 255 then num(a / 255) else nil } }
end
if p.type ~= "linear" and p.type ~= "radial" then
return { { which, "none" } }
end
gradients += 1
local id = "g" .. gradients
local kids = {}
for _, s in (if type(p.stops) == "table" then p.stops else {}) do
local a = s[5] or 255
table.insert(kids, el("stop", { { "offset", s[1] or 0 }, { "stop-color", hex({ s[2], s[3], s[4] }) }, { "stop-opacity", if a < 255 then num(a / 255) else nil } }))
end
local attrs: { { any } } = { { "id", id }, { "gradientUnits", if p.units == "userSpaceOnUse" then "userSpaceOnUse" else nil } }
if p.type == "linear" then
table.insert(attrs, { "x1", p.x1 or 0 })
table.insert(attrs, { "y1", p.y1 or 0 })
table.insert(attrs, { "x2", p.x2 or 1 })
table.insert(attrs, { "y2", p.y2 or 0 })
else
table.insert(attrs, { "cx", p.cx or 0.5 })
table.insert(attrs, { "cy", p.cy or 0.5 })
table.insert(attrs, { "r", p.r or 0.5 })
table.insert(attrs, { "fx", p.fx })
table.insert(attrs, { "fy", p.fy })
if p.fr and p.fr ~= 0 then
table.insert(attrs, { "fr", p.fr })
end
end
table.insert(attrs, { "spreadMethod", if p.spread and p.spread ~= "pad" then p.spread else nil })
table.insert(attrs, { "gradientTransform", matrix(p.transform) })
table.insert(defs, el(if p.type == "linear" then "linearGradient" else "radialGradient", attrs, kids))
local op = tonumber(p.opacity) or 1
return { { which, "url(#" .. id .. ")" }, { which .. "-opacity", if op < 1 then num(op) else nil } }
end
local clipIds: { [number]: string } = {}
local function clipRef(id: number?): string?
if id == nil or type(clips[id]) ~= "table" then
return nil
end
if clipIds[id] == nil then
local cid = "c" .. id
clipIds[id] = cid
local kids = {}
for _, cp in (if type(clips[id].paths) == "table" then clips[id].paths else {}) do
table.insert(kids, el("path", { { "d", PathData.serialize(cp.d or {}) }, { "transform", matrix(cp.transform) }, { "clip-rule", if cp.rule == "evenodd" then "evenodd" else nil } }))
end
table.insert(defs, el("clipPath", { { "id", cid } }, kids))
end
return "url(#" .. clipIds[id] .. ")"
end
local root = {}
-- the open <g> stack: { id, children }
local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } }
local function chain(g: number?): { number }
local out = {}
local guard = 0
while g ~= nil and guard < 256 do
table.insert(out, 1, g)
local gr = groups[g]
g = if type(gr) == "table" then gr.parent else nil
guard += 1
end
return out
end
for _, p in v.paths do
if type(p) ~= "table" or type(p.d) ~= "table" then
continue
end
local want = chain(p.group)
local keep = 1
while keep < #stack and stack[keep + 1].id == want[keep] do
keep += 1
end
while #stack > keep do
table.remove(stack)
end
for k = keep, #want do
local gr = groups[want[k]] or {}
local kids = {}
local op = tonumber(gr.opacity) or 1
table.insert(stack[#stack].kids, el("g", { { "opacity", if op < 1 then op else nil }, { "clip-path", clipRef(gr.clip) } }, kids))
table.insert(stack, { id = want[k], kids = kids })
end
local attrs: { { any } } = { { "id", p.id }, { "d", PathData.serialize(p.d) }, { "transform", matrix(p.transform) } }
for _, kv in paintAttrs(p.fill, "fill") do
table.insert(attrs, kv)
end
table.insert(attrs, { "fill-rule", if p.fillRule == "evenodd" then "evenodd" else nil })
for _, kv in paintAttrs(p.stroke, "stroke") do
if kv[2] ~= "none" then
table.insert(attrs, kv)
end
end
if type(p.stroke) == "table" then
local sw = tonumber(p.strokeWidth) or 1
table.insert(attrs, { "stroke-width", if sw ~= 1 then sw else nil })
table.insert(attrs, { "stroke-linejoin", if p.strokeLineJoin and p.strokeLineJoin ~= "miter" then p.strokeLineJoin else nil })
table.insert(attrs, { "stroke-linecap", if p.strokeLineCap and p.strokeLineCap ~= "butt" then p.strokeLineCap else nil })
local ml = tonumber(p.strokeMiterLimit)
table.insert(attrs, { "stroke-miterlimit", if ml and ml ~= 4 then ml else nil })
if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then
local parts = {}
for k, d in p.strokeDashArray do
parts[k] = num(tonumber(d) or 0)
end
table.insert(attrs, { "stroke-dasharray", table.concat(parts, " ") })
local off = tonumber(p.strokeDashOffset)
table.insert(attrs, { "stroke-dashoffset", if off and off ~= 0 then off else nil })
end
end
local op = tonumber(p.opacity) or 1
table.insert(attrs, { "opacity", if op < 1 then op else nil })
local node = el("path", attrs)
local cr = clipRef(p.clip)
if cr then
node = el("g", { { "clip-path", cr } }, { node })
end
table.insert(stack[#stack].kids, node)
end
local children = {}
if #defs > 0 then
table.insert(children, el("defs", {}, defs))
end
for _, c in root do
table.insert(children, c)
end
local vb = v.viewBox
local vbText = if type(vb) == "table" and #vb == 4 then num(vb[1]) .. " " .. num(vb[2]) .. " " .. num(vb[3]) .. " " .. num(vb[4]) else nil
local svg = el("svg", {
{ "xmlns", "http://www.w3.org/2000/svg" },
{ "width", v.width },
{ "height", v.height },
{ "viewBox", vbText },
{ "preserveAspectRatio", meta.preserveAspectRatio },
}, children)
local s, err = Xml.encode(Xml.document(svg, { version = "1.0", encoding = "UTF-8" }), { indent = 1 })
if not s then
return nil, tostring(err)
end
return s .. "\n", nil
end
return Write
+96
View File
@@ -0,0 +1,96 @@
--!strict
-- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs
-- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg
-- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from
-- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke /
-- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and
-- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path
-- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %).
-- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and
-- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/Raster; encode writes SVG back from a Vector.
-- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also
-- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
local Parse = require("@formats/vector/svg/Parse")
local Render = require("@formats/vector/svg/Render")
local Write = require("@formats/vector/svg/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Svg = {
name = "svg",
category = "vector",
extensions = { "svg" },
mime = { "image/svg+xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend" },
caps = { decode = true, encode = true, rasterize = true, text = false },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
}
export type EncodeOptions = {}
export type RasterizeOptions = Render.Options
-- ------------------------------------------------------------------------------------------------ sniff
function Svg.sniff(r: Bytes.Reader): number
local h = r:peek(4096)
if string.sub(h, 1, 3) == "\239\187\191" then
h = string.sub(h, 4)
end
if not string.match(h, "^%s*<") then
return 0
end
if string.find(h, "<svg[%s>:]") or string.find(h, "<%w+:svg[%s>]") then
return 0.95
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Svg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Vector?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 26
if r.limit - r.base > maxBytes then
return nil, Err.new(Err.LIMIT, "file is over the byte limit")
end
local doc, xerr = Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base))
if not doc then
return nil, xerr
end
local v, msg = Parse.document(doc)
if not v then
return nil, Err.new(Err.CORRUPT, msg or "bad SVG")
end
v.meta.source = { format = "svg" }
return v, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?)
local s, err = Write.vector(v)
if not s then
return nil, Err.new(Err.ARG, err or "bad Vector")
end
return buffer.fromstring(s), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox
-- maps onto w x h by its preserveAspectRatio.
function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?)
if type(v) ~= "table" or type(v.paths) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Vector value")
end
local W = math.ceil(w or v.width or 0)
local H = math.ceil(h or v.height or 0)
if W < 1 or H < 1 or W * H > 2 ^ 26 then
return nil, Err.new(Err.ARG, "bad raster size")
end
return Render.rasterize(v, W, H, opts), nil
end
return Svg
+156
View File
@@ -0,0 +1,156 @@
--!strict
-- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip)
-- to gids and back; property values and their types; number formatting. Never throws.
local Base64 = require("@formats/core/Base64")
local Deflate = require("@formats/codecs/Deflate")
local Data = {}
-- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message
function Data.csv(text: string): ({ number }?, string?)
local out = {}
for tok in string.gmatch(text, "[^,%s]+") do
local v = tonumber(tok)
if v == nil or v < 0 or v >= 4294967296 or v % 1 ~= 0 then
return nil, "bad gid " .. string.sub(tok, 1, 20)
end
table.insert(out, v)
end
return out, nil
end
-- base64(text, compression) -> { gid } | nil, message, unsupported?
function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?)
local raw, err = Base64.decode(text)
if not raw then
return nil, err
end
local bytes: buffer = raw
if compression == "zlib" then
local z, zerr = Deflate.zlib(bytes)
if not z then
return nil, "zlib: " .. tostring(zerr)
end
bytes = z
elseif compression == "gzip" then
local z, zerr = Deflate.gunzip(bytes)
if not z then
return nil, "gzip: " .. tostring(zerr)
end
bytes = z
elseif compression ~= nil and compression ~= "" then
return nil, "compression " .. compression .. " is not supported", true
end
local n = buffer.len(bytes) // 4
local out = table.create(n)
for i = 0, n - 1 do
out[i + 1] = buffer.readu32(bytes, i * 4)
end
return out, nil
end
-- toBase64(gids, compression?, level?) -> text | nil, message
function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?)
local b = buffer.create(#gids * 4)
for i, g in gids do
buffer.writeu32(b, (i - 1) * 4, g % 4294967296)
end
if compression == "zlib" then
local z = Deflate.zlibCompress(b, { level = level or 6 })
if not z then
return nil, "zlib failed"
end
b = z
elseif compression == "gzip" then
local z = Deflate.gzip(b, { level = level or 6 })
if not z then
return nil, "gzip failed"
end
b = z
elseif compression ~= nil and compression ~= "" then
return nil, "compression " .. compression .. " is not supported"
end
return Base64.encode(b), nil
end
-- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print
function Data.num(v: number): string
if v % 1 == 0 and math.abs(v) < 2 ^ 53 then
return string.format("%.0f", v)
end
local s = string.format("%.15g", v)
if tonumber(s) ~= v then
s = string.format("%.17g", v)
end
return s
end
-- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line)
function Data.csvText(gids: { number }, width: number): string
local rows = {}
local row = {}
for i, g in gids do
table.insert(row, Data.num(g))
if width > 0 and i % width == 0 then
table.insert(rows, table.concat(row, ","))
row = {}
end
end
if #row > 0 then
table.insert(rows, table.concat(row, ","))
end
return "\n" .. table.concat(rows, ",\n") .. "\n"
end
-- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil)
function Data.color(s: string?): string?
if type(s) ~= "string" then
return nil
end
local h = string.lower((string.gsub(s, "^#", "")))
if #h == 8 and string.sub(h, 1, 2) == "ff" then
h = string.sub(h, 3)
end
return "#" .. h
end
-- property values: TMX / TMJ type names -> a Luau value from text
function Data.value(typ: string, text: string): any
if typ == "int" or typ == "float" or typ == "object" then
return tonumber(text) or 0
elseif typ == "bool" then
return text == "true" or text == "1"
elseif typ == "color" then
return Data.color(text) or ""
end
return text
end
-- typeOf(v, declared?) -> the Tiled type to write for v
function Data.typeOf(v: any, declared: string?): string
if declared then
return declared
end
if type(v) == "boolean" then
return "bool"
elseif type(v) == "number" then
return if v % 1 == 0 then "int" else "float"
elseif type(v) == "table" then
return "class"
end
return "string"
end
-- sortedKeys(t) -> its string keys, sorted
function Data.sortedKeys(t: { [any]: any }): { string }
local out = {}
for k in pairs(t) do
if type(k) == "string" then
table.insert(out, k)
end
end
table.sort(out)
return out
end
return Data
+634
View File
@@ -0,0 +1,634 @@
--!strict
-- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ
-- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?.
local Types = require("@formats/Types")
local Data = require("@formats/vector/tiled/Data")
local Tmj = {}
local function n(v: any, default: number?): number?
if type(v) == "number" then
return v
end
return default
end
local function b(v: any, default: boolean): boolean
if type(v) == "boolean" then
return v
end
return default
end
local function s(v: any): string?
if type(v) == "string" then
return v
end
return nil
end
local function list(v: any): { any }
if type(v) == "table" then
return v
end
return {}
end
-- ------------------------------------------------------------------------------------------------ read
local function properties(v: any): ({ [string]: any }, { [string]: string }?)
local props: { [string]: any } = {}
local types: { [string]: string }? = nil
for _, p in list(v) do
if type(p) == "table" and type(p.name) == "string" then
local typ = s(p.type) or "string"
local val: any = p.value
if typ == "class" then
local inner, innerTypes = {}, nil
if type(val) == "table" then
-- a class value is an object of member -> value (types come from the project): keep them as they are
for k, x in pairs(val) do
if type(k) == "string" then
inner[k] = x
end
end
end
val = { class = s(p.propertytype) or "", properties = inner, propertyTypes = innerTypes }
elseif typ == "int" or typ == "float" or typ == "object" then
val = n(val, 0)
elseif typ == "bool" then
val = val == true
elseif typ == "color" then
val = Data.color(s(val)) or ""
elseif type(val) ~= "string" then
val = if val == nil then "" else tostring(val)
end
props[p.name] = val
if typ ~= "string" then
types = types or {}
;(types :: any)[p.name] = typ
end
end
end
return props, types
end
local function withProps(t: any, v: any)
local props, types = properties(v.properties)
t.properties = props
if types then
t.propertyTypes = types
end
end
local function gids(v: any, encoding: string?, compression: string?): ({ number }?, string?, boolean?)
if type(v) == "string" then
if encoding == "base64" or encoding == nil then
return Data.base64(v, compression)
end
return nil, "unknown encoding " .. tostring(encoding), true
end
local out = {}
for _, g in list(v) do
if type(g) ~= "number" or g < 0 or g >= 4294967296 then
return nil, "bad gid"
end
table.insert(out, g)
end
return out, nil
end
local function object(o: any): any
local obj: any = {
id = n(o.id),
name = s(o.name) or "",
class = s(o.class) or s(o.type) or "",
x = n(o.x, 0),
y = n(o.y, 0),
width = n(o.width, 0),
height = n(o.height, 0),
rotation = n(o.rotation, 0),
gid = n(o.gid),
visible = b(o.visible, true),
template = s(o.template),
shape = "rectangle",
}
withProps(obj, o)
if o.ellipse == true then
obj.shape = "ellipse"
elseif o.point == true then
obj.shape = "point"
end
for _, kind in { "polygon", "polyline" } do
if type(o[kind]) == "table" then
obj.shape = kind
local pts = {}
for _, p in o[kind] do
if type(p) == "table" then
table.insert(pts, { n(p.x, 0), n(p.y, 0) })
end
end
obj.points = pts
end
end
if type(o.text) == "table" then
local t = o.text
obj.shape = "text"
obj.text = {
text = s(t.text) or "",
fontFamily = s(t.fontfamily) or "sans-serif",
pixelSize = n(t.pixelsize, 16),
wrap = b(t.wrap, false),
color = Data.color(s(t.color)) or "#000000",
bold = b(t.bold, false),
italic = b(t.italic, false),
underline = b(t.underline, false),
strikeout = b(t.strikeout, false),
kerning = b(t.kerning, true),
halign = s(t.halign) or "left",
valign = s(t.valign) or "top",
}
end
return obj
end
local TYPES = { tilelayer = "tiles", objectgroup = "objects", imagelayer = "image", group = "group" }
local layer: (v: any, depth: number) -> (any, string?, boolean?)
local function common(v: any, typ: string): any
local l: any = {
type = typ,
id = n(v.id),
name = s(v.name) or "",
visible = b(v.visible, true),
opacity = n(v.opacity, 1),
x = n(v.x, 0),
y = n(v.y, 0),
offsetX = n(v.offsetx, 0),
offsetY = n(v.offsety, 0),
parallaxX = n(v.parallaxx, 1),
parallaxY = n(v.parallaxy, 1),
tintColor = Data.color(s(v.tintcolor)),
class = s(v.class) or "",
locked = b(v.locked, false),
}
withProps(l, v)
return l
end
local function objectGroup(v: any): any
local l = common(v, "objects")
l.drawOrder = s(v.draworder) or "topdown"
l.color = Data.color(s(v.color))
l.objects = {}
for _, o in list(v.objects) do
if type(o) == "table" then
table.insert(l.objects, object(o))
end
end
return l
end
layer = function(v: any, depth: number): (any, string?, boolean?)
if type(v) ~= "table" then
return nil, "a layer is not an object"
end
if depth > 100 then
return nil, "groups nested too deep"
end
local typ = TYPES[v.type]
if typ == "tiles" then
local l = common(v, "tiles")
l.width = n(v.width, 0)
l.height = n(v.height, 0)
l.encoding = s(v.encoding)
l.compression = s(v.compression)
if type(v.chunks) == "table" then
l.chunks = {}
for _, c in v.chunks do
if type(c) == "table" then
local g, err, uns = gids(c.data, l.encoding, l.compression)
if not g then
return nil, err, uns
end
table.insert(l.chunks, { x = n(c.x, 0), y = n(c.y, 0), width = n(c.width, 0), height = n(c.height, 0), data = g })
end
end
elseif v.data ~= nil then
local g, err, uns = gids(v.data, l.encoding, l.compression)
if not g then
return nil, err, uns
end
l.data = g
end
return l
elseif typ == "objects" then
return objectGroup(v)
elseif typ == "image" then
local l = common(v, "image")
l.imageSource = s(v.image)
l.imageWidth = n(v.imagewidth)
l.imageHeight = n(v.imageheight)
l.transparentColor = Data.color(s(v.transparentcolor))
l.repeatX = b(v.repeatx, false)
l.repeatY = b(v.repeaty, false)
return l
elseif typ == "group" then
local l = common(v, "group")
l.layers = {}
for _, c in list(v.layers) do
local sub, err, uns = layer(c, depth + 1)
if not sub then
return nil, err, uns
end
table.insert(l.layers, sub)
end
return l
end
return nil, "unknown layer type " .. tostring(v.type)
end
-- tileset(v) -> Tileset (a map's entry, or a .tsj root)
function Tmj.tileset(v: any): any
local ts: any = {
firstGid = n(v.firstgid, 1),
source = s(v.source),
name = s(v.name) or "",
tileWidth = n(v.tilewidth, 0),
tileHeight = n(v.tileheight, 0),
spacing = n(v.spacing, 0),
margin = n(v.margin, 0),
count = n(v.tilecount, 0),
columns = n(v.columns, 0),
objectAlignment = s(v.objectalignment),
class = s(v.class) or "",
imageSource = s(v.image),
imageWidth = n(v.imagewidth),
imageHeight = n(v.imageheight),
transparentColor = Data.color(s(v.transparentcolor)),
}
withProps(ts, v)
if type(v.tileoffset) == "table" then
ts.tileOffset = { x = n(v.tileoffset.x, 0), y = n(v.tileoffset.y, 0) }
end
local tiles = {}
for _, t in list(v.tiles) do
if type(t) == "table" then
local tile: any = { id = n(t.id, 0), class = s(t.class) or s(t.type) or "", probability = n(t.probability) }
withProps(tile, t)
tile.imageSource = s(t.image)
tile.imageWidth = n(t.imagewidth)
tile.imageHeight = n(t.imageheight)
if type(t.animation) == "table" then
tile.animation = {}
for _, f in t.animation do
if type(f) == "table" then
table.insert(tile.animation, { tileId = n(f.tileid, 0), duration = n(f.duration, 0) })
end
end
end
if type(t.objectgroup) == "table" then
tile.objectGroup = objectGroup(t.objectgroup)
end
table.insert(tiles, tile)
end
end
table.sort(tiles, function(x: any, y: any): boolean
return x.id < y.id
end)
ts.tiles = tiles
return ts
end
-- read(value) -> TileMap | nil, message, unsupported?
function Tmj.read(v: any): (any, string?, boolean?)
if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then
return nil, "not a Tiled map (type is not \"map\")"
end
local map: any = Types.TileMap.new(n(v.width, 0) :: number, n(v.height, 0) :: number, n(v.tilewidth, 0) :: number, n(v.tileheight, 0) :: number)
map.version = if type(v.version) == "number" then Data.num(v.version) else s(v.version)
map.tiledVersion = s(v.tiledversion)
map.orientation = s(v.orientation) or "orthogonal"
map.renderOrder = s(v.renderorder) or "right-down"
map.infinite = b(v.infinite, false)
map.nextLayerId = n(v.nextlayerid)
map.nextObjectId = n(v.nextobjectid)
map.backgroundColor = Data.color(s(v.backgroundcolor))
map.hexSideLength = n(v.hexsidelength)
map.staggerAxis = s(v.staggeraxis)
map.staggerIndex = s(v.staggerindex)
map.class = s(v.class) or ""
map.parallaxOriginX = n(v.parallaxoriginx, 0)
map.parallaxOriginY = n(v.parallaxoriginy, 0)
withProps(map, v)
for _, ts in list(v.tilesets) do
if type(ts) == "table" then
table.insert(map.tilesets, Tmj.tileset(ts))
end
end
for _, l in list(v.layers) do
local x, err, uns = layer(l, 0)
if not x then
return nil, err, uns
end
table.insert(map.layers, x)
end
return map, nil
end
-- ------------------------------------------------------------------------------------------------ write
local function obj(pairs_: { { any } }): any
local o = Types.object()
for _, kv in pairs_ do
if kv[2] ~= nil then
Types.set(o, kv[1], kv[2])
end
end
return o
end
local function nz(v: any, default: any): any
if v == nil or v == default then
return nil
end
return v
end
local function str(v: any): string?
if type(v) == "string" and v ~= "" then
return v
end
return nil
end
local function propList(props: any, types: any): { any }?
if type(props) ~= "table" or next(props) == nil then
return nil
end
local out = {}
for _, k in Data.sortedKeys(props) do
local v = props[k]
local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil)
if typ == "class" and type(v) == "table" then
local members = Types.object()
if type(v.properties) == "table" then
for _, mk in Data.sortedKeys(v.properties) do
Types.set(members, mk, v.properties[mk])
end
end
table.insert(out, obj({ { "name", k }, { "propertytype", v.class or "" }, { "type", "class" }, { "value", members } }))
else
table.insert(out, obj({ { "name", k }, { "type", typ }, { "value", v } }))
end
end
return out
end
local function writeObject(o: any): any
local t: any = nil
if o.shape == "text" and type(o.text) == "table" then
local x = o.text
t = obj({
{ "bold", nz(x.bold, false) },
{ "color", nz(x.color, "#000000") },
{ "fontfamily", nz(x.fontFamily, "sans-serif") },
{ "halign", nz(x.halign, "left") },
{ "italic", nz(x.italic, false) },
{ "kerning", nz(x.kerning, true) },
{ "pixelsize", nz(x.pixelSize, 16) },
{ "strikeout", nz(x.strikeout, false) },
{ "text", tostring(x.text or "") },
{ "underline", nz(x.underline, false) },
{ "valign", nz(x.valign, "top") },
{ "wrap", nz(x.wrap, false) },
})
end
local pts: any = nil
if (o.shape == "polygon" or o.shape == "polyline") and type(o.points) == "table" then
pts = {}
for _, p in o.points do
table.insert(pts, obj({ { "x", tonumber(p[1]) or 0 }, { "y", tonumber(p[2]) or 0 } }))
end
end
return obj({
{ "ellipse", if o.shape == "ellipse" then true else nil },
{ "gid", o.gid },
{ "height", o.height or 0 },
{ "id", o.id },
{ "name", o.name or "" },
{ "point", if o.shape == "point" then true else nil },
{ "polygon", if o.shape == "polygon" then pts else nil },
{ "polyline", if o.shape == "polyline" then pts else nil },
{ "properties", propList(o.properties, o.propertyTypes) },
{ "rotation", o.rotation or 0 },
{ "template", o.template },
{ "text", t },
{ "type", o.class or "" },
{ "visible", o.visible ~= false },
{ "width", o.width or 0 },
{ "x", o.x or 0 },
{ "y", o.y or 0 },
})
end
export type WriteOptions = { encoding: string?, compression: string?, level: number? }
local function writeObjectGroup(l: any): any
local objs = {}
for _, o in (if type(l.objects) == "table" then l.objects else {}) do
table.insert(objs, writeObject(o))
end
return objs
end
local writeLayer: (l: any, o: WriteOptions) -> (any, string?)
writeLayer = function(l: any, o: WriteOptions): (any, string?)
local t = l.type
local fields: { { any } } = {}
local function add(k: string, v: any)
table.insert(fields, { k, v })
end
if t == "tiles" then
local enc = o.encoding or l.encoding
if enc ~= "base64" then
enc = nil
end
local comp = if enc then (o.compression or (if o.encoding then nil else l.compression)) else nil
local function payload(g: { number }): (any, string?)
if enc == "base64" then
return Data.toBase64(g, comp, o.level)
end
return g, nil
end
if type(l.chunks) == "table" then
local chunks = {}
for _, c in l.chunks do
local d, err = payload(c.data or {})
if d == nil then
return nil, err
end
table.insert(chunks, obj({ { "data", d }, { "height", c.height or 0 }, { "width", c.width or 0 }, { "x", c.x or 0 }, { "y", c.y or 0 } }))
end
add("chunks", chunks)
local sx, sy = math.huge, math.huge
for _, c in l.chunks do
sx, sy = math.min(sx, c.x or 0), math.min(sy, c.y or 0)
end
if #l.chunks > 0 then
add("startx", sx)
add("starty", sy)
end
elseif type(l.data) == "table" then
local d, err = payload(l.data)
if d == nil then
return nil, err
end
add("data", d)
end
add("compression", comp)
add("encoding", enc)
add("height", l.height or 0)
elseif t == "objects" then
add("color", l.color)
add("draworder", l.drawOrder or "topdown")
elseif t == "image" then
add("image", l.imageSource or "")
add("imageheight", l.imageHeight)
add("imagewidth", l.imageWidth)
elseif t == "group" then
local kids = {}
for _, c in (if type(l.layers) == "table" then l.layers else {}) do
local x, err = writeLayer(c, o)
if x == nil then
return nil, err
end
table.insert(kids, x)
end
add("layers", kids)
else
return nil, "unknown layer type " .. tostring(t)
end
add("class", str(l.class))
add("id", l.id)
add("locked", nz(l.locked, false))
add("name", l.name or "")
if t == "objects" then
add("objects", writeObjectGroup(l))
end
add("offsetx", nz(l.offsetX, 0))
add("offsety", nz(l.offsetY, 0))
add("opacity", l.opacity or 1)
add("parallaxx", nz(l.parallaxX, 1))
add("parallaxy", nz(l.parallaxY, 1))
add("properties", propList(l.properties, l.propertyTypes))
if t == "image" then
add("repeatx", nz(l.repeatX, false))
add("repeaty", nz(l.repeatY, false))
end
add("tintcolor", l.tintColor)
if t == "image" then
add("transparentcolor", l.transparentColor)
end
add("type", if t == "tiles" then "tilelayer" elseif t == "objects" then "objectgroup" elseif t == "image" then "imagelayer" else "group")
add("visible", l.visible ~= false)
if t == "tiles" then
add("width", l.width or 0)
end
add("x", l.x or 0)
add("y", l.y or 0)
return obj(fields), nil
end
-- tilesetValue(ts, inMap) -> a JSON object
function Tmj.tilesetValue(ts: any, inMap: boolean): any
if inMap and type(ts.source) == "string" then
return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } })
end
local tiles: any = nil
if type(ts.tiles) == "table" and #ts.tiles > 0 then
tiles = {}
for _, tile in ts.tiles do
local anim: any = nil
if type(tile.animation) == "table" then
anim = {}
for _, f in tile.animation do
table.insert(anim, obj({ { "duration", f.duration or 0 }, { "tileid", f.tileId or 0 } }))
end
end
local og: any = nil
if type(tile.objectGroup) == "table" then
og = writeLayer(tile.objectGroup, {})
end
table.insert(tiles, obj({
{ "animation", anim },
{ "id", tile.id or 0 },
{ "image", tile.imageSource },
{ "imageheight", tile.imageHeight },
{ "imagewidth", tile.imageWidth },
{ "objectgroup", og },
{ "probability", tile.probability },
{ "properties", propList(tile.properties, tile.propertyTypes) },
{ "type", str(tile.class) },
}))
end
end
return obj({
{ "class", str(ts.class) },
{ "columns", ts.columns or 0 },
{ "firstgid", if inMap then ts.firstGid or 1 else nil },
{ "image", ts.imageSource },
{ "imageheight", ts.imageHeight },
{ "imagewidth", ts.imageWidth },
{ "margin", ts.margin or 0 },
{ "name", ts.name or "" },
{ "objectalignment", ts.objectAlignment },
{ "properties", propList(ts.properties, ts.propertyTypes) },
{ "spacing", ts.spacing or 0 },
{ "tilecount", ts.count or 0 },
{ "tileheight", ts.tileHeight or 0 },
{ "tileoffset", if type(ts.tileOffset) == "table" then obj({ { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }) else nil },
{ "tiles", tiles },
{ "tilewidth", ts.tileWidth or 0 },
{ "transparentcolor", ts.transparentColor },
{ "type", if inMap then nil else "tileset" },
})
end
-- write(map, opts) -> a JSON value | nil, message
function Tmj.write(map: any, o: WriteOptions): (any, string?)
local layers = {}
for _, l in map.layers do
local x, err = writeLayer(l, o)
if x == nil then
return nil, err
end
table.insert(layers, x)
end
local tilesets = {}
for _, ts in map.tilesets do
table.insert(tilesets, Tmj.tilesetValue(ts, true))
end
return obj({
{ "backgroundcolor", map.backgroundColor },
{ "class", str(map.class) },
{ "compressionlevel", -1 },
{ "height", map.height },
{ "hexsidelength", map.hexSideLength },
{ "infinite", map.infinite == true },
{ "layers", layers },
{ "nextlayerid", map.nextLayerId },
{ "nextobjectid", map.nextObjectId },
{ "orientation", map.orientation or "orthogonal" },
{ "parallaxoriginx", nz(map.parallaxOriginX, 0) },
{ "parallaxoriginy", nz(map.parallaxOriginY, 0) },
{ "properties", propList(map.properties, map.propertyTypes) },
{ "renderorder", map.renderOrder or "right-down" },
{ "staggeraxis", map.staggerAxis },
{ "staggerindex", map.staggerIndex },
{ "tiledversion", map.tiledVersion },
{ "tileheight", map.tileHeight },
{ "tilesets", tilesets },
{ "tilewidth", map.tileWidth },
{ "type", "map" },
{ "version", map.version or "1.10" },
{ "width", map.width },
}), nil
end
return Tmj
+618
View File
@@ -0,0 +1,618 @@
--!strict
-- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/Xml tree <-> a Types.TileMap, and TSX tilesets.
-- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?.
local Xml = require("@formats/codecs/Xml")
local Types = require("@formats/Types")
local Data = require("@formats/vector/tiled/Data")
local Tmx = {}
type Node = Types.XmlNode
local function a(n: Node, k: string): string?
return (n.attrs :: any)[k]
end
local function num(n: Node, k: string, default: number?): number?
local v = a(n, k)
if v == nil then
return default
end
return tonumber(v) or default
end
local function flag(n: Node, k: string, default: boolean): boolean
local v = a(n, k)
if v == nil then
return default
end
return v == "1" or v == "true"
end
-- ------------------------------------------------------------------------------------------------ read
-- <properties> -> values, types (types only for the non-string ones)
local function properties(n: Node?): ({ [string]: any }, { [string]: string }?)
local props: { [string]: any } = {}
local types: { [string]: string }? = nil
if n == nil then
return props, nil
end
for _, p in Xml.children(n, "property") do
local name = a(p, "name")
if name then
local typ = a(p, "type") or "string"
local v: any
if typ == "class" then
local inner, innerTypes = properties(Xml.child(p, "properties"))
v = { class = a(p, "propertytype") or "", properties = inner, propertyTypes = innerTypes }
else
local text = a(p, "value")
if text == nil then
text = Xml.text(p) -- multi-line strings
end
v = Data.value(typ, text :: string)
end
props[name] = v
if typ ~= "string" then
types = types or {}
;(types :: any)[name] = typ
end
end
end
return props, types
end
local function withProps(t: any, n: Node)
local props, types = properties(Xml.child(n, "properties"))
t.properties = props
if types then
t.propertyTypes = types
end
end
-- the gids of a <data> (or <chunk>) node
local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?)
if encoding == "csv" then
return Data.csv(Xml.text(d))
elseif encoding == "base64" then
return Data.base64(Xml.text(d), compression)
elseif encoding == nil or encoding == "" then
local out = {}
for _, t in Xml.children(d, "tile") do
table.insert(out, num(t, "gid", 0) :: number)
end
return out, nil
end
return nil, "unknown encoding " .. encoding, true
end
local function object(o: Node): any
local obj: any = {
id = num(o, "id"),
name = a(o, "name") or "",
class = a(o, "class") or a(o, "type") or "",
x = num(o, "x", 0),
y = num(o, "y", 0),
width = num(o, "width", 0),
height = num(o, "height", 0),
rotation = num(o, "rotation", 0),
gid = num(o, "gid"),
visible = flag(o, "visible", true),
template = a(o, "template"),
shape = "rectangle",
}
withProps(obj, o)
if Xml.child(o, "ellipse") then
obj.shape = "ellipse"
elseif Xml.child(o, "point") then
obj.shape = "point"
end
for _, kind in { "polygon", "polyline" } do
local p = Xml.child(o, kind)
if p then
obj.shape = kind
local pts = {}
for x, y in string.gmatch(a(p, "points") or "", "([^,%s]+),([^,%s]+)") do
table.insert(pts, { tonumber(x) or 0, tonumber(y) or 0 })
end
obj.points = pts
end
end
local t = Xml.child(o, "text")
if t then
obj.shape = "text"
obj.text = {
text = Xml.text(t),
fontFamily = a(t, "fontfamily") or "sans-serif",
pixelSize = num(t, "pixelsize", 16),
wrap = flag(t, "wrap", false),
color = Data.color(a(t, "color")) or "#000000",
bold = flag(t, "bold", false),
italic = flag(t, "italic", false),
underline = flag(t, "underline", false),
strikeout = flag(t, "strikeout", false),
kerning = flag(t, "kerning", true),
halign = a(t, "halign") or "left",
valign = a(t, "valign") or "top",
}
end
return obj
end
local layer: (n: Node) -> (any, string?, boolean?)
local function common(n: Node, typ: string): any
local l: any = {
type = typ,
id = num(n, "id"),
name = a(n, "name") or "",
visible = flag(n, "visible", true),
opacity = num(n, "opacity", 1),
x = num(n, "x", 0),
y = num(n, "y", 0),
offsetX = num(n, "offsetx", 0),
offsetY = num(n, "offsety", 0),
parallaxX = num(n, "parallaxx", 1),
parallaxY = num(n, "parallaxy", 1),
tintColor = Data.color(a(n, "tintcolor")),
class = a(n, "class") or "",
locked = flag(n, "locked", false),
}
withProps(l, n)
return l
end
local function objectGroup(n: Node): any
local l = common(n, "objects")
l.drawOrder = a(n, "draworder") or "topdown"
l.color = Data.color(a(n, "color"))
l.objects = {}
for _, o in Xml.children(n, "object") do
table.insert(l.objects, object(o))
end
return l
end
layer = function(n: Node): (any, string?, boolean?)
local name = n.name
if name == "layer" then
local l = common(n, "tiles")
l.width = num(n, "width", 0)
l.height = num(n, "height", 0)
local d = Xml.child(n, "data")
if d then
local enc, comp = a(d, "encoding"), a(d, "compression")
l.encoding, l.compression = enc, comp
local chunks = Xml.children(d, "chunk")
if #chunks > 0 then
l.chunks = {}
for _, c in chunks do
local g, err, uns = gids(c, enc, comp)
if not g then
return nil, err, uns
end
table.insert(l.chunks, { x = num(c, "x", 0), y = num(c, "y", 0), width = num(c, "width", 0), height = num(c, "height", 0), data = g })
end
else
local g, err, uns = gids(d, enc, comp)
if not g then
return nil, err, uns
end
l.data = g
end
end
return l
elseif name == "objectgroup" then
return objectGroup(n)
elseif name == "imagelayer" then
local l = common(n, "image")
l.repeatX = flag(n, "repeatx", false)
l.repeatY = flag(n, "repeaty", false)
local img = Xml.child(n, "image")
if img then
l.imageSource = a(img, "source")
l.imageWidth = num(img, "width")
l.imageHeight = num(img, "height")
l.transparentColor = Data.color(a(img, "trans"))
end
return l
elseif name == "group" then
local l = common(n, "group")
l.layers = {}
for _, c in n.children do
if type(c) == "table" then
local sub, err, uns = layer(c)
if err then
return nil, err, uns
end
if sub then
table.insert(l.layers, sub)
end
end
end
return l
end
return nil
end
-- a <tileset> element (in a map, or a .tsx root) -> Tileset
function Tmx.tileset(n: Node): any
local ts: any = {
firstGid = num(n, "firstgid", 1),
source = a(n, "source"),
name = a(n, "name") or "",
tileWidth = num(n, "tilewidth", 0),
tileHeight = num(n, "tileheight", 0),
spacing = num(n, "spacing", 0),
margin = num(n, "margin", 0),
count = num(n, "tilecount", 0),
columns = num(n, "columns", 0),
objectAlignment = a(n, "objectalignment"),
class = a(n, "class") or "",
}
withProps(ts, n)
local off = Xml.child(n, "tileoffset")
if off then
ts.tileOffset = { x = num(off, "x", 0), y = num(off, "y", 0) }
end
local img = Xml.child(n, "image")
if img then
ts.imageSource = a(img, "source")
ts.imageWidth = num(img, "width")
ts.imageHeight = num(img, "height")
ts.transparentColor = Data.color(a(img, "trans"))
end
local tiles = {}
for _, t in Xml.children(n, "tile") do
local tile: any = { id = num(t, "id", 0), class = a(t, "class") or a(t, "type") or "", probability = num(t, "probability") }
withProps(tile, t)
local ti = Xml.child(t, "image")
if ti then
tile.imageSource = a(ti, "source")
tile.imageWidth = num(ti, "width")
tile.imageHeight = num(ti, "height")
end
local anim = Xml.child(t, "animation")
if anim then
tile.animation = {}
for _, f in Xml.children(anim, "frame") do
table.insert(tile.animation, { tileId = num(f, "tileid", 0), duration = num(f, "duration", 0) })
end
end
local og = Xml.child(t, "objectgroup")
if og then
tile.objectGroup = objectGroup(og)
end
table.insert(tiles, tile)
end
ts.tiles = tiles
return ts
end
-- read(root) -> TileMap | nil, message, unsupported?
function Tmx.read(root: Node): (any, string?, boolean?)
if root.name ~= "map" then
return nil, "the root element is <" .. root.name .. ">, not <map>"
end
local map: any = Types.TileMap.new(num(root, "width", 0) :: number, num(root, "height", 0) :: number, num(root, "tilewidth", 0) :: number, num(root, "tileheight", 0) :: number)
map.version = a(root, "version")
map.tiledVersion = a(root, "tiledversion")
map.orientation = a(root, "orientation") or "orthogonal"
map.renderOrder = a(root, "renderorder") or "right-down"
map.infinite = flag(root, "infinite", false)
map.nextLayerId = num(root, "nextlayerid")
map.nextObjectId = num(root, "nextobjectid")
map.backgroundColor = Data.color(a(root, "backgroundcolor"))
map.hexSideLength = num(root, "hexsidelength")
map.staggerAxis = a(root, "staggeraxis")
map.staggerIndex = a(root, "staggerindex")
map.class = a(root, "class") or ""
map.parallaxOriginX = num(root, "parallaxoriginx", 0)
map.parallaxOriginY = num(root, "parallaxoriginy", 0)
withProps(map, root)
for _, c in root.children do
if type(c) == "table" then
if c.name == "tileset" then
table.insert(map.tilesets, Tmx.tileset(c))
else
local l, err, uns = layer(c)
if err then
return nil, err, uns
end
if l then
table.insert(map.layers, l)
end
end
end
end
return map, nil
end
-- ------------------------------------------------------------------------------------------------ write
type Attrs = { [string]: string }
local function el(name: string, attrs: { { any } }, children: { any }?): Node
-- attrs in order; nil / default values dropped by the caller
local o = Types.object()
for _, kv in attrs do
if kv[2] ~= nil then
local v = kv[2]
Types.set(o, kv[1], if type(v) == "number" then Data.num(v) elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v))
end
end
return Xml.element(name, o :: any, children)
end
local function nz(v: any, default: any): any
if v == nil or v == default then
return nil
end
return v
end
local function str(v: any): string?
if type(v) == "string" and v ~= "" then
return v
end
return nil
end
local function propsNode(props: any, types: any): Node?
if type(props) ~= "table" or next(props) == nil then
return nil
end
local list = {}
for _, k in Data.sortedKeys(props) do
local v = props[k]
local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil)
if typ == "class" and type(v) == "table" then
local inner = propsNode(v.properties, v.propertyTypes)
table.insert(list, el("property", { { "name", k }, { "type", "class" }, { "propertytype", v.class or "" } }, if inner then { inner } else nil))
else
local text = if type(v) == "boolean" then (if v then "true" else "false") elseif type(v) == "number" then Data.num(v) else tostring(v)
if string.find(text, "\n", 1, true) then
table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil } }, { text }))
else
table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil }, { "value", text } }))
end
end
end
return el("properties", {}, list)
end
local function addProps(children: { any }, t: any)
local p = propsNode(t.properties, t.propertyTypes)
if p then
table.insert(children, p)
end
end
local function writeObject(o: any): Node
local kids = {}
addProps(kids, o)
local shape = o.shape
if shape == "ellipse" then
table.insert(kids, el("ellipse", {}))
elseif shape == "point" then
table.insert(kids, el("point", {}))
elseif (shape == "polygon" or shape == "polyline") and type(o.points) == "table" then
local pts = {}
for _, p in o.points do
table.insert(pts, Data.num(tonumber(p[1]) or 0) .. "," .. Data.num(tonumber(p[2]) or 0))
end
table.insert(kids, el(shape, { { "points", table.concat(pts, " ") } }))
elseif shape == "text" and type(o.text) == "table" then
local t = o.text
table.insert(kids, el("text", {
{ "fontfamily", nz(t.fontFamily, "sans-serif") },
{ "pixelsize", nz(t.pixelSize, 16) },
{ "wrap", nz(t.wrap, false) },
{ "color", nz(t.color, "#000000") },
{ "bold", nz(t.bold, false) },
{ "italic", nz(t.italic, false) },
{ "underline", nz(t.underline, false) },
{ "strikeout", nz(t.strikeout, false) },
{ "kerning", nz(t.kerning, true) },
{ "halign", nz(t.halign, "left") },
{ "valign", nz(t.valign, "top") },
}, { tostring(t.text or "") }))
end
return el("object", {
{ "id", o.id },
{ "name", str(o.name) },
{ "type", str(o.class) },
{ "gid", o.gid },
{ "x", o.x or 0 },
{ "y", o.y or 0 },
{ "width", nz(o.width, 0) },
{ "height", nz(o.height, 0) },
{ "rotation", nz(o.rotation, 0) },
{ "visible", nz(o.visible, true) },
{ "template", o.template },
}, kids)
end
local function commonAttrs(l: any, extra: { { any } }): { { any } }
local out: { { any } } = { { "id", l.id }, { "name", str(l.name) or "" }, { "class", str(l.class) } }
table.move(extra, 1, #extra, #out + 1, out)
local tail = {
{ "visible", nz(l.visible, true) },
{ "locked", nz(l.locked, false) },
{ "opacity", nz(l.opacity, 1) },
{ "tintcolor", l.tintColor },
{ "offsetx", nz(l.offsetX, 0) },
{ "offsety", nz(l.offsetY, 0) },
{ "parallaxx", nz(l.parallaxX, 1) },
{ "parallaxy", nz(l.parallaxY, 1) },
}
table.move(tail, 1, #tail, #out + 1, out)
return out
end
local function writeObjectGroup(l: any, tag: string?): Node
local kids = {}
addProps(kids, l)
for _, o in (if type(l.objects) == "table" then l.objects else {}) do
table.insert(kids, writeObject(o))
end
return el(tag or "objectgroup", commonAttrs(l, { { "color", l.color }, { "draworder", nz(l.drawOrder, "topdown") } }), kids)
end
export type WriteOptions = { encoding: string?, compression: string?, level: number? }
local writeLayer: (l: any, o: WriteOptions) -> (Node?, string?)
writeLayer = function(l: any, o: WriteOptions): (Node?, string?)
local t = l.type
if t == "tiles" then
local kids = {}
addProps(kids, l)
local enc = o.encoding or l.encoding or "csv"
local comp = if o.encoding then o.compression else (o.compression or l.compression)
if enc ~= "base64" then
comp = nil
end
local function payload(g: { number }, width: number): (string?, string?)
if enc == "csv" then
return Data.csvText(g, width), nil
end
local s, err = Data.toBase64(g, comp, o.level)
if not s then
return nil, err
end
return "\n " .. s .. "\n ", nil
end
local dataKids = {}
if type(l.chunks) == "table" then
for _, c in l.chunks do
local kids: { any } = {}
if enc == "xml" then
for _, g in (c.data or {}) do
table.insert(kids, el("tile", { { "gid", if g ~= 0 then g else nil } }))
end
else
local s, err = payload(c.data or {}, c.width or 0)
if not s then
return nil, err
end
kids = { s }
end
table.insert(dataKids, el("chunk", { { "x", c.x or 0 }, { "y", c.y or 0 }, { "width", c.width or 0 }, { "height", c.height or 0 } }, kids))
end
elseif type(l.data) == "table" and enc == "xml" then
for _, g in l.data do
table.insert(dataKids, el("tile", { { "gid", if g ~= 0 then g else nil } }))
end
elseif type(l.data) == "table" then
local s, err = payload(l.data, l.width or 0)
if not s then
return nil, err
end
dataKids = { s }
end
table.insert(kids, el("data", { { "encoding", if enc == "xml" then nil else enc }, { "compression", comp } }, dataKids))
return el("layer", commonAttrs(l, { { "x", nz(l.x, 0) }, { "y", nz(l.y, 0) }, { "width", l.width or 0 }, { "height", l.height or 0 } }), kids), nil
elseif t == "objects" then
return writeObjectGroup(l), nil
elseif t == "image" then
local kids = {}
addProps(kids, l)
if l.imageSource then
table.insert(kids, el("image", { { "source", l.imageSource }, { "trans", l.transparentColor }, { "width", l.imageWidth }, { "height", l.imageHeight } }))
end
return el("imagelayer", commonAttrs(l, { { "repeatx", nz(l.repeatX, false) }, { "repeaty", nz(l.repeatY, false) } }), kids), nil
elseif t == "group" then
local kids = {}
addProps(kids, l)
for _, c in (if type(l.layers) == "table" then l.layers else {}) do
local n, err = writeLayer(c, o)
if not n then
return nil, err
end
table.insert(kids, n)
end
return el("group", commonAttrs(l, {}), kids), nil
end
return nil, "unknown layer type " .. tostring(t)
end
-- tilesetNode(ts, inMap) -> <tileset>
function Tmx.tilesetNode(ts: any, inMap: boolean): Node
if inMap and type(ts.source) == "string" then
return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } })
end
local kids = {}
if type(ts.tileOffset) == "table" then
table.insert(kids, el("tileoffset", { { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }))
end
addProps(kids, ts)
if ts.imageSource then
table.insert(kids, el("image", { { "source", ts.imageSource }, { "trans", ts.transparentColor }, { "width", ts.imageWidth }, { "height", ts.imageHeight } }))
end
for _, tile in (if type(ts.tiles) == "table" then ts.tiles else {}) do
local tk = {}
addProps(tk, tile)
if tile.imageSource then
table.insert(tk, el("image", { { "source", tile.imageSource }, { "width", tile.imageWidth }, { "height", tile.imageHeight } }))
end
if type(tile.objectGroup) == "table" then
table.insert(tk, writeObjectGroup(tile.objectGroup))
end
if type(tile.animation) == "table" then
local frames = {}
for _, f in tile.animation do
table.insert(frames, el("frame", { { "tileid", f.tileId or 0 }, { "duration", f.duration or 0 } }))
end
table.insert(tk, el("animation", {}, frames))
end
table.insert(kids, el("tile", { { "id", tile.id or 0 }, { "type", str(tile.class) }, { "probability", tile.probability } }, tk))
end
return el("tileset", {
{ "firstgid", if inMap then ts.firstGid or 1 else nil },
{ "name", ts.name or "" },
{ "class", str(ts.class) },
{ "tilewidth", ts.tileWidth or 0 },
{ "tileheight", ts.tileHeight or 0 },
{ "spacing", nz(ts.spacing, 0) },
{ "margin", nz(ts.margin, 0) },
{ "tilecount", ts.count or 0 },
{ "columns", ts.columns or 0 },
{ "objectalignment", ts.objectAlignment },
}, kids)
end
-- write(map, opts) -> an XML document node | nil, message
function Tmx.write(map: any, o: WriteOptions): (Node?, string?)
local kids = {}
addProps(kids, map)
for _, ts in map.tilesets do
table.insert(kids, Tmx.tilesetNode(ts, true))
end
for _, l in map.layers do
local n, err = writeLayer(l, o)
if not n then
return nil, err
end
table.insert(kids, n)
end
local root = el("map", {
{ "version", map.version or "1.10" },
{ "tiledversion", map.tiledVersion },
{ "class", str(map.class) },
{ "orientation", map.orientation or "orthogonal" },
{ "renderorder", map.renderOrder or "right-down" },
{ "width", map.width },
{ "height", map.height },
{ "tilewidth", map.tileWidth },
{ "tileheight", map.tileHeight },
{ "hexsidelength", map.hexSideLength },
{ "staggeraxis", map.staggerAxis },
{ "staggerindex", map.staggerIndex },
{ "parallaxoriginx", nz(map.parallaxOriginX, 0) },
{ "parallaxoriginy", nz(map.parallaxOriginY, 0) },
{ "backgroundcolor", map.backgroundColor },
{ "infinite", map.infinite == true },
{ "nextlayerid", map.nextLayerId },
{ "nextobjectid", map.nextObjectId },
}, kids)
return Xml.document(root, { version = "1.0", encoding = "UTF-8" }), nil
end
return Tmx
+189
View File
@@ -0,0 +1,189 @@
--!strict
-- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map
-- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib /
-- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles,
-- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers,
-- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets
-- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay
-- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the
-- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json".
-- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external
-- tilesets or images (callers resolve `source` / `imageSource` paths themselves).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
local Json = require("@formats/codecs/Json")
local Tmx = require("@formats/vector/tiled/Tmx")
local Tmj = require("@formats/vector/tiled/Tmj")
-- ------------------------------------------------------------------------------------------------ contract
local Tiled = {
name = "tiled",
category = "vector",
extensions = { "tmx", "tmj", "tsx", "tsj" },
mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" },
deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" },
caps = { decode = true, encode = true, tilesets = true, infinite = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 256 MB)
}
export type EncodeOptions = {
format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (JSON); default: the source's flavour, else tmx
encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64"
compression: string?, -- base64 data: nil | "zlib" | "gzip"
level: number?, -- deflate level for compressed data (default 6)
indent: number?, -- spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON)
}
-- ------------------------------------------------------------------------------------------------ sniff
local function head(r: Bytes.Reader): string
local h = r:peek(1024)
if string.sub(h, 1, 3) == "\239\187\191" then
h = string.sub(h, 4)
end
return h
end
function Tiled.sniff(r: Bytes.Reader): number
local h = head(r)
if string.match(h, "^%s*<") then
if string.find(h, "<map[%s>]") or string.find(h, "<tileset[%s>]") then
return 0.9
end
return 0
end
if string.match(h, "^%s*{") then
-- Tiled writes its keys sorted: "type" comes last, so look at the tail too
local n = r:remaining()
local tail = if n > 1024 then r:peek(1024, n - 1024) else ""
for _, part in { h, tail } do
if string.find(part, "\"type\"%s*:%s*\"map\"") or string.find(part, "\"type\"%s*:%s*\"tileset\"") then
return 0.8
end
end
if string.find(h, "\"tilewidth\"", 1, true) and (string.find(h, "\"orientation\"", 1, true) or string.find(h, "\"tilesets\"", 1, true)) then
return 0.6
end
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its
-- meta.tileset is true) | nil, Err
function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if r.limit - r.base > maxBytes then
return nil, Err.new(Err.LIMIT, "file is over the byte limit")
end
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local h = head(r)
local map: any, msg: string?, unsupported: boolean?
local flavour
if string.match(h, "^%s*<") then
local doc, xerr = Xml.decode(text)
if not doc then
return nil, xerr
end
local root = (doc :: any).root
if root == nil then
return nil, Err.new(Err.CORRUPT, "no root element")
end
if root.name == "tileset" then
map = Types.TileMap.new(0, 0, 0, 0)
map.tilesets = { Tmx.tileset(root) }
map.meta.tileset = true
flavour = "tsx"
else
map, msg, unsupported = Tmx.read(root)
flavour = "tmx"
end
else
local v, jerr = Json.decode(text)
if v == nil then
return nil, jerr
end
if type(v) == "table" and v.type == "tileset" then
map = Types.TileMap.new(0, 0, 0, 0)
map.tilesets = { Tmj.tileset(v) }
map.meta.tileset = true
flavour = "tsj"
else
map, msg, unsupported = Tmj.read(v)
flavour = "tmj"
end
end
if not map then
return nil, Err.new(if unsupported then Err.UNSUPPORTED else Err.CORRUPT, msg or "bad map")
end
map.meta.source = { format = flavour }
return map, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Tiled.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then
return nil, Err.new(Err.ARG, "needs a TileMap value")
end
local o: EncodeOptions = opts or {}
local meta: any = if type(map.meta) == "table" then map.meta else {}
local fmt = o.format or (if type(meta.source) == "table" then meta.source.format else nil) or "tmx"
fmt = string.lower(fmt)
if fmt == "tiled" then
fmt = if type(meta.source) == "table" and meta.source.format then meta.source.format else "tmx"
end
local tilesetOnly = meta.tileset == true or fmt == "tsx" or fmt == "tsj"
if o.encoding and o.encoding ~= "csv" and o.encoding ~= "base64" and o.encoding ~= "xml" then
return nil, Err.new(Err.ARG, "encoding must be csv, base64 or xml")
end
if o.compression and o.compression ~= "zlib" and o.compression ~= "gzip" then
return nil, Err.new(Err.ARG, "compression must be zlib or gzip")
end
local wo = { encoding = o.encoding, compression = o.compression, level = o.level }
if fmt == "tmx" or fmt == "tsx" or fmt == "xml" then
local doc: any, err: string?
if tilesetOnly then
if not map.tilesets[1] then
return nil, Err.new(Err.ARG, "no tileset to write")
end
doc = Xml.document(Tmx.tilesetNode(map.tilesets[1], false), { version = "1.0", encoding = "UTF-8" })
else
doc, err = Tmx.write(map, wo)
end
if not doc then
return nil, Err.new(Err.ARG, err or "bad map")
end
local s, xerr = Xml.encode(doc, { indent = o.indent or 1 })
if not s then
return nil, xerr
end
return buffer.fromstring(s .. "\n"), nil
elseif fmt == "tmj" or fmt == "tsj" or fmt == "json" then
local v: any, err: string?
if tilesetOnly then
if not map.tilesets[1] then
return nil, Err.new(Err.ARG, "no tileset to write")
end
v = Tmj.tilesetValue(map.tilesets[1], false)
else
v, err = Tmj.write(map, wo)
end
if v == nil then
return nil, Err.new(Err.ARG, err or "bad map")
end
local indent = if o.indent == 0 then nil else (o.indent or 2)
local s, jerr = Json.encode(v, { indent = indent })
if not s then
return nil, jerr
end
return buffer.fromstring(s .. "\n"), nil
end
return nil, Err.new(Err.ARG, "unknown format " .. tostring(fmt) .. " (tmx, tmj, tsx, tsj)")
end
return Tiled
+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()
+45
View File
@@ -471,3 +471,48 @@ do
MeshOps.voxelsToPrimitive(grid)
end)
end
do
-- layered + vector (ws-vec): PSD decode / encode of 8 RGBA layers 1024 x 768, flatten (codecs/Blend), SVG
-- rasterize at 512 x 512 (codecs/Raster). No fixtures: the inputs are built here.
local Types = require("@formats/Types")
local Psd = require("@formats/layered/psd")
local LayerOps = require("@formats/ops/LayerOps")
local Svg = require("@formats/vector/svg")
local W, H = 1024, 768
local doc = Types.Layered.new(W, H)
local modes = { "normal", "multiply", "screen", "overlay", "normal", "softLight", "difference", "normal" }
for k = 1, 8 do
local img = Types.Image.new(W, H)
local px = img.pixels
for i = 0, W * H - 1 do
local x, y = i % W, i // W
buffer.writeu32(px, i * 4, ((x * k) % 256) + ((y * 3) % 256) * 256 + (((x + y) // 4) % 256) * 65536 + (if (x // 64 + y // 64 + k) % 3 == 0 then 0 else 200) * 16777216)
end
local l = Types.Layered.layer("L" .. k, img)
l.blend = modes[k]
doc.layers[k] = l
end
local psd = assert(Psd.encode(doc))
bench("psd decode 8 layers 1024x768", 2, W * H * 4 * 9, function()
Psd.decode(Bytes.reader(psd))
end)
bench("psd encode 8 layers (RLE)", 1, W * H * 4 * 9, function()
Psd.encode(doc)
end)
bench("flatten 8 layers (blend modes)", 2, W * H * 4 * 8, function()
LayerOps.flatten(doc)
end)
local shapes = {}
for k = 0, 39 do
table.insert(shapes, string.format("<circle cx='%d' cy='%d' r='%d' fill='url(#g)' stroke='#222' stroke-width='2' opacity='0.8'/>", (k * 37) % 100, (k * 53) % 100, 5 + k % 12))
table.insert(shapes, string.format("<path d='M%d %d q 20 -30 40 0 t 40 0' fill='none' stroke='hsl(%d, 70%%, 50%%)' stroke-width='3' stroke-dasharray='4 2'/>", k % 50, k * 2, k * 9))
end
local text = "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><defs><radialGradient id='g' fx='0.3' fy='0.3'><stop offset='0' stop-color='#fff'/><stop offset='1' stop-color='#36c'/></radialGradient></defs>" .. table.concat(shapes) .. "</svg>"
local v = assert(Svg.decode(Bytes.reader(buffer.fromstring(text))))
bench("svg parse (80 elements)", 5, #text, function()
Svg.decode(Bytes.reader(buffer.fromstring(text)))
end)
bench("svg rasterize 512x512 (80 shapes)", 2, 512 * 512 * 4, function()
Svg.rasterize(v, 512, 512)
end)
end
+180
View File
@@ -0,0 +1,180 @@
-- tools/fixtures/_ours.luau: our encoders' output for the reference tools to read (run by tools/fixtures/*.py through
-- `luau tools/fixtures/_ours.luau -a <format>`). Prints one JSON object: { "data": hex of the encoded file, ... the
-- facts the python side checks the reference's reading against }.
local Types = require("@formats/Types")
local Crc32 = require("@formats/core/Crc32")
local LayerOps = require("@formats/ops/LayerOps")
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
local function jstr(s: string): string
return '"' .. string.gsub(s, '[%c"\\]', function(c: string): string
return string.format("\\u%04x", string.byte(c))
end) .. '"'
end
local function json(v: any): string
if type(v) == "table" then
if #v > 0 or next(v) == nil then
local t = {}
for i, x in v do
t[i] = json(x)
end
return "[" .. table.concat(t, ",") .. "]"
end
local t = {}
for k, x in v do
table.insert(t, jstr(k) .. ":" .. json(x))
end
return "{" .. table.concat(t, ",") .. "}"
elseif type(v) == "string" then
return jstr(v)
elseif type(v) == "boolean" then
return if v then "true" else "false"
end
return tostring(v)
end
-- a deterministic rgba8 image
local function image(w: number, h: number, seed: number, alpha: boolean?): Types.Image
local img = Types.Image.new(w, h)
for y = 0, h - 1 do
for x = 0, w - 1 do
local o = (y * w + x) * 4
buffer.writeu8(img.pixels, o, (x * (seed + 3) * 7 + y * 5) % 256)
buffer.writeu8(img.pixels, o + 1, (y * (seed + 1) * 9 + x) % 256)
buffer.writeu8(img.pixels, o + 2, ((x + seed) * (y + 1) * 3) % 256)
buffer.writeu8(img.pixels, o + 3, if alpha and (x + y) % 3 == 0 then (x * 40 + seed) % 256 else 255)
end
end
return img
end
local function gray(w: number, h: number): Types.Image
local img = Types.Image.new(w, h, "gray8")
for i = 0, w * h - 1 do
buffer.writeu8(img.pixels, i, (i * 13) % 256)
end
return img
end
-- the Layered document tests/layered/psd.luau also builds (keep them in step)
local function psdDoc(): Types.Layered
local L = Types.Layered
local doc = L.new(36, 24)
local bg = L.layer("Background", image(36, 24, 1))
local mul = L.layer("Multiply", image(20, 12, 2, true), 4, 3)
mul.blend = "multiply"
mul.opacity = 200 / 255
local scr = L.layer("Screen", image(18, 18, 3, true), 12, 4)
scr.blend = "screen"
local iso = L.group("Isolated", { scr })
iso.blend = "normal"
iso.opacity = 180 / 255
local hid = L.layer("Hidden", image(8, 8, 4), 1, 1)
hid.visible = false
local diff = L.layer("Diff \u{e9}\u{65e5}", image(14, 10, 5, true), 18, 12)
diff.blend = "difference"
local pass = L.group("Pass", { hid, diff })
local base = L.layer("Base", image(10, 8, 6), 24, 14)
local clip = L.layer("Clipped", image(14, 12, 7, true), 20, 10)
clip.clip = true
local masked = L.layer("Masked", image(16, 10, 8), 2, 12)
masked.mask = { image = gray(12, 8), x = 4, y = 13, default = 0 }
local fill = L.layer("Fill", image(8, 24, 9, true), 28, 0)
fill.fillOpacity = 128 / 255
fill.blend = "lighten"
doc.layers = { bg, mul, iso, pass, base, clip, masked, fill }
return doc
end
-- an animated sprite (tests/layered/aseprite.luau builds the same one)
local function aseDoc(): Types.Layered
local L = Types.Layered
local doc = L.new(24, 16)
local bgImg = image(24, 16, 1)
local shared = image(10, 8, 2, true)
local frames = {}
for f = 1, 3 do
local bg = L.layer("Background", bgImg)
local mul = L.layer("Mul", if f == 2 then image(10, 8, 7, true) else shared, 3 + (if f == 2 then 1 else 0), 2)
mul.blend = "multiply"
local half = L.layer("Half", image(12, 9, 3 + f, true), f * 2, 4)
half.fillOpacity = 128 / 255
local g = L.group("Group", { mul, half })
local top = L.layer("Top", image(6, 6, 9 + f, true), 16 - f, 8)
top.opacity = 200 / 255
frames[f] = { layers = { bg, g, top }, delay = 0.05 * f }
end
doc.frames = frames
doc.layers = frames[1].layers
doc.meta.tags = { { name = "all", from = 1, to = 3, direction = "pingpong", ["repeat"] = 0 } }
return doc
end
-- a Tiled map (tools/fixtures/tiled.py has Tiled read our TMX and TMJ of it)
local function tiledMap(): Types.TileMap
local m: any = Types.TileMap.new(5, 4, 16, 16)
m.nextLayerId, m.nextObjectId = 5, 4
m.properties = { name = "ours", n = 7, f = 0.5, ok = false, c = "#ff112233" }
m.propertyTypes = { c = "color" }
m.tilesets = { { firstGid = 1, name = "tiles", tileWidth = 16, tileHeight = 16, columns = 4, count = 8, spacing = 0, margin = 0, imageSource = "tiles.png", imageWidth = 64, imageHeight = 32, properties = {}, tiles = { { id = 2, class = "Wall", properties = { hard = true } }, { id = 4, properties = {}, animation = { { tileId = 4, duration = 120 }, { tileId = 5, duration = 80 } } } } } }
local data = {}
for i = 1, 20 do
data[i] = (i * 3) % 9
end
data[2] += 0x80000000
data[10] += 0x40000000
local tiles = { type = "tiles", id = 1, name = "ground", width = 5, height = 4, data = data, visible = true, opacity = 0.8, offsetX = 2, offsetY = 0, properties = { deep = 3 }, encoding = "base64", compression = "zlib" }
local objs = {
{ id = 1, name = "a", class = "Spawn", x = 4, y = 5.5, width = 8, height = 8, rotation = 30, visible = true, shape = "rectangle", properties = { team = "red" } },
{ id = 2, name = "b", class = "", x = 20, y = 10, width = 0, height = 0, rotation = 0, visible = true, shape = "polyline", points = { { 0, 0 }, { 8, 4 }, { 16, 0 } }, properties = {} },
{ id = 3, name = "c", class = "", x = 30, y = 30, width = 60, height = 14, rotation = 0, visible = false, shape = "text", text = { text = "hi there", fontFamily = "sans-serif", pixelSize = 14, wrap = true, color = "#00ff00", bold = false, italic = true, underline = false, strikeout = false, kerning = true, halign = "right", valign = "top" }, properties = {} },
}
local og = { type = "objects", id = 3, name = "things", visible = true, opacity = 1, drawOrder = "topdown", objects = objs, properties = {} }
local img = { type = "image", id = 4, name = "sky", visible = true, opacity = 1, imageSource = "sky.png", imageWidth = 40, imageHeight = 20, repeatX = true, repeatY = false, properties = {} }
local group = { type = "group", id = 2, name = "grp", visible = true, opacity = 0.5, layers = { og, img }, properties = {} }
m.layers = { tiles, group }
return m
end
local which, arg = ...
if which == "psd" then
local Psd = require("@formats/layered/psd")
local doc = psdDoc()
local data = Psd.encode(doc) :: buffer
local flat = LayerOps.flatten(doc) :: Types.Image
local layers = {}
for l, depth in LayerOps.leaves(doc.layers) do
local lay = l :: any
table.insert(layers, { name = lay.name, crc = Crc32.of(lay.image.pixels), left = lay.x, top = lay.y, width = lay.image.width, height = lay.image.height, blend = lay.blend, visible = lay.visible, clip = lay.clip == true, opacity = math.floor(lay.opacity * 255 + 0.5), depth = depth })
end
print(json({ data = hex(data), composite = Crc32.of(flat.pixels), layers = layers }))
elseif which == "aseprite" then
local Ase = require("@formats/layered/aseprite")
local doc = aseDoc()
local data = Ase.encode(doc) :: buffer
local frames = {}
for f = 1, 3 do
frames[f] = hex((LayerOps.flatten(doc, { frame = f }) :: Types.Image).pixels)
end
print(json({ data = hex(data), nframes = 3, frames = frames }))
elseif which == "tiled" then
local Tiled = require("@formats/vector/tiled")
local m = tiledMap()
local tmx = Tiled.encode(m, { format = "tmx" }) :: buffer
local tmj = Tiled.encode(m, { format = "tmj" }) :: buffer
print(json({ tmx = hex(tmx), tmj = hex(tmj) }))
elseif which == "svg" then
-- the SVG text given on the command line, decoded and written back by our encoder
local Svg = require("@formats/vector/svg")
local Bytes = require("@formats/core/Bytes")
local v = Svg.decode(Bytes.reader(buffer.fromstring(arg)))
local out = if v then Svg.encode(v) else nil
print(json({ svg = if out then buffer.tostring(out) else "" }))
end
+213
View File
@@ -0,0 +1,213 @@
# Aseprite fixtures (tools/fixtures.py). Sprites written here by a small writer following docs/ase-file-specs.md
# (RGBA / grayscale / indexed, raw / zlib / linked cels, groups, hidden layers, blend modes, layer and cel opacity,
# old and new palette chunks, tags, user data), sprites written by LibreSprite (the reference: an Aseprite 1.1 fork,
# in nixpkgs) and LibreSprite's flattened rendering of every frame:
# tests/gen/aseprite.luau { cases = { { name, data, width, height, nframes, cels = { { frame, layer, x, y, w, h,
# crc } }, frames = { RGBA of LibreSprite's frame i } } } }
# tests/gen/aseprite_ours.luau { frames = { ... }, ours = { ... } }: our encoder's sprite (tools/fixtures/_ours.luau)
# rendered by LibreSprite, with our flatten of the same frames
import json, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/layered/aseprite", "src/Formats/codecs/Blend.luau", "tools/fixtures/_ours.luau"]
def s(text):
b = text.encode()
return struct.pack("<H", len(b)) + b
def chunk(ctype, body):
return struct.pack("<IH", len(body) + 6, ctype) + body
def layer_chunk(name, flags=3, ltype=0, level=0, blend=0, opacity=255):
return chunk(0x2004, struct.pack("<HHHHHHB3x", flags, ltype, level, 0, 0, blend, opacity) + s(name))
def cel_chunk(layer, x, y, w, h, pixels, opacity=255, kind=2, link=None, z=0):
head = struct.pack("<HhhBHh5x", layer, x, y, opacity, 1 if link is not None else kind, z)
if link is not None:
return chunk(0x2005, head + struct.pack("<H", link))
if kind == 0:
return chunk(0x2005, head + struct.pack("<HH", w, h) + pixels)
return chunk(0x2005, head + struct.pack("<HH", w, h) + zlib.compress(pixels))
def palette_chunk(colors, names=None):
body = struct.pack("<III8x", len(colors), 0, len(colors) - 1)
for i, c in enumerate(colors):
n = (names or {}).get(i)
body += struct.pack("<H4B", 1 if n else 0, *c) + (s(n) if n else b"")
return chunk(0x2019, body)
def old_palette_chunk(colors):
body = struct.pack("<HBB", 1, 0, len(colors) & 255) + b"".join(bytes(c[:3]) for c in colors)
return chunk(0x0004, body)
def tags_chunk(tags):
body = struct.pack("<H8x", len(tags))
for name, a, b, d, rep in tags:
body += struct.pack("<HHBH6x3Bx", a, b, d, rep, 255, 0, 0) + s(name)
return chunk(0x2018, body)
def user_chunk(text=None, color=None):
f = (1 if text is not None else 0) | (2 if color else 0)
return chunk(0x2020, struct.pack("<I", f) + (s(text) if text is not None else b"") + (bytes(color) if color else b""))
def sprite(w, h, depth, frames, transparent=0, flags=3, ncolors=0):
"""frames: [(duration_ms, [chunk bytes])]"""
body = b""
for dur, chunks in frames:
data = b"".join(chunks)
body += struct.pack("<IHHHxxI", len(data) + 16, 0xF1FA, min(len(chunks), 0xFFFF), dur, len(chunks)) + data
head = struct.pack("<IHHHHHIH II B3x H BB hhHH", 128 + len(body), 0xA5E0, len(frames), w, h, depth, flags, 100, 0, 0, transparent, ncolors, 1, 1, 0, 0, 16, 16)
head += b"\0" * (128 - len(head))
return head + body
def rgba(w, h, seed, alpha=True):
out = bytearray()
for y in range(h):
for x in range(w):
a = 255 if not alpha or (x + y) % 4 else (x * 50 + seed * 30) % 256
out += bytes(((x * (seed + 2) * 9 + y * 3) % 256, (y * (seed + 1) * 11 + x) % 256, ((x + seed) * (y + 2) * 5) % 256, a))
return bytes(out)
def case_rgba():
W, H = 32, 24
cels = []
def cel(frame, layer, x, y, w, h, px, **kw):
cels.append({"frame": frame, "layer": layer, "x": x, "y": y, "w": w, "h": h, "crc": zlib.crc32(px)})
return cel_chunk(layer - 1, x, y, w, h, px, **kw)
bg = rgba(W, H, 1, alpha=False)
pal = [(i, 255 - i, (i * 7) % 256, 255) for i in range(0, 256, 16)]
f1 = [
palette_chunk(pal, {0: "first", 3: "fourth"}),
layer_chunk("Background", flags=1 | 2 | 8),
layer_chunk("Group", ltype=1, flags=3),
layer_chunk("Mul", level=1, blend=1, opacity=200),
user_chunk("mul layer", (1, 2, 3, 4)),
layer_chunk("Half", level=1),
layer_chunk("Hidden", flags=2),
layer_chunk("Top"),
tags_chunk([("walk", 0, 1, 0, 0), ("back", 1, 2, 2, 3)]),
user_chunk("walk tag"),
user_chunk(None),
cel(1, 1, 0, 0, W, H, bg, kind=0),
cel(1, 3, 4, 3, 16, 12, rgba(16, 12, 2)),
user_chunk("a cel"),
cel(1, 4, 10, 8, 14, 10, rgba(14, 10, 3), opacity=128),
cel(1, 5, 0, 0, 8, 8, rgba(8, 8, 4)),
cel(1, 6, 20, 2, 10, 20, rgba(10, 20, 5)),
]
f2 = [
cel_chunk(0, 0, 0, W, H, bg, link=0),
cel(2, 3, 6, 5, 16, 12, rgba(16, 12, 6)),
cel(2, 6, -4, 10, 12, 8, rgba(12, 8, 7), kind=0),
]
f3 = [
cel_chunk(0, 0, 0, W, H, bg, link=0),
cel_chunk(2, 4, 3, 16, 12, b"", link=0),
cel(3, 4, 1, 1, 30, 20, rgba(30, 20, 8), opacity=64),
]
# linked cels repeat their target
cels.append({"frame": 2, "layer": 1, "x": 0, "y": 0, "w": W, "h": H, "crc": zlib.crc32(bg)})
cels.append({"frame": 3, "layer": 1, "x": 0, "y": 0, "w": W, "h": H, "crc": zlib.crc32(bg)})
cels.append({"frame": 3, "layer": 3, "x": 4, "y": 3, "w": 16, "h": 12, "crc": zlib.crc32(rgba(16, 12, 2))})
return sprite(W, H, 32, [(100, f1), (150, f2), (200, f3)], ncolors=len(pal)), cels
def case_gray():
cels = []
px = bytes(v for x in range(10 * 6) for v in ((x * 4) % 256, 255 if x % 3 else 128))
exp = b"".join(bytes((px[i * 2],) * 3 + (px[i * 2 + 1],)) for i in range(60))
cels.append({"frame": 1, "layer": 1, "x": 1, "y": 1, "w": 10, "h": 6, "crc": zlib.crc32(exp)})
cels.append({"frame": 2, "layer": 1, "x": 3, "y": 2, "w": 10, "h": 6, "crc": zlib.crc32(exp)})
f1 = [layer_chunk("G"), cel_chunk(0, 1, 1, 10, 6, px)]
f2 = [cel_chunk(0, 3, 2, 10, 6, px, kind=0)]
return sprite(14, 9, 16, [(80, f1), (80, f2)]), cels
def case_indexed():
# the background cel covers the sprite (as Aseprite writes it): its transparent index stays opaque
pal = [(0, 0, 0, 255), (255, 0, 0, 255), (0, 255, 0, 255), (0, 0, 255, 255), (255, 255, 0, 255)]
idx = bytes((x + y) % 5 for y in range(7) for x in range(9))
bgi = bytes((x * y) % 5 for y in range(9) for x in range(12))
exp = b"".join(bytes(pal[i][:3]) + bytes((0 if i == 0 else 255,)) for i in idx)
exp_bg = b"".join(bytes(pal[i]) for i in bgi)
cels = [{"frame": 1, "layer": 1, "x": 0, "y": 0, "w": 12, "h": 9, "crc": zlib.crc32(exp_bg)},
{"frame": 1, "layer": 2, "x": 2, "y": 1, "w": 9, "h": 7, "crc": zlib.crc32(exp)}]
f1 = [old_palette_chunk(pal), layer_chunk("Back", flags=1 | 2 | 8), layer_chunk("Sprite"), cel_chunk(0, 0, 0, 12, 9, bgi), cel_chunk(1, 2, 1, 9, 7, idx)]
return sprite(12, 9, 8, [(100, f1)], transparent=0, ncolors=5), cels
def libresprite(ctx, argv, cwd):
if shutil.which("libresprite"):
subprocess.run(["libresprite"] + argv, check=True, capture_output=True, cwd=cwd)
else:
subprocess.run(["nix", "shell", "nixpkgs#libresprite", "-c", "libresprite"] + argv, check=True, capture_output=True, cwd=cwd)
def rgba_of(ctx, png):
argv = ["magick", png, "-depth", "8", "rgba:-"]
try:
return subprocess.run(argv, check=True, capture_output=True).stdout
except (OSError, subprocess.CalledProcessError):
return ctx.nix("imagemagick", argv)
def render(ctx, data, nframes):
"""LibreSprite's flattened frames of an .ase (RGBA bytes each)"""
with tempfile.TemporaryDirectory() as d:
open(os.path.join(d, "in.aseprite"), "wb").write(data)
libresprite(ctx, ["-b", "in.aseprite", "--save-as", "f.png"], d)
if nframes == 1:
return [rgba_of(ctx, os.path.join(d, "f.png"))]
return [rgba_of(ctx, os.path.join(d, "f%d.png" % i)) for i in range(1, nframes + 1)]
def resave(ctx, data, ext_in="aseprite"):
with tempfile.TemporaryDirectory() as d:
open(os.path.join(d, "in." + ext_in), "wb").write(data)
libresprite(ctx, ["-b", "in." + ext_in, "--save-as", "out.aseprite"], d)
return open(os.path.join(d, "out.aseprite"), "rb").read()
def run_ours(ctx, fmt):
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
luau = shutil.which("luau")
argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt]
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)
def gif(ctx):
with tempfile.TemporaryDirectory() as d:
a, b, g = os.path.join(d, "a.png"), os.path.join(d, "b.png"), os.path.join(d, "anim.gif")
for argv in (["magick", "-size", "12x8", "gradient:red-blue", a], ["magick", "-size", "12x8", "xc:green", b], ["magick", "-delay", "20", a, b, "-loop", "0", g]):
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
return open(g, "rb").read()
def generate(ctx):
cases = []
for name, (data, cels) in (("rgba", case_rgba()), ("gray", case_gray()), ("indexed", case_indexed())):
n = struct.unpack_from("<H", data, 6)[0]
w, h = struct.unpack_from("<HH", data, 8)
cases.append({"name": name, "data": data, "width": w, "height": h, "nframes": n, "cels": cels, "frames": render(ctx, data, n)})
# sprites LibreSprite writes: our rgba case re-saved, and a GIF converted
re = resave(ctx, cases[0]["data"])
cases.append({"name": "libresprite-resave", "data": re, "width": 32, "height": 24, "nframes": 3, "cels": [], "frames": render(ctx, re, 3)})
g = resave(ctx, gif(ctx), "gif")
cases.append({"name": "libresprite-gif", "data": g, "width": 12, "height": 8, "nframes": 2, "cels": [], "frames": render(ctx, g, 2)})
ctx.emit("aseprite", {"cases": cases})
o = run_ours(ctx, "aseprite")
data = bytes.fromhex(o["data"])
ctx.emit("aseprite_ours", {"nframes": o["nframes"], "frames": render(ctx, data, o["nframes"]), "ours": [bytes.fromhex(f) for f in o["frames"]]})
+389
View File
@@ -0,0 +1,389 @@
# PSD fixtures (tools/fixtures.py): PSD / PSB files written here (a small writer below: every colour mode, 1/8/16/32
# bits, raw / RLE / ZIP / ZIP-with-prediction channels, groups, pass-through, clipping, masks, fill opacity, hidden
# layers, Unicode names, every blend mode) and one written by ImageMagick, all read by psd-tools (the reference):
# tests/gen/psd.luau { cases = { { name, data, width, height, composite (RGBA of psd-tools' merged image),
# layers = { { name, left, top, width, height, crc (RGBA of psd-tools' layer.topil()) } },
# flat (psd-tools' composite of the layers, RGBA) } } }
# tests/gen/psd_ours.luau { checks = { { label, ok } } }: our encoder's PSD (tools/fixtures/_ours.luau, run with
# luau) read by psd-tools, compared with the layers and the flattened image we wrote.
import json, os, random, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/layered/psd", "src/Formats/codecs/Blend.luau", "src/Formats/ops/LayerOps.luau", "tools/fixtures/_ours.luau"]
BLEND = ["norm", "diss", "dark", "mul ", "idiv", "lbrn", "dkCl", "lite", "scrn", "div ", "lddg", "lgCl", "over", "sLit",
"hLit", "vLit", "lLit", "pLit", "hMix", "diff", "smud", "fsub", "fdiv", "hue ", "sat ", "colr", "lum "]
def packbits(row):
out, i, n = bytearray(), 0, len(row)
while i < n:
j = i
while j + 1 < n and row[j + 1] == row[i] and j - i < 127:
j += 1
if j - i >= 2:
out += bytes([257 - (j - i + 1), row[i]])
i = j + 1
else:
k = i
while k < n and k - i < 128 and not (k + 2 < n and row[k] == row[k + 1] == row[k + 2]):
k += 1
out += bytes([k - i - 1]) + row[i:k]
i = k
return bytes(out)
def bytes_per(depth):
return {8: 1, 16: 2, 32: 4}[depth]
def channel_data(plane, w, h, depth, comp, psb=False):
"""plane: bytes (rows of w samples, big endian) -> compression code + data"""
rb = w * bytes_per(depth)
if w == 0 or h == 0:
return struct.pack(">H", 0)
if comp == 0:
return struct.pack(">H", 0) + plane
if comp == 1:
rows = [packbits(plane[y * rb:(y + 1) * rb]) for y in range(h)]
fmt = ">I" if psb else ">H"
return struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows)
if comp == 2:
return struct.pack(">H", 2) + zlib.compress(plane)
# zip with prediction
out = bytearray()
for y in range(h):
row = plane[y * rb:(y + 1) * rb]
if depth == 8:
out += bytes([row[0]] + [(row[x] - row[x - 1]) & 255 for x in range(1, w)])
elif depth == 16:
vals = struct.unpack(">%dH" % w, row)
out += struct.pack(">%dH" % w, *([vals[0]] + [(vals[x] - vals[x - 1]) & 0xFFFF for x in range(1, w)]))
else:
planes = bytes(row[x * 4 + k] for k in range(4) for x in range(w))
out += bytes([planes[0]] + [(planes[x] - planes[x - 1]) & 255 for x in range(1, len(planes))])
return struct.pack(">H", 3) + zlib.compress(bytes(out))
def pascal(name, pad=4):
b = name.encode("latin-1", "replace")[:255]
s = bytes([len(b)]) + b
while len(s) % pad:
s += b"\0"
return s
def block(key, data, psb=False):
while len(data) % 4:
data += b"\0"
return b"8BIM" + key + (struct.pack(">Q", len(data)) if psb and key in (b"Lr16", b"Lr32", b"Layr") else struct.pack(">I", len(data))) + data
def luni(name):
u = name.encode("utf-16-be")
return struct.pack(">I", len(u) // 2) + u
class Layer:
def __init__(self, name, left, top, w, h, chans, blend="norm", opacity=255, clip=0, hidden=False, section=None,
section_blend=None, fill=None, mask=None, comp=1):
self.__dict__.update(locals())
def layer_info(layers, depth, psb, neg):
recs, data = bytearray(), bytearray()
for L in layers:
recs += struct.pack(">iiii", L.top, L.left, L.top + L.h, L.left + L.w)
chans = list(L.chans.items())
if L.mask:
chans.append((-2, L.mask["plane"]))
recs += struct.pack(">H", len(chans))
for cid, plane in chans:
if cid == -2:
m = L.mask
cd = channel_data(plane, m["w"], m["h"], depth, 1, psb)
else:
cd = channel_data(plane, L.w, L.h, depth, L.comp, psb)
recs += struct.pack(">h", cid) + (struct.pack(">Q", len(cd)) if psb else struct.pack(">I", len(cd)))
data += cd
flags = 8 | (2 if L.hidden else 0) | (16 if L.section else 0)
recs += b"8BIM" + L.blend.encode() + bytes([L.opacity, L.clip, flags, 0])
ex = bytearray()
if L.mask:
m = L.mask
ex += struct.pack(">IiiiiBBH", 20, m["top"], m["left"], m["top"] + m["h"], m["left"] + m["w"], m["default"], m.get("flags", 0), 0)
else:
ex += struct.pack(">I", 0)
ex += struct.pack(">I", 0)
ex += pascal(L.name)
ex += block(b"luni", luni(L.name))
if L.section is not None:
ex += block(b"lsct", struct.pack(">I", L.section) + (b"8BIM" + L.section_blend.encode() if L.section_blend else b""))
if L.fill is not None:
ex += block(b"iOpa", bytes([L.fill, 0, 0, 0]))
recs += struct.pack(">I", len(ex)) + ex
body = struct.pack(">h", -len(layers) if neg else len(layers)) + recs + data
if len(body) % 2:
body += b"\0"
return body
def psd(w, h, mode, depth, nch, merged_planes, layers=None, psb=False, comp=1, palette=None, lr16=False, neg=True, resources=b""):
out = b"8BPS" + struct.pack(">H", 2 if psb else 1) + b"\0" * 6 + struct.pack(">HIIHH", nch, h, w, depth, mode)
cm = palette or b""
out += struct.pack(">I", len(cm)) + cm
out += struct.pack(">I", len(resources)) + resources
L = lambda n: struct.pack(">Q", n) if psb else struct.pack(">I", n)
if layers:
li = layer_info(layers, depth, psb, neg)
if lr16:
lm = L(0) + struct.pack(">I", 0) + block(b"Lr16" if depth == 16 else b"Lr32", li, psb)
else:
lm = L(len(li)) + li + struct.pack(">I", 0)
out += L(len(lm)) + lm
else:
out += L(0)
rb = (w + 7) // 8 if depth == 1 else w * bytes_per(depth)
if comp == 0:
out += struct.pack(">H", 0) + b"".join(merged_planes)
elif comp == 1:
rows = [packbits(p[y * rb:(y + 1) * rb]) for p in merged_planes for y in range(h)]
fmt = ">I" if psb else ">H"
out += struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows)
else:
out += struct.pack(">H", 2) + zlib.compress(b"".join(merged_planes))
return out
def plane8(w, h, f):
return bytes(f(x, y) & 255 for y in range(h) for x in range(w))
def plane16(w, h, f):
return b"".join(struct.pack(">H", f(x, y) & 0xFFFF) for y in range(h) for x in range(w))
def plane32(w, h, f):
return b"".join(struct.pack(">f", f(x, y)) for y in range(h) for x in range(w))
def rgba_layer(name, left, top, w, h, seed, **kw):
rng = random.Random(seed)
k = [rng.randrange(1, 9) for _ in range(8)]
chans = {
0: plane8(w, h, lambda x, y: x * k[0] * 7 + y * k[1]),
1: plane8(w, h, lambda x, y: y * k[2] * 9 + x * k[3]),
2: plane8(w, h, lambda x, y: (x ^ y) * k[4] * 5),
-1: plane8(w, h, lambda x, y: 255 if (x + y) % 5 else 90 + (x * k[5] * 13) % 160),
}
return Layer(name, left, top, w, h, chans, **kw)
def divider():
return Layer("</Layer group>", 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, section=3)
def group(name, blend="pass", opacity=255, hidden=False):
return Layer(name, 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, blend=blend, opacity=opacity, section=1, section_blend=blend, hidden=hidden)
def merged_rgb(w, h, alpha=True):
ps = [plane8(w, h, lambda x, y, c=c: x * 5 + y * 3 + c * 70) for c in range(3)]
if alpha:
ps.append(plane8(w, h, lambda x, y: 255 - x))
return ps
def cases():
W, H = 40, 30
out = []
# 1. a full RGB document: groups, pass-through, clipping, masks, fill, hidden, every compression
mask = {"top": 5, "left": 8, "w": 20, "h": 12, "default": 0, "plane": plane8(20, 12, lambda x, y: x * 12)}
layers = [
rgba_layer("Background", 0, 0, W, H, 1, comp=0),
rgba_layer("Multiply", 5, 4, 20, 15, 2, blend="mul ", opacity=200),
divider(),
rgba_layer("Screen", -3, 10, 25, 25, 3, blend="scrn", comp=2),
rgba_layer("Overlay", 15, 2, 30, 12, 4, blend="over", comp=3),
group("Isolated", blend="norm", opacity=180),
divider(),
rgba_layer("Diff é日", 10, 10, 20, 15, 5, blend="diff"),
rgba_layer("Hidden", 0, 0, 10, 10, 6, hidden=True),
group("Pass"),
rgba_layer("Base", 20, 15, 15, 10, 7),
rgba_layer("Clipped", 15, 12, 20, 14, 8, clip=1, blend="mul "),
rgba_layer("Masked", 2, 2, 30, 20, 9, mask=mask),
rgba_layer("Fill", 25, 0, 15, 30, 10, fill=128, blend="lite"),
]
out.append(("rgb-layers", psd(W, H, 3, 8, 4, merged_rgb(W, H), layers)))
# 2. every blend mode on its own (two layers)
for key in BLEND:
ls = [rgba_layer("Bottom", 0, 0, 24, 16, 11, comp=0), rgba_layer("Top " + key, 4, 2, 18, 12, 12, blend=key, opacity=230)]
out.append(("blend-" + key.strip(), psd(24, 16, 3, 8, 4, merged_rgb(24, 16), ls)))
# 3. 16-bit RGB with the layers in Lr16, ZIP with prediction
ch16 = lambda s: {0: plane16(12, 9, lambda x, y: x * 5000 + y * 31 + s), 1: plane16(12, 9, lambda x, y: y * 7000 + s), 2: plane16(12, 9, lambda x, y: (x * y * 997) + s), -1: plane16(12, 9, lambda x, y: 65535 - x * 3000)}
l16 = [Layer("L16a", 0, 0, 12, 9, ch16(1), comp=3), Layer("L16b", 3, 2, 12, 9, ch16(77), comp=1, blend="mul ")]
m16 = [plane16(16, 12, lambda x, y, c=c: x * 4000 + y * 100 + c * 9000) for c in range(3)] + [plane16(16, 12, lambda x, y: 65535)]
out.append(("rgb16-lr16", psd(16, 12, 3, 16, 4, m16, l16, lr16=True)))
# 4. 32-bit: merged only (floats) and a layer in Lr32
m32 = [plane32(10, 7, lambda x, y, c=c: (x + c) / 12.0) for c in range(3)]
l32 = [Layer("F", 1, 1, 6, 5, {0: plane32(6, 5, lambda x, y: x / 6.0), 1: plane32(6, 5, lambda x, y: y / 5.0), 2: plane32(6, 5, lambda x, y: 0.5), -1: plane32(6, 5, lambda x, y: 1.0)}, comp=3)]
out.append(("rgb32", psd(10, 7, 3, 32, 3, m32, l32, lr16=True, comp=0)))
# 5. greyscale with layers, raw merged
gl = [Layer("G1", 0, 0, 20, 10, {0: plane8(20, 10, lambda x, y: x * 12), -1: plane8(20, 10, lambda x, y: 255)}),
Layer("G2", 5, 3, 10, 6, {0: plane8(10, 6, lambda x, y: 200 - y * 20), -1: plane8(10, 6, lambda x, y: 128 + x * 10)}, blend="scrn")]
out.append(("gray", psd(20, 10, 1, 8, 2, [plane8(20, 10, lambda x, y: x * 12 + y), plane8(20, 10, lambda x, y: 255)], gl, comp=0)))
# 6. CMYK, merged + a layer
cm = [plane8(14, 8, lambda x, y, c=c: 255 - (x * 15 + c * 40) % 256) for c in range(4)]
cl = [Layer("C", 2, 1, 8, 5, {0: plane8(8, 5, lambda x, y: 200), 1: plane8(8, 5, lambda x, y: 40 * x), 2: plane8(8, 5, lambda x, y: 255), 3: plane8(8, 5, lambda x, y: 220 + y), -1: plane8(8, 5, lambda x, y: 255)})]
out.append(("cmyk", psd(14, 8, 4, 8, 4, cm, cl)))
# 7. indexed (merged only), 8. bitmap (merged only), 9. Lab
pal = bytes(range(256)) + bytes((i * 3) % 256 for i in range(256)) + bytes(255 - i for i in range(256))
out.append(("indexed", psd(17, 9, 2, 8, 1, [plane8(17, 9, lambda x, y: x * 15 + y)], palette=pal, comp=1)))
out.append(("bitmap", psd(24, 7, 0, 1, 1, [bytes((x * 37 + y * 11) & 255 for y in range(7) for x in range(3))], comp=0)))
out.append(("lab", psd(9, 5, 9, 8, 3, [plane8(9, 5, lambda x, y: x * 28), plane8(9, 5, lambda x, y: 100 + y * 10), plane8(9, 5, lambda x, y: 150)], comp=1)))
# 10. PSB with layers (8-byte lengths, 4-byte RLE counts)
out.append(("psb", psd(W, H, 3, 8, 4, merged_rgb(W, H), [rgba_layer("A", 0, 0, W, H, 21), rgba_layer("B", 3, 3, 10, 10, 22, blend="mul ")], psb=True)))
# 11. no alpha in the merged image, positive layer count
out.append(("rgb-noalpha", psd(W, H, 3, 8, 3, merged_rgb(W, H, False), [rgba_layer("Only", 0, 0, W, H, 31)], neg=False)))
return out
REF = r'''
import json, os, sys, zlib
from psd_tools import PSDImage
d = %r
res = []
for name in sorted(os.listdir(d)):
if not name.endswith(".psd"):
continue
psd = PSDImage.open(os.path.join(d, name))
c = {"name": name[:-4], "width": psd.width, "height": psd.height}
try:
im = psd.topil()
c["composite"] = im.convert("RGBA").tobytes().hex() if im is not None else ""
except Exception as e:
c["composite"] = ""
layers = []
for l in psd.descendants():
if l.is_group():
layers.append({"name": l.name, "group": True})
continue
e = {"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height}
try:
im = l.topil()
if im is not None:
e["crc"] = zlib.crc32(im.convert("RGBA").tobytes())
except Exception:
pass
layers.append(e)
c["layers"] = layers
try:
f = psd.composite(force=True, color=0.0, alpha=0.0)
c["flat"] = f.convert("RGBA").tobytes().hex()
except Exception as e:
c["flaterr"] = str(e)
res.append(c)
print(json.dumps(res))
'''
def pyrun(ctx, code):
try:
return ctx.python(["psd-tools", "numpy", "pillow"], code)
except subprocess.CalledProcessError as e:
raise RuntimeError("psd-tools failed:\n" + e.stderr.decode(errors="replace"))
def reference(ctx, files):
with tempfile.TemporaryDirectory() as d:
for name, data in files:
open(os.path.join(d, name + ".psd"), "wb").write(data)
res = json.loads(pyrun(ctx, REF % d))
by = {r["name"]: r for r in res}
out = []
for name, data in files:
r = by[name]
case = {"name": name, "data": data, "width": r["width"], "height": r["height"], "composite": bytes.fromhex(r["composite"])}
if "flat" in r:
case["flat"] = bytes.fromhex(r["flat"])
case["layers"] = r["layers"]
out.append(case)
return out
def imagemagick(ctx):
# image 0 is the merged image, the rest are layers (ImageMagick 7.1 writes the blend key of some layers byte-reversed
# ("mron"), which psd-tools refuses: these layers avoid it)
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "im.psd")
argv = ["magick", "-size", "32x24", "gradient:red-blue", "(", "-clone", "0", ")",
"(", "-size", "8x8", "radial-gradient:yellow-none", "-repage", "+20+10", ")", p]
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
return open(p, "rb").read()
def generate(ctx):
files = cases()
files.append(("imagemagick", imagemagick(ctx)))
ctx.emit("psd", {"cases": reference(ctx, files)})
ctx.emit("psd_ours", {"checks": ours(ctx)})
def run_ours(ctx, fmt):
"""our encoder's output and facts, from tools/fixtures/_ours.luau"""
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
argv = [shutil.which("luau") or "luau", script, "-a", fmt]
if shutil.which("luau"):
out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout
else:
out = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt], check=True, capture_output=True, cwd=ctx.root).stdout
return json.loads(out)
OURS = r'''
import json, sys, zlib
from psd_tools import PSDImage
psd = PSDImage.open(%r)
res = {"width": psd.width, "height": psd.height, "composite": zlib.crc32(psd.topil().convert("RGBA").tobytes()), "layers": []}
for l in psd.descendants():
if l.is_group():
res["layers"].append({"group": True, "name": l.name, "blend": str(l.blend_mode), "opacity": l.opacity, "visible": l.visible})
continue
res["layers"].append({"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height,
"crc": zlib.crc32(l.topil().convert("RGBA").tobytes()), "blend": str(l.blend_mode), "opacity": l.opacity,
"visible": l.visible, "clip": bool(l.clipping_layer), "mask": l.has_mask()})
print(json.dumps(res))
'''
PSD_BLEND = {"normal": "NORMAL", "multiply": "MULTIPLY", "screen": "SCREEN", "difference": "DIFFERENCE", "lighten": "LIGHTEN"}
def ours(ctx):
o = run_ours(ctx, "psd")
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "ours.psd")
open(p, "wb").write(bytes.fromhex(o["data"]))
ref = json.loads(pyrun(ctx, OURS % p))
checks = []
def check(label, ok):
checks.append({"label": label, "ok": bool(ok)})
check("psd-tools: composite = our flatten", ref["composite"] == o["composite"])
leaves = [l for l in ref["layers"] if not l.get("group")]
check("psd-tools: leaf count", len(leaves) == len(o["layers"]))
for want, got in zip(o["layers"], leaves):
n = want["name"]
check(n + ": name", got["name"] == n)
check(n + ": pixels", got["crc"] == want["crc"])
check(n + ": bounds", (got["left"], got["top"], got["width"], got["height"]) == (want["left"], want["top"], want["width"], want["height"]))
check(n + ": blend", got["blend"].endswith(PSD_BLEND.get(want["blend"], "?")))
check(n + ": opacity", got["opacity"] == want["opacity"])
check(n + ": visible", got["visible"] == want["visible"])
check(n + ": clip", got["clip"] == want["clip"])
groups = [l for l in ref["layers"] if l.get("group")]
check("psd-tools: two groups", [g["name"] for g in groups] == ["Isolated", "Pass"])
check("psd-tools: pass-through group", len(groups) == 2 and groups[1]["blend"].endswith("PASS_THROUGH") and groups[0]["blend"].endswith("NORMAL"))
check("psd-tools: masked layer has a mask", any(l.get("mask") for l in leaves if l["name"] == "Masked"))
return checks
+140
View File
@@ -0,0 +1,140 @@
# Subtitle fixtures (tests/gen/subtitles.luau, for tests/subtitle/srt.luau, vtt.luau and ass.luau) with
# ffmpeg as the reference: a random SRT script converted by ffmpeg to SRT / WebVTT / ASS, and hand-written WebVTT /
# ASS / SSA files with their features, converted by ffmpeg to SRT. Every case carries the expected cues
# ({ start_ms, stop_ms, plain text }) so the tests compare our decode with ffmpeg's view of the same file.
import os, random, re, shutil, subprocess, tempfile
WORDS = ["alpha", "beta", "gamma", "delta", "omega", "café", "naïve", "日本", "fox", "dog", "42", "hello", "world"]
def ffmpeg(ctx, src_bytes, src_ext, dst_ext):
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "in." + src_ext)
dst = os.path.join(d, "out." + dst_ext)
open(src, "wb").write(src_bytes)
argv = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src, dst]
if shutil.which("ffmpeg"):
subprocess.run(argv, check=True, capture_output=True)
else:
ctx.nix("ffmpeg", argv)
return open(dst, "rb").read()
def plain(s):
return re.sub(r"{[^}]*}", "", re.sub(r"<[^>]*>", "", s)).replace("&amp;", "&")
def srt_time(ms):
return "%02d:%02d:%02d,%03d" % (ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000)
def random_srt(rng, n):
cues, t = [], 500
for i in range(n):
start = t + rng.randrange(0, 3000)
stop = start + rng.randrange(300, 5000)
t = stop
lines = []
for _ in range(rng.randrange(1, 3)):
words = [rng.choice(WORDS) for _ in range(rng.randrange(1, 6))]
if rng.random() < 0.3:
k = rng.randrange(len(words))
tag = rng.choice("ibu")
words[k] = "<%s>%s</%s>" % (tag, words[k], tag)
lines.append(" ".join(words))
cues.append((start, stop, "\n".join(lines)))
text = "".join("%d\n%s --> %s\n%s\n\n" % (i + 1, srt_time(a), srt_time(b), t) for i, (a, b, t) in enumerate(cues))
return text.encode(), [{"start": a, "stop": b, "plain": plain(t)} for a, b, t in cues]
VTT = """WEBVTT - a test file
Kind: captions
STYLE
::cue { color: yellow }
REGION
id:r1 width:40%
NOTE this is a comment
over two lines
intro
00:01.000 --> 00:04.500 align:start position:10%
<v Roger>Hello <i>there</i></v>
00:05.250 --> 00:07.000
first line
second line
01:00:02.000 --> 01:00:03.123 line:0
<c.loud>an hour in</c> &amp; more
"""
ASS = """[Script Info]
; Script generated by hand
Title: test
ScriptType: v4.00+
PlayResX: 640
PlayResY: 480
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
Style: Top,Verdana,24,&H0000FFFF,&H000000FF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,2,0,8,10,10,10,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.00,0:00:03.50,Default,Bob,0,0,0,,Hello, {\\i1}world{\\i0}!
Comment: 0,0:00:02.00,0:00:04.00,Default,,0,0,0,,a comment line
Dialogue: 1,0:00:04.20,0:00:06.00,Top,,0,0,0,,{\\an8\\b1}Bold top{\\b0}\\Nsecond line
Dialogue: 0,0:01:02.03,0:01:05.99,Default,,0,0,0,,{\\pos(10,20)}commas, inside, the text
[Fonts]
fontname: x.ttf
ABCDEF
"""
SSA = """[Script Info]
Title: old
ScriptType: v4.00
[V4 Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding
Style: Default,Tahoma,24,16777215,65535,65535,-2147483640,-1,0,1,3,0,2,30,30,30,0,0
[Events]
Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: Marked=0,0:00:00.50,0:00:02.00,Default,,0000,0000,0000,,old style
Dialogue: Marked=0,0:00:02.50,0:00:04.25,Default,,0000,0000,0000,,{\\i1}two{\\i0}\\Nlines
"""
def parse_srt(data):
"""the cues of an SRT (ffmpeg's output) -> [{start, stop, plain}]"""
out = []
text = data.decode("utf-8-sig").replace("\r\n", "\n")
for block in re.split(r"\n\s*\n", text.strip()):
lines = block.split("\n")
for k, l in enumerate(lines):
m = re.match(r"(\d+):(\d+):(\d+)[,.](\d+) --> (\d+):(\d+):(\d+)[,.](\d+)", l)
if m:
g = [int(x) for x in m.groups()]
out.append({"start": ((g[0] * 60 + g[1]) * 60 + g[2]) * 1000 + g[3], "stop": ((g[4] * 60 + g[5]) * 60 + g[6]) * 1000 + g[7], "plain": plain("\n".join(lines[k + 1:]))})
break
return out
def generate(ctx):
rng = random.Random(7)
src, cues = random_srt(rng, 40)
out = {"srt": src, "cues": cues}
for ext in ("srt", "vtt", "ass"):
out["ffmpeg_" + ext] = ffmpeg(ctx, src, "srt", ext)
hand = []
for name, ext, data in (("vtt", "vtt", VTT), ("ass", "ass", ASS), ("ssa", "ssa", SSA)):
b = data.encode()
ref = ffmpeg(ctx, b, ext, "srt")
hand.append({"name": name, "data": b, "ffmpeg_srt": ref, "cues": parse_srt(ref)})
out["hand"] = hand
ctx.emit("subtitles", out)
+202
View File
@@ -0,0 +1,202 @@
# SVG fixtures (tools/fixtures.py): hand-written SVGs, one feature area each, rendered by resvg (nixpkgs#resvg, the
# reference rasterizer), and the same documents decoded and written back by our encoder (tools/fixtures/_ours.luau)
# then rendered by resvg too:
# tests/gen/svg.luau { cases = { { name, svg, width, height, ref (resvg RGBA), ours (our SVG text), ours_ref
# (resvg's RGBA of our SVG) } } }
import json, os, shutil, subprocess, tempfile
INPUTS = ["src/Formats/vector/svg", "tools/fixtures/_ours.luau"]
def svg(w, h, body, extra=""):
return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="%d" height="%d"%s>\n%s\n</svg>\n' % (w, h, extra, body)
CASES = {
"shapes": svg(64, 64, """
<rect x="4" y="4" width="20" height="14" fill="red"/>
<rect x="30" y="4" width="28" height="16" rx="5" fill="#0a0" stroke="black" stroke-width="2"/>
<circle cx="14" cy="34" r="9" fill="blue"/>
<ellipse cx="44" cy="34" rx="14" ry="7" fill="orange" stroke="purple"/>
<line x1="4" y1="50" x2="30" y2="60" stroke="black" stroke-width="3"/>
<polyline points="34,60 40,48 46,58 52,46 60,60" fill="none" stroke="teal" stroke-width="2"/>
<polygon points="4,62 10,52 16,62" fill="magenta"/>"""),
"path-commands": svg(64, 64, """
<path d="M4 4 L20 4 H28 V12 L4 12 Z" fill="#c00"/>
<path d="m34 4 l10 0 h8 v8 l-18 0 z" fill="#0c0"/>
<path d="M4 20 C10 14 18 30 24 20 S36 26 40 20" fill="none" stroke="blue" stroke-width="2"/>
<path d="M4 34 Q14 24 24 34 T44 34 T60 30" fill="none" stroke="black" stroke-width="2"/>
<path d="m4 44 c4-6 12 6 16 0 s8-6 12 0 q4 6 8 0 t8 0" fill="none" stroke="#a0a" stroke-width="2"/>
<path d="M4,60L10,52,16,60zM20 60 52 60 36 50z" fill="gold" stroke="brown"/>"""),
"arcs": svg(64, 64, """
<path d="M8 16 A12 8 0 0 1 32 16" fill="none" stroke="red" stroke-width="2"/>
<path d="M36 16 A12 8 0 1 0 60 16" fill="none" stroke="blue" stroke-width="2"/>
<path d="M8 40 a10 10 0 1 1 20 0 a10 10 0 1 1 -20 0" fill="#9c9"/>
<path d="M36 32 A14 6 30 0 1 58 48" fill="none" stroke="black" stroke-width="2"/>
<path d="M36 58 A3 3 0 0 1 58 58" fill="none" stroke="purple" stroke-width="2"/>"""),
"transforms": svg(64, 64, """
<g transform="translate(32 32)">
<rect x="-6" y="-6" width="12" height="12" fill="red" transform="rotate(30)"/>
<g transform="scale(1.5, 0.75)"><circle cx="12" cy="-20" r="5" fill="blue"/></g>
<rect x="-28" y="10" width="14" height="10" fill="green" transform="skewX(20)"/>
<rect x="10" y="10" width="10" height="10" fill="orange" transform="matrix(1 0.3 -0.2 1 2 0) rotate(-15 15 15)"/>
</g>"""),
"stroke-styles": svg(64, 64, """
<polyline points="6,20 18,6 30,20" fill="none" stroke="black" stroke-width="6" stroke-linejoin="miter"/>
<polyline points="36,20 48,6 60,20" fill="none" stroke="black" stroke-width="6" stroke-linejoin="round"/>
<polyline points="6,40 18,26 30,40" fill="none" stroke="black" stroke-width="6" stroke-linejoin="bevel"/>
<polyline points="36,40 48,38 60,40" fill="none" stroke="black" stroke-width="5" stroke-miterlimit="1.5"/>
<line x1="8" y1="48" x2="56" y2="48" stroke="blue" stroke-width="5" stroke-linecap="butt"/>
<line x1="8" y1="55" x2="56" y2="55" stroke="blue" stroke-width="5" stroke-linecap="round"/>
<line x1="8" y1="62" x2="56" y2="62" stroke="blue" stroke-width="3" stroke-linecap="square"/>"""),
"dashes": svg(64, 64, """
<line x1="4" y1="8" x2="60" y2="8" stroke="black" stroke-width="3" stroke-dasharray="6 3"/>
<line x1="4" y1="18" x2="60" y2="18" stroke="red" stroke-width="3" stroke-dasharray="5,2,1" stroke-dashoffset="3"/>
<circle cx="20" cy="42" r="14" fill="none" stroke="blue" stroke-width="3" stroke-dasharray="8 4"/>
<rect x="40" y="30" width="20" height="24" fill="none" stroke="green" stroke-width="2" stroke-dasharray="4" stroke-linecap="round"/>"""),
"fill-rule": svg(64, 32, """
<path d="M16 2 L22 30 L2 12 L30 12 L10 30 Z" fill="navy" fill-rule="nonzero"/>
<path d="M48 2 L54 30 L34 12 L62 12 L42 30 Z" fill="navy" fill-rule="evenodd"/>"""),
"opacity": svg(64, 64, """
<rect x="2" y="2" width="60" height="60" fill="#eee"/>
<g opacity="0.5"><rect x="6" y="6" width="24" height="24" fill="red"/><rect x="16" y="16" width="24" height="24" fill="blue"/></g>
<rect x="34" y="6" width="24" height="24" fill="green" fill-opacity="0.4" stroke="black" stroke-width="4" stroke-opacity="0.6"/>
<circle cx="20" cy="48" r="12" fill="orange" stroke="purple" stroke-width="6" opacity="0.6"/>
<circle cx="46" cy="48" r="12" fill="rgba(0,0,255,0.5)"/>"""),
"linear-gradient": svg(64, 64, """
<defs>
<linearGradient id="a"><stop offset="0" stop-color="red"/><stop offset="0.5" stop-color="yellow"/><stop offset="1" stop-color="blue"/></linearGradient>
<linearGradient id="b" x1="0" y1="0" x2="0.3" y2="0" spreadMethod="reflect"><stop offset="0" stop-color="#000"/><stop offset="1" stop-color="#fff"/></linearGradient>
<linearGradient id="c" x1="0" y1="0" x2="0.25" y2="0.25" spreadMethod="repeat"><stop offset="0%" stop-color="green"/><stop offset="100%" stop-color="white" stop-opacity="0.2"/></linearGradient>
<linearGradient id="d" gradientTransform="rotate(90 0.5 0.5)"><stop offset="0" stop-color="purple"/><stop offset="1" stop-color="orange"/></linearGradient>
</defs>
<rect x="2" y="2" width="60" height="12" fill="url(#a)"/>
<rect x="2" y="16" width="60" height="12" fill="url(#b)"/>
<rect x="2" y="30" width="28" height="30" fill="url(#c)"/>
<circle cx="47" cy="45" r="14" fill="url(#d)" stroke="url(#a)" stroke-width="3"/>"""),
"radial-gradient": svg(64, 64, """
<defs>
<radialGradient id="r1"><stop offset="0" stop-color="white"/><stop offset="1" stop-color="blue"/></radialGradient>
<radialGradient id="r2" cx="0.5" cy="0.5" r="0.5" fx="0.25" fy="0.25"><stop offset="0" stop-color="yellow"/><stop offset="0.6" stop-color="red"/><stop offset="1" stop-color="black"/></radialGradient>
<radialGradient id="r3" gradientUnits="userSpaceOnUse" cx="16" cy="48" r="8" spreadMethod="repeat"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#080"/></radialGradient>
</defs>
<rect x="2" y="2" width="28" height="28" fill="url(#r1)"/>
<ellipse cx="47" cy="16" rx="15" ry="12" fill="url(#r2)"/>
<rect x="2" y="34" width="28" height="28" fill="url(#r3)"/>
<circle cx="47" cy="48" r="13" fill="url(#r2)" fill-opacity="0.7"/>"""),
"gradient-href": svg(64, 32, """
<defs>
<linearGradient id="base"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient>
<linearGradient id="tilted" xlink:href="#base" x2="0" y2="1"/>
<radialGradient id="rad" href="#base"/>
</defs>
<rect x="2" y="2" width="28" height="28" fill="url(#tilted)"/>
<rect x="34" y="2" width="28" height="28" fill="url(#rad)"/>"""),
"css": svg(64, 64, """
<style>
rect { fill: red; stroke: black }
.blue { fill: blue }
#special { fill: green; stroke-width: 4 }
circle.big, ellipse { fill: orange; }
/* a comment */
@media print { rect { fill: pink } }
</style>
<rect x="4" y="4" width="20" height="20"/>
<rect x="30" y="4" width="20" height="20" class="blue"/>
<rect x="4" y="30" width="20" height="20" class="blue" id="special"/>
<rect x="30" y="30" width="20" height="20" class="blue" style="fill: purple"/>
<circle class="big" cx="58" cy="58" r="5"/>
<ellipse cx="10" cy="58" rx="6" ry="4" fill="black"/>"""),
"use-symbol": svg(64, 64, """
<defs>
<g id="dot"><circle r="5" fill="red"/><circle r="2" fill="white"/></g>
<symbol id="sym" viewBox="0 0 10 10"><rect width="10" height="10" fill="blue"/><path d="M0 0 L10 10" stroke="white"/></symbol>
<rect id="bar" width="20" height="4"/>
</defs>
<use href="#dot" x="10" y="10"/>
<use xlink:href="#dot" transform="translate(30 10) scale(1.5)"/>
<use href="#sym" x="4" y="24" width="20" height="20"/>
<use href="#sym" x="30" y="24" width="30" height="15"/>
<use href="#bar" x="4" y="54" fill="green"/>
<use href="#bar" x="30" y="54" style="fill: orange" opacity="0.5"/>"""),
"viewbox-meet": svg(64, 40, """
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="red"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="xMinYMax meet"'),
"viewbox-slice": svg(64, 40, """
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="blue"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice"'),
"viewbox-none": svg(64, 40, """
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="green"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="none"'),
"nested-svg": svg(64, 64, """
<rect width="64" height="64" fill="#eef"/>
<svg x="8" y="8" width="48" height="24" viewBox="0 0 20 10"><circle cx="5" cy="5" r="5" fill="red"/><circle cx="15" cy="5" r="5" fill="blue"/></svg>
<svg x="8" y="36" width="20" height="20"><rect x="5" y="5" width="50%" height="50%" fill="green"/><circle cx="20" cy="10" r="8" fill="red"/></svg>"""),
"clip-path": svg(64, 64, """
<defs>
<clipPath id="c1"><circle cx="16" cy="16" r="12"/></clipPath>
<clipPath id="c2" clipPathUnits="objectBoundingBox"><rect x="0.25" y="0" width="0.5" height="1"/></clipPath>
<clipPath id="c3"><path d="M34 34 h26 v26 h-26z M40 40 h14 v14 h-14z" clip-rule="evenodd"/></clipPath>
</defs>
<rect x="2" y="2" width="30" height="30" fill="red" clip-path="url(#c1)"/>
<g clip-path="url(#c2)"><rect x="34" y="2" width="28" height="28" fill="blue"/><circle cx="48" cy="16" r="10" fill="yellow"/></g>
<rect x="2" y="34" width="28" height="28" fill="green" clip-path="url(#c2)"/>
<rect x="34" y="34" width="28" height="28" fill="purple" clip-path="url(#c3)"/>"""),
"units": svg(64, 64, """
<rect x="2mm" y="2mm" width="10mm" height="5mm" fill="red"/>
<rect x="40pt" y="4" width="12pt" height="12pt" fill="blue"/>
<rect x="10%" y="50%" width="25%" height="10%" fill="green"/>
<circle cx="48" cy="48" r="1em" fill="orange" style="font-size: 8px"/>
<rect x="4" y="52" width="1in" height="0.1in" fill="black" transform="scale(0.5)"/>"""),
"colors": svg(64, 32, """
<g color="teal">
<rect x="0" y="0" width="8" height="16" fill="cornflowerblue"/>
<rect x="8" y="0" width="8" height="16" fill="#f80"/>
<rect x="16" y="0" width="8" height="16" fill="#ff008080"/>
<rect x="24" y="0" width="8" height="16" fill="rgb(10%, 50%, 90%)"/>
<rect x="32" y="0" width="8" height="16" fill="rgba(200, 0, 100, 0.5)"/>
<rect x="40" y="0" width="8" height="16" fill="hsl(120, 100%, 25%)"/>
<rect x="48" y="0" width="8" height="16" fill="currentColor"/>
<rect x="56" y="0" width="8" height="16" fill="transparent" stroke="currentColor"/>
<rect x="0" y="16" width="64" height="16" fill="none" stroke="DarkOrchid" stroke-width="4"/>
</g>"""),
"inheritance": svg(64, 64, """
<g fill="red" stroke="blue" stroke-width="3">
<rect x="4" y="4" width="24" height="24"/>
<g fill="green"><rect x="36" y="4" width="24" height="24" stroke="inherit"/></g>
<g style="stroke: none"><circle cx="16" cy="46" r="12"/></g>
<g display="none"><rect x="36" y="36" width="24" height="24"/></g>
<rect x="36" y="36" width="10" height="10" visibility="hidden"/>
<g visibility="hidden"><rect x="48" y="48" width="12" height="12" visibility="visible"/></g>
</g>"""),
}
def resvg(ctx, data, w, h):
with tempfile.TemporaryDirectory() as d:
src, png = os.path.join(d, "in.svg"), os.path.join(d, "out.png")
open(src, "wb").write(data)
argv = ["resvg", "-w", str(w), "-h", str(h), src, png]
if shutil.which("resvg"):
subprocess.run(argv, check=True, capture_output=True)
else:
subprocess.run(["nix", "shell", "nixpkgs#resvg", "-c"] + argv, check=True, capture_output=True)
argv = ["magick", png, "-depth", "8", "rgba:-"]
try:
return subprocess.run(argv, check=True, capture_output=True).stdout
except (OSError, subprocess.CalledProcessError):
return ctx.nix("imagemagick", argv)
def ours(ctx, text):
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
luau = shutil.which("luau")
argv = [luau, script, "-a", "svg", text] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", "svg", text]
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)["svg"]
def generate(ctx):
import re
cases = []
for name, text in CASES.items():
w, h = (int(x) for x in re.search(r'width="(\d+)" height="(\d+)"', text).groups())
data = text.encode()
mine = ours(ctx, text)
cases.append({"name": name, "svg": data, "width": w, "height": h, "ref": resvg(ctx, data, w, h), "ours": mine,
"ours_ref": resvg(ctx, mine.encode(), w, h)})
ctx.emit("svg", {"cases": cases})
+279
View File
@@ -0,0 +1,279 @@
# Tiled fixtures (tools/fixtures.py), with Tiled itself (nixpkgs#tiled, run headless) as the reference:
# tests/gen/tiled.luau { cases = { { name, tmx (hand-written), tmj (Tiled's export), tiled_tmx (Tiled's re-save) } },
# tsx, tsj (an external tileset and Tiled's JSON export of it) }
# tests/gen/tiled_ours.luau { checks = { { label, ok } } }: a map built and written by our encoder (TMX with
# base64 + zlib data, and TMJ; tools/fixtures/_ours.luau) re-exported by Tiled as JSON and
# compared with our own TMJ
import base64, gzip, json, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/vector/tiled", "tools/fixtures/_ours.luau"]
TSX = """<?xml version="1.0" encoding="UTF-8"?>
<tileset version="1.10" tiledversion="1.10.2" name="ext" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
<tileoffset x="2" y="-3"/>
<properties>
<property name="kind" value="terrain"/>
</properties>
<image source="tiles.png" width="64" height="32"/>
<tile id="1" type="Water" probability="0.5">
<properties>
<property name="speed" type="float" value="0.25"/>
</properties>
<animation>
<frame tileid="1" duration="100"/>
<frame tileid="2" duration="150"/>
</animation>
</tile>
<tile id="5">
<objectgroup draworder="index" id="2">
<object id="1" x="1" y="2" width="10" height="12"/>
<object id="2" x="3" y="3">
<ellipse/>
</object>
</objectgroup>
</tile>
</tileset>
"""
def layer_bytes(gids):
return b"".join(struct.pack("<I", g) for g in gids)
def ortho():
W, H = 6, 4
g1 = [(x + y * W) % 9 for y in range(H) for x in range(W)]
g1[3] |= 0x80000000
g1[7] |= 0x40000000
g1[11] |= 0x20000000
g2 = [(x * y) % 5 for y in range(H) for x in range(W)]
g3 = [9 + (x + y) % 8 if (x + y) % 3 else 0 for y in range(H) for x in range(W)]
g4 = [1 + (x % 2) for y in range(H) for x in range(W)]
csv = ",\n".join(",".join(str(g) for g in g1[y * W:(y + 1) * W]) for y in range(H))
z = base64.b64encode(zlib.compress(layer_bytes(g2))).decode()
gz = base64.b64encode(gzip.compress(layer_bytes(g3), mtime=0)).decode()
raw = base64.b64encode(layer_bytes(g4)).decode()
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" class="Level" orientation="orthogonal" renderorder="left-up" width="{W}" height="{H}" tilewidth="16" tileheight="16" backgroundcolor="#ff102030" infinite="0" nextlayerid="9" nextobjectid="10">
<properties>
<property name="title" value="Ünïcode &amp; more"/>
<property name="count" type="int" value="42"/>
<property name="ratio" type="float" value="1.5"/>
<property name="on" type="bool" value="true"/>
<property name="tint" type="color" value="#80ff0000"/>
<property name="file" type="file" value="other.tmx"/>
<property name="target" type="object" value="3"/>
<property name="notes">line one
line two</property>
</properties>
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
<tile id="0">
<properties>
<property name="solid" type="bool" value="true"/>
</properties>
</tile>
<tile id="3" type="Door"/>
</tileset>
<tileset firstgid="9" source="ext.tsx"/>
<layer id="1" name="csv" width="{W}" height="{H}" opacity="0.75" offsetx="3" offsety="-2" tintcolor="#ff00ff">
<properties>
<property name="layerprop" value="x"/>
</properties>
<data encoding="csv">
{csv}
</data>
</layer>
<layer id="2" name="zlib" width="{W}" height="{H}" visible="0" parallaxx="0.5">
<data encoding="base64" compression="zlib">
{z}
</data>
</layer>
<layer id="3" name="gzip" width="{W}" height="{H}" locked="1">
<data encoding="base64" compression="gzip">
{gz}
</data>
</layer>
<layer id="4" name="raw" class="Deco" width="{W}" height="{H}">
<data encoding="base64">
{raw}
</data>
</layer>
<group id="5" name="group" opacity="0.5" offsetx="1">
<imagelayer id="6" name="sky" repeatx="1">
<image source="sky.png" width="40" height="20"/>
</imagelayer>
<objectgroup id="7" name="things" color="#a0a0a4" draworder="index">
<object id="1" name="box" type="Crate" x="10" y="12.5" width="16" height="8" rotation="45">
<properties>
<property name="weight" type="float" value="2.25"/>
</properties>
</object>
<object id="2" name="ring" x="40" y="5" width="10" height="10">
<ellipse/>
</object>
<object id="3" name="spot" x="7" y="9">
<point/>
</object>
<object id="4" name="poly" x="20" y="20">
<polygon points="0,0 16,0 8,-12.5"/>
</object>
<object id="5" name="line" x="30" y="30" visible="0">
<polyline points="0,0 5,5 10,0 15,5"/>
</object>
<object id="6" name="label" x="2" y="40" width="80" height="20">
<text fontfamily="Serif" pixelsize="12" wrap="1" color="#ff0000" bold="1" halign="center" valign="bottom">Hello &lt;Tiled&gt;</text>
</object>
<object id="7" name="tile" gid="2147483651" x="50" y="50" width="16" height="16"/>
</objectgroup>
</group>
</map>
"""
def iso():
W, H = 3, 3
tiles = "\n".join(' <tile gid="%d"/>' % ((x + y) % 4) for y in range(H) for x in range(W))
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" orientation="hexagonal" renderorder="right-down" width="{W}" height="{H}" tilewidth="32" tileheight="28" infinite="0" hexsidelength="14" staggeraxis="x" staggerindex="even" nextlayerid="2" nextobjectid="1">
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
</tileset>
<layer id="1" name="xmltiles" width="{W}" height="{H}">
<data>
{tiles}
</data>
</layer>
</map>
"""
def infinite():
def chunk(cx, cy):
g = [(cx // 16 + cy // 16 + x + y) % 5 for y in range(16) for x in range(16)]
rows = ",\n".join(",".join(str(v) for v in g[y * 16:(y + 1) * 16]) for y in range(16))
return f' <chunk x="{cx}" y="{cy}" width="16" height="16">\n{rows}\n</chunk>'
# Tiled's canonical layout: chunks by row, the layer's size = the chunks' bounds
chunks = "\n".join(chunk(cx, cy) for cx, cy in ((16, -16), (-16, 0), (0, 0)))
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" orientation="orthogonal" renderorder="right-down" width="30" height="20" tilewidth="16" tileheight="16" infinite="1" nextlayerid="2" nextobjectid="1">
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
</tileset>
<layer id="1" name="chunks" width="48" height="32">
<data encoding="csv">
{chunks}
</data>
</layer>
</map>
"""
def tiled(ctx, argv, cwd):
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
if shutil.which("tiled"):
subprocess.run(["tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
else:
subprocess.run(["nix", "shell", "nixpkgs#tiled", "-c", "tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
def magick(ctx, argv):
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
def workdir(ctx, d):
magick(ctx, ["magick", "-size", "64x32", "gradient:red-blue", os.path.join(d, "tiles.png")])
magick(ctx, ["magick", "-size", "40x20", "xc:skyblue", os.path.join(d, "sky.png")])
open(os.path.join(d, "ext.tsx"), "w").write(TSX)
def run_ours(ctx, fmt):
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
luau = shutil.which("luau")
argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt]
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)
def gids(layer):
"""a JSON tile layer's gids (arrays, or base64 with compression) -> list"""
d = layer.get("data")
if isinstance(d, str):
raw = base64.b64decode(d)
c = layer.get("compression", "")
raw = zlib.decompress(raw) if c == "zlib" else gzip.decompress(raw) if c == "gzip" else raw
return list(struct.unpack("<%dI" % (len(raw) // 4), raw))
return d
IGNORE = {"version", "tiledversion", "compressionlevel", "encoding", "compression", "opacity_obj"}
DEFAULTS = {"offsetx": 0, "offsety": 0, "parallaxx": 1, "parallaxy": 1, "locked": False}
def norm(v, obj=False):
"""a JSON map without the fields that only say which Tiled wrote it, or that hold defaults"""
if isinstance(v, dict):
out = {}
if v.get("type") == "tilelayer" and "data" in v:
v = dict(v, data=gids(v))
for k, x in v.items():
if k in IGNORE or (k in DEFAULTS and x == DEFAULTS[k]) or (obj and k == "opacity"):
continue
out[k] = [norm(o, True) for o in x] if k == "objects" else norm(x)
return out
if isinstance(v, list):
return [norm(x) for x in v]
if isinstance(v, float) and v.is_integer():
return int(v)
return v
def diff(a, b, path="", out=None):
out = [] if out is None else out
if isinstance(a, dict) and isinstance(b, dict):
for k in sorted(set(a) | set(b)):
if k not in a or k not in b:
out.append("%s.%s: %s vs %s" % (path, k, a.get(k, "<missing>"), b.get(k, "<missing>")))
else:
diff(a[k], b[k], path + "." + k, out)
elif isinstance(a, list) and isinstance(b, list):
if len(a) != len(b):
out.append("%s: length %d vs %d" % (path, len(a), len(b)))
for i, (x, y) in enumerate(zip(a, b)):
diff(x, y, "%s[%d]" % (path, i), out)
elif a != b:
out.append("%s: %r vs %r" % (path, a, b))
return out
def generate(ctx):
cases = []
with tempfile.TemporaryDirectory() as d:
workdir(ctx, d)
for name, text in (("ortho", ortho()), ("hex", iso()), ("infinite", infinite())):
open(os.path.join(d, name + ".tmx"), "w").write(text)
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmj"], d)
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmx"], d)
cases.append({"name": name, "tmx": text, "tmj": open(os.path.join(d, name + "-out.tmj"), "rb").read(),
"tiled_tmx": open(os.path.join(d, name + "-out.tmx"), "rb").read()})
tiled(ctx, ["--export-tileset", "ext.tsx", "ext.tsj"], d)
tsj = open(os.path.join(d, "ext.tsj"), "rb").read()
ctx.emit("tiled", {"cases": cases, "tsx": TSX, "tsj": tsj})
# our encoder's files, read by Tiled
o = run_ours(ctx, "tiled")
open(os.path.join(d, "ours.tmx"), "wb").write(bytes.fromhex(o["tmx"]))
open(os.path.join(d, "ours.tmj"), "wb").write(bytes.fromhex(o["tmj"]))
tiled(ctx, ["--export-map", "ours.tmx", "ours-from-tmx.tmj"], d)
tiled(ctx, ["--export-map", "ours.tmj", "ours-from-tmj.tmj"], d)
mine = norm(json.loads(bytes.fromhex(o["tmj"])))
checks = []
for label, f in (("Tiled on our TMX", "ours-from-tmx.tmj"), ("Tiled on our TMJ", "ours-from-tmj.tmj")):
theirs = norm(json.load(open(os.path.join(d, f))))
dd = diff(mine, theirs)
checks.append({"label": label + (": " + "; ".join(dd[:5]) if dd else ""), "ok": not dd})
ctx.emit("tiled_ours", {"checks": checks})