Skip to content

Instantly share code, notes, and snippets.

@kevinmartinjos
Created April 16, 2015 18:06
Show Gist options
  • Save kevinmartinjos/ed88e5f39f7422fde7e6 to your computer and use it in GitHub Desktop.
Save kevinmartinjos/ed88e5f39f7422fde7e6 to your computer and use it in GitHub Desktop.
Draft, rectangle packing algorithm
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);
}
@kevinmartinjos
Copy link
Author

Incomplete. Will be working on this.

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