Files
rosetta/src/Rosetta/image/gif/Decode.luau
T

62 lines
1.8 KiB
Luau

--!strict
--!native
--!optimize 2
-- image/gif/Decode: GIF frame pixels: palette indexes (plain or interlaced) to rgba8, drawn onto the canvas.
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local Decode = {}
-- interlace passes: every 8th row from 0, every 8th from 4, every 4th from 2, every 2nd from 1
local function interlacedRow(fh: number): { number }
local map = table.create(fh, 0)
local r = 0
for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do
local y = pass[1]
while y < fh do
map[y + 1] = r
r += 1
y += pass[2]
end
end
return map
end
function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer)
local rows = if interlaced then interlacedRow(fh) else nil
for y = 0, fh - 1 do
local src = (if rows then rows[y + 1] else y) * fw
local dst = y * fw * 4
for x = 0, fw - 1 do
writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4))
end
end
end
function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number)
local x0, y0 = math.max(0, fx), math.max(0, fy)
local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
for y = y0, y1 - 1 do
local s = ((y - fy) * fw - fx) * 4
local d = y * cw * 4
for x = x0, x1 - 1 do
local v = readu32(frame, s + x * 4)
if v >= 0x01000000 then
writeu32(canvas, d + x * 4, v)
end
end
end
end
function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number)
local x0, y0 = math.max(0, fx), math.max(0, fy)
local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
if x1 <= x0 then
return
end
for y = y0, y1 - 1 do
buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4)
end
end
return Decode