I'm working on a game engine, that loads assets from a map format (Gleed2d). Let's say there are 5 identical trees, then the engine will load 'res/tree.png' as an image for each game object.
Doing this using love.graphics.newImage('res/tree.png') will take up 5x the memory, as love loads each asset as a new texture.
...
Obviously not the smart way to go. To make the engine share already loaded assets, I created a texture manager:
Pretty straightforward.
Code: Select all
local textureMngr = sclass()
function textureMngr:init()
self.textures = {}
end
function textureMngr:load(filename)
if not self.textures[filename] then self.textures[filename] = love.graphics.newImage(filename) end
return self.textures[filename]
end
function textureMngr:getFilename(texture)
for i,v in pairs(self.textures) do
if texture == v then return i end
end
end
function textureMngr:delete(id)
if type(id) == "string" then
self.texture[id] = nil
else
self.texture[self:getFilename(id)] = nil
end
end
texture = textureMngr()
But there's one downside of this. Since all the image object are stored in the texture managers table, they don't get collected by luas garbage collection when no other game instance is pointing to it, since it's still accessible through the texture manager.
So if I want to load another map, I'm either stuck with all the old images still in memory or manually have to delete them.
Is there some way to determine if no other table except the index in the image manager is pointing to the image userdata object.