vec: layered/aseprite read + write (RGBA/gray/indexed, raw/zlib/linked cels, groups, blend, layer+cel opacity, palettes old+new, tags, user data); tests vs LibreSprite renders, LibreSprite reading our sprites, round trips; tools/fixtures/_ours.luau runs our encoders for the reference tools
This commit is contained in:
1 parent
e0629b12a3
commit
b76b2ec32d
6 files changed
+1185
No files matched your search
@@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|
||||
|---|---|---|---|---|---|---|
|
||||
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.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` |
|
||||
|
||||
@@ -26,6 +26,18 @@ local list: { Entry } = {
|
||||
return require("@formats/image/png")
|
||||
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",
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -87,6 +87,30 @@ local function psdDoc(): Types.Layered
|
||||
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
|
||||
|
||||
local which = ...
|
||||
if which == "psd" then
|
||||
local Psd = require("@formats/layered/psd")
|
||||
@@ -99,4 +123,13 @@ if which == "psd" then
|
||||
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 }))
|
||||
end
|
||||
@@ -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"]]})
|
||||
Reference in new issue
Block a user