Skip to content

Instantly share code, notes, and snippets.

@JomerDev
Last active May 14, 2016 13:31
Show Gist options
  • Save JomerDev/c213ce333fbc2828b09b079f7563cf61 to your computer and use it in GitHub Desktop.
Save JomerDev/c213ce333fbc2828b09b079f7563cf61 to your computer and use it in GitHub Desktop.
A packer for the bin packing problem
local packer = {}
function packer:new(w,h)
local new = setmetatable({},{__index = self})
new.x = 0
new.y = 0
new.w = w
new.h = h
return new
end
function packer:fit(blocks)
for id,block in pairs(blocks) do
local node = self.findNode( self, block.w or block[1], block.h or block[2])
if node then
blocks[id].fit = self.splitNode( node, block.w or block[1], block.h or block[2])
end
end
return blocks
end
function packer.findNode(root, w, h)
if root.used then
return packer.findNode(root.right, w, h) or packer.findNode( root.down, w, h)
elseif w <= root.w and h <= root.h then
return root
else
return nil
end
end
function packer.splitNode(node, w, h)
node.used = true
node.down = { x = node.x, y = node.y + h, w = node.w, h = node.h - h }
node.right = { x = node.x + w, y = node.y, w = node.w - w, h = h }
return node
end
return packer
local function splitNode(node, w, h)
node.used = true
node.down = { x = node.x, y = node.y + h, w = node.w, h = node.h - h }
node.right = { x = node.x + w, y = node.y, w = node.w - w, h = h }
return node
end
local function findNode(root, w, h)
if root.used then
return findNode(root.right, w, h) or findNode( root.down, w, h)
elseif w <= root.w and h <= root.h then
return root
else
return nil
end
end
function fit(w, h, blocks)
local root = {x = 0, y = 0, w = w, h = h }
for id,block in pairs(blocks) do
local node = findNode( root, block.w or block[1], block.h or block[2])
if node then
blocks[id].fit = splitNode( node, block.w or block[1], block.h or block[2])
end
end
return blocks
end
return fit
@JomerDev
Copy link
Author

JomerDev commented Apr 29, 2016

This: https://github.com/jakesgordon/bin-packing/ was used as an example

You probably should use the small packer.
Example:
`
local packer = require("packer")
local blocks = {
{10,10},
{5,5},
{2.5,5},
{2.5,5}
}

local textureWidth, textureHeight = 10,20

local results = packer(textureWidth, textureHeight, blocks)

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment