Export Aseprite Tilemap

From F256 Foenix
Jump to navigationJump to search
This LUA script file needs to be placed in Aseprite's "scripts" folder.[edit | edit source]
-- export tilemap.lua
-- Copyright (C) 2022  Daniel Tremblay
--
-- This file is released under the terms of the MIT license.

local spr = app.activeSprite
local pc = app.pixelColor
if not spr then return print "No active sprite" end

if ColorMode.TILEMAP == nil then ColorMode.TILEMAP = 4 end
assert(ColorMode.TILEMAP == 4)

local output_folder = app.fs.filePath(spr.filename)

local function write_foenix_data(filename, data)
  local file = io.open(filename, "wb")
  local str = string.char(table.unpack(data))
  file:write(str)
  file:close()
end

local function export_cel(cel)
  local t = {
    frame=cel.frameNumber-1,
    bounds={ x=cel.bounds.x,
             y=cel.bounds.y,
             width=cel.bounds.width,
             height=cel.bounds.height }
  }

  if cel.image.colorMode == ColorMode.TILEMAP then
    local tilemap = cel.image
    -- save tilemap
    t.tilemap = { width=tilemap.width,
                  height=tilemap.height,
                  tiles={} }
    for it in tilemap:pixels() do
      table.insert(t.tilemap.tiles, pc.tileI(it()))
    end
  else
    -- save regular cel
    image_n = image_n + 1
    local imageFn = fs.joinPath(output_folder, "image" .. image_n .. ".png")
    cel.image:saveAs(imageFn)
    t.image = imageFn
  end

  fill_user_data(t, cel)
  return t
end


----------------------------------------------------------------------
-- Creates output folder
-- fs.makeDirectory(output_folder)  -- don't!!

----------------------------------------------------------------------
-- Write /sprite.json file in the output folder

local tilemapFile = app.fs.joinPath(output_folder, "tilemap.tlm")

local data = {}
-- add a tile because Vicky II requires it
table.insert(data,0)
table.insert(data,0)
-- iterate over each layer
for _,layer in ipairs(spr.layers) do
  -- iterate over each cel
  for _,cel in ipairs(layer.cels) do
    local tilemap = cel.image
    for it in tilemap:pixels() do
      table.insert(data, pc.tileI(it()))
      table.insert(data, 0)
    end
  end
  --data[y*grid.width*2 + x*2]=grid.tileIndex
end
    

    
--for i=1,1000 do data[i] = math.random(0,255) end

write_foenix_data(tilemapFile, data)