-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindowing.js
85 lines (70 loc) · 2.41 KB
/
windowing.js
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
"use strict";
var windowOpt = require("./lib/solvers/windowOpt");
var getSize = require("./lib/utils/getSize");
var getArea = require("./lib/utils/getArea");
var rotate = require("./lib/utils/rotate");
var unrotate = require("./lib/utils/unrotate");
var getTotalArea = require("./lib/utils/getTotalArea");
var rotateLayout = require("./lib/utils/rotateLayout");
var isSymmetric = require("./lib/utils/isSymmetric");
module.exports = function(rectangles, strategies, options){
options = options || {};
if(!options.silent){
console.log("Packing " + rectangles.length + " rectangles with " +
strategies.length + " strategies using the envelope-based algorithm.");
}
var depth = options.depth || 3,
finalDepth = options.finalDepth || depth;
var totalArea = getTotalArea(rectangles),
bestArea = Infinity, bestLayout = null, bestRectangles = null;
packing: {
strategies.some(function(produceScore, index){
if(!options.silent){
console.log("Trying strategy #" + (index + 1) + " ...");
}
var result = windowOpt(rectangles, produceScore, depth, finalDepth),
area = getArea(rectangles, result.layout);
if(!options.silent){
console.log("Wasted " + (area - totalArea) + " pixels.");
}
if(result.layout && area < bestArea){
bestArea = area;
bestLayout = result.layout;
bestRectangles = rectangles.slice(0);
}
return bestArea === totalArea;
});
if(bestArea === totalArea || options.suppressSymmetry || isSymmetric(rectangles)){
break packing;
}
if(!options.silent){
console.log("Trying a rotated solution.");
}
var rotatedRectangles = rotate(rectangles);
strategies.some(function(produceScore){
if(!options.silent){
console.log("Trying strategy #" + (index + 1) + " ...");
}
var result = windowOpt(rotatedRectangles, produceScore, depth, finalDepth),
area = getArea(rectangles, result.layout);
if(!options.silent){
console.log("Wasted " + (area - totalArea) + " pixels.");
}
if(result.layout && area < bestArea){
bestArea = area;
bestLayout = rotateLayout(result.layout);
bestRectangles = unrotate(rectangles);
}
return bestArea === totalArea;
});
}
if(!options.silent){
var waste = bestArea - totalArea;
if(waste){
console.log("The best solution wasted " + waste + " pixels.");
}else{
console.log("Found ideal solution.");
}
}
return {area: bestArea, layout: bestLayout, rectangles: bestRectangles};
};