Files
rosetta/examples/layered.luau
T

56 lines
2.3 KiB
Luau

-- examples/layered.luau: build a layered document (a group, a clipping layer, a blend mode), flatten it, save it as
-- PSD and Aseprite, and make a small Aseprite animation exported as a GIF. Run from the repository root:
-- luau examples/layered.luau (docs/guide/layered.md explains the type).
local F = require("@formats")
local I, L = F.ops.image, F.Types.Layered
local function solid(w, h, r, g, b, a)
local img = assert(I.new(w, h))
I.fill(img, r, g, b, a)
return img
end
local doc = L.new(64, 64)
local shadow = L.layer("Shadow", solid(64, 64, 0, 0, 80, 255))
shadow.clip = true -- only where Card has alpha
shadow.blend = "multiply"
local card = L.layer("Card", solid(40, 40, 250, 200, 60, 255), 12, 12)
doc.layers = {
L.layer("Paper", solid(64, 64, 245, 245, 240, 255)), -- bottom
L.group("Art", { card, shadow }),
L.layer("Glass", solid(64, 20, 255, 255, 255, 255), 0, 0), -- top
}
doc.layers[3].opacity = 0.25
local flat = assert(F.ops.layers.flatten(doc))
print(string.format("flattened %dx%d, pixel (32, 40) = %d %d %d %d", flat.width, flat.height, I.getPixel(flat, 32, 40)))
for layer, depth in F.ops.layers.leaves(doc.layers) do
print(string.rep(" ", depth) .. layer.name .. " (" .. layer.blend .. ")")
end
-- save and reload in both layered formats
for _, fmt in { "psd", "aseprite" } do
local bytes = assert(F.save(doc, nil, { format = fmt }))
local back = assert(F.load(bytes))
assert(back.kind == "layered" and back.width == 64)
local again = assert(F.ops.layers.flatten(back))
local r1 = I.getPixel(again, 32, 40)
local r2 = I.getPixel(flat, 32, 40)
assert(math.abs(r1 - r2) <= 2)
print(string.format("%-8s %6d bytes, %d top-level layers", fmt, buffer.len(bytes), #back.layers))
end
-- an animation: a dot moving across four frames
local anim = L.new(16, 16)
local dot = solid(4, 4, 255, 60, 60, 255)
anim.frames = {}
for i = 1, 4 do
anim.frames[i] = { layers = { L.layer("Back", solid(16, 16, 20, 20, 30, 255)), L.layer("Dot", dot, i * 3 - 2, 6) }, delay = 0.15 }
end
anim.layers = anim.frames[1].layers
local ase = assert(F.save(anim, nil, { format = "aseprite" }))
local gifImage = assert(F.ops.layers.flattenFrames(assert(F.load(ase))))
local gif = assert(F.save(gifImage, nil, { format = "gif" }))
assert(I.frameCount(assert(F.load(gif))) == 4)
print("aseprite animation -> gif: 4 frames, " .. buffer.len(gif) .. " bytes")