Created
April 16, 2015 18:06
-
-
Save kevinmartinjos/ed88e5f39f7422fde7e6 to your computer and use it in GitHub Desktop.
Draft, rectangle packing algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Globals = { | |
originX: 0, | |
originY: 0, | |
rectangles: [] | |
}; | |
function Packer(ratio, w_, h_){ | |
this.ratio = ratio; | |
this.width = w_; | |
this.height = h_; | |
this.blocks = []; | |
this.addBlock = function addBlock(block){ | |
this.blocks.push(block); | |
} | |
this.sortByArea = function(blocks){ | |
//bubble sorting the rectangles by area | |
for(var i=0; i<blocks.length; i++){ | |
for(var j=0; j<blocks.length - 1; j++){ | |
var area1 = blocks[j].width * blocks[j].height; | |
var area2 = blocks[j+1].width * blocks[j+1].height; | |
if(area1 < area2){ | |
var temp = blocks[j]; | |
blocks[j] = blocks[j+1]; | |
blocks[j+1] = temp; | |
} | |
} | |
} | |
} | |
//Initially, the only block in the packer | |
//is one large unoccuppied rectangle | |
this.addBlock(new PackerBlock(w_, h_)); | |
} | |
function PackerBlock(w_, h_){ | |
this.originX = 0; | |
this.originY = 0; | |
this.width = w_; | |
this.height = h_; | |
this.free = true; | |
} | |
function pack(ratio, rectangles){ | |
//creating a packer that considers the whole sketch canvas | |
var packer = new Packer(ratio, width, height); | |
packer.sortByArea(rectangles); | |
rectangles[0].originX = 0; | |
rectangles[0].originY = 0; | |
} | |
function Rectangle(x0, y0, w_, h_){ | |
this.width = w_; | |
this.height = h_; | |
this.originX = x0; | |
this.originY = y0; | |
} | |
function addRectangle(x, y, w_, h_){ | |
var rectangle = new Rectangle(x, y, w_, h_); | |
Globals.rectangles.push(rectangle); | |
} | |
function drawRectangles(){ | |
for(var i=0; i<Globals.rectangles.length; i++){ | |
var r = Globals.rectangles[i]; | |
rect(r.originX, r.originY, r.width, r.height); | |
} | |
} | |
function setup(){ | |
createCanvas(720, 480); | |
frameRate(30); | |
rectMode(CORNER); | |
} | |
function draw(){ | |
background(192); | |
drawRectangles(); | |
//draw rectangle when dragging | |
if(mouseIsPressed){ | |
rect(Globals.originX, Globals.originY, abs(Globals.originX-mouseX), abs(Globals.originY-mouseY)); | |
} | |
} | |
function mousePressed(){ | |
Globals.originX = mouseX; | |
Globals.originY = mouseY; | |
} | |
function mouseReleased(){ | |
addRectangle(Globals.originX, Globals.originY, abs(Globals.originX-mouseX), abs(Globals.originY-mouseY)); | |
pack(1, Globals.rectangles); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Incomplete. Will be working on this.