-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimagetable.lua
97 lines (79 loc) · 2.5 KB
/
imagetable.lua
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
local module = {}
playdate.graphics.imagetable = module
local meta = {}
meta.__index = meta
module.__index = meta
function module.new(path)
local imagetable = setmetatable({}, meta)
local folder = ""
local pattern = path.."-table-"
-- no findLast() so reverse string first
local start, ends = string.find(string.reverse(path), "/")
if start and ends then
folder = string.sub(path, 1, #path - ends)
pattern = string.sub(path, #path - ends + 2).."-table-"
end
-- escape dashes
pattern = string.gsub(pattern, "%-", "%%%-")
-- TODO: escape other magic chars?
-- TODO: support about a sequence of files (image1.png, image2.png, etc)
local actualFilename = ""
local files = love.filesystem.getDirectoryItems(folder)
for i = 1, #files, 1 do
local f = files[i]
local s, e = string.find(f, pattern)
if s and e then
-- file found, remove extension
actualFilename = string.sub(f, 1, #f - 4)
break
end
end
-- parse frame width and height out of filename
local matches = string.gmatch(actualFilename, "%-(%d+)")
local frameWidth = tonumber(matches())
local frameHeight = tonumber(matches())
local actualPath = folder.."/"..actualFilename
-- load atlas
local atlas = love.image.newImageData(actualPath..".png")
-- create a separate image for each frame
local w = atlas:getWidth()
local h = atlas:getHeight()
local rows = h / frameHeight
local columns = w / frameWidth
local images = {}
for r = 0, rows - 1, 1 do
for c = 0, columns - 1, 1 do
local imageData = love.image.newImageData(frameWidth, frameHeight)
for x = 0, frameWidth - 1, 1 do
for y = 0, frameHeight - 1, 1 do
local r, g, b, a = atlas:getPixel(x + (c * frameWidth), y + (r * frameHeight))
imageData:setPixel(x, y, r, g, b, a)
end
end
local image = playdate.graphics.image.new(frameWidth, frameHeight)
image.data:replacePixels(imageData)
table.insert(images, image)
end
end
imagetable.length = rows * columns
imagetable._images = images
imagetable._width = w
imagetable._height = h
imagetable._rows = rows
imagetable._columns = columns
imagetable._frameWidth = frameWidth
imagetable._frameHeight = frameHeight
return imagetable
end
function meta:drawImage(n, x, y, flip)
self._images[n]:draw(x, y, flip)
end
function meta:getImage(n)
return self._images[n]
end
function meta:getLength()
return self.length
end
function meta:getSize()
return self._rows, self._columns
end