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
@@ -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
|
||||
Reference in new issue
Block a user