aboutsummaryrefslogtreecommitdiff
path: root/src/textures.lua
blob: 9ed789cf3549defe485d0cc966e88d7c162b4a75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
require "string"
local load_ase_data = require "src.lovease"

local default_anim = {
  frame_count = 1,
  default_tag = "default",
  tags = {
    default = {from=1, to=1, duration=1},
  },
}

local img_bank = {}
local img_data_bank = {}
local anim_bank = {}

local function load_ase(path)
  local ase = load_ase_data(path)

  local width = ase.header.width
  local height = ase.header.height

  local frames = {}
  local tags = {}
  local default_tag

  for _, frame in ipairs(ase.header.frames) do
    for _, chunk in ipairs(frame.chunks) do
      if chunk.type == 0x2005 then
        local cel = chunk.data
        local buf = love.data.decompress("data", "zlib", cel.data)
        local data = love.image.newImageData(cel.width, cel.height, "rgba8", buf)
        local img = lg.newImage(data)
        table.insert(frames, {img=img, x=cel.x, y=cel.y})
      elseif chunk.type == 0x2018 then
        for i, tag in ipairs(chunk.data.tags) do
          if i == 1 then
            default_tag = tag.name
          end

          tags[tag.name] = {
            from = tag.from + 1,
            to = tag.to + 1,
            -- this is placed wrong but idc
            duration = (tag.frame_duration or 100) / 1000,
          }
        end
      end
    end
  end

  local sheet = lg.newCanvas(width * #frames, height)
  lg.setCanvas(sheet)
  for i, frame in ipairs(frames) do
    lg.draw(frame.img, (i - 1) * width + frame.x, frame.y)
  end
  lg.setCanvas()

  img_bank[path] = sheet
  anim_bank[path] = {
    frame_count = #frames,
    default_tag = default_tag,
    tags = tags,
  }
end

function load_textures_from(path)
  path = path or "res/img"
  local files = lf.getDirectoryItems(path)

  for _, file in ipairs(files) do
    local filepath = path.."/"..file

    if lf.getInfo(filepath).type == "directory" then
      load_textures_from(filepath)
    else
      if is_filetype(filepath, {"png"}) then
        local data = li.newImageData(filepath)
        img_data_bank[filepath] = data
        img_bank[filepath] = lg.newImage(data)
      elseif filepath:match("%.ase$") then
        load_ase(filepath)
      end
    end
  end
end

function get_tex(name)
  return img_bank[name]
end

function get_tex_data(name)
  return img_data_bank[name]
end

function get_anim(name)
  return anim_bank[name] or default_anim
end