rectpackbin 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,578 @@
1
+ const { GuillotineBssfSas } = require('./guillotine');
2
+ // Helper function to convert float to decimal with specified precision
3
+ function float2dec(ft, decimalDigits) {
4
+ return Number(Math.ceil(ft * Math.pow(10, decimalDigits)) / Math.pow(10, decimalDigits));
5
+ }
6
+
7
+ // Sorting algorithms for rectangle lists
8
+ const SORT_AREA = (rectList) => [...rectList].sort((a, b) => (b[0] * b[1]) - (a[0] * a[1]));
9
+ const SORT_PERI = (rectList) => [...rectList].sort((a, b) => (b[0] + b[1]) - (a[0] + a[1]));
10
+ const SORT_DIFF = (rectList) => [...rectList].sort((a, b) => Math.abs(b[0] - b[1]) - Math.abs(a[0] - a[1]));
11
+ const SORT_SSIDE = (rectList) => [...rectList].sort((a, b) => {
12
+ const [minA, maxA] = [Math.min(a[0], a[1]), Math.max(a[0], a[1])];
13
+ const [minB, maxB] = [Math.min(b[0], b[1]), Math.max(b[0], b[1])];
14
+ return minB - minA || maxB - maxA;
15
+ });
16
+ const SORT_LSIDE = (rectList) => [...rectList].sort((a, b) => {
17
+ const [maxA, minA] = [Math.max(a[0], a[1]), Math.min(a[0], a[1])];
18
+ const [maxB, minB] = [Math.max(b[0], b[1]), Math.min(b[0], b[1])];
19
+ return maxB - maxA || minB - minA;
20
+ });
21
+ const SORT_RATIO = (rectList) => [...rectList].sort((a, b) => (b[0] / b[1]) - (a[0] / a[1]));
22
+ const SORT_NONE = (rectList) => [...rectList];
23
+ const PackingMode = {
24
+ Online: 0,
25
+ Offline: 1,
26
+ properties: {
27
+ 0: { name: "Online" },
28
+ 1: { name: "Offline" }
29
+ }
30
+ };
31
+
32
+ const PackingBin = {
33
+ BNF: 0, // Bin Next Fit
34
+ BFF: 1, // Bin First Fit
35
+ BBF: 2, // Bin Best Fit
36
+ Global: 3, // Global Fit
37
+ properties: {
38
+ 0: { name: "BNF" },
39
+ 1: { name: "BFF" },
40
+ 2: { name: "BBF" },
41
+ 3: { name: "Global" }
42
+ }
43
+ };
44
+
45
+ class BinFactory {
46
+ constructor(width, height, count, packAlgo, ...args) {
47
+ this._width = width;
48
+ this._height = height;
49
+ this._count = count;
50
+ this._packAlgo = packAlgo;
51
+ this._algoArgs = args;
52
+ this._refBin = null; // Reference bin used to calculate fitness
53
+ }
54
+
55
+ _createBin() {
56
+ return new this._packAlgo(this._width, this._height, ...this._algoArgs);
57
+ }
58
+
59
+ isEmpty() {
60
+ return this._count < 1;
61
+ }
62
+
63
+ fitness(width, height) {
64
+ if (!this._refBin) {
65
+ this._refBin = this._createBin();
66
+ }
67
+ return this._refBin.fitness(width, height);
68
+ }
69
+
70
+ fitsInside(width, height) {
71
+ if (!this._refBin) {
72
+ this._refBin = this._createBin();
73
+ }
74
+ return this._refBin._fitsSurface(width, height);
75
+ }
76
+
77
+ newBin() {
78
+ if (this._count > 0) {
79
+ this._count--;
80
+ return this._createBin();
81
+ }
82
+ return null;
83
+ }
84
+ }
85
+
86
+ class PackerOnline {
87
+ constructor({packAlgo = GuillotineBssfSas, rotation = true}) {
88
+ this._rotation = rotation;
89
+ this._packAlgo = packAlgo;
90
+ this.reset();
91
+ }
92
+
93
+ *[Symbol.iterator]() {
94
+ yield* [...this._closedBins, ...this._openBins];
95
+ }
96
+
97
+ get length() {
98
+ return this._closedBins.length + this._openBins.length;
99
+ }
100
+
101
+ _newOpenBin(width = null, height = null, rid = null) {
102
+ const factoriesToDelete = new Set();
103
+ let newBin = null;
104
+
105
+ for (const [key, binFac] of Object.entries(this._emptyBins)) {
106
+ if (!binFac.fitsInside(width, height)) continue;
107
+
108
+ newBin = binFac.newBin();
109
+ if (!newBin) continue;
110
+
111
+ this._openBins.push(newBin);
112
+
113
+ if (binFac.isEmpty()) {
114
+ factoriesToDelete.add(key);
115
+ }
116
+ break;
117
+ }
118
+
119
+ factoriesToDelete.forEach(f => delete this._emptyBins[f]);
120
+ return newBin;
121
+ }
122
+
123
+ addBin(width, height, count = 1, options = {}) {
124
+ options.rot = this._rotation;
125
+ const binFactory = new BinFactory(width, height, count, this._packAlgo, options);
126
+ this._emptyBins[this._binCount++] = binFactory;
127
+ }
128
+
129
+ rectList() {
130
+ const rectangles = [];
131
+ let binCount = 0;
132
+
133
+ for (const bin of this) {
134
+ for (const rect of bin) {
135
+ rectangles.push([binCount, rect.x, rect.y, rect.width, rect.height, rect.rid]);
136
+ }
137
+ binCount++;
138
+ }
139
+
140
+ return rectangles;
141
+ }
142
+
143
+ binList() {
144
+ return [...this].map(b => [b.width, b.height]);
145
+ }
146
+
147
+ validatePacking() {
148
+ for (const b of this) {
149
+ b.validatePacking();
150
+ }
151
+ }
152
+
153
+ reset() {
154
+ this._closedBins = [];
155
+ this._openBins = [];
156
+ this._emptyBins = new Map();
157
+ this._binCount = 0;
158
+ }
159
+ }
160
+
161
+
162
+ const PackerMixin = Base => class extends Base {
163
+ /**
164
+ * Rectangles aren't packed until pack() is called
165
+ */
166
+ constructor({packAlgo = GuillotineBssfSas, sortAlgo = SORT_NONE, rotation = true} = {} ) {
167
+ super({packAlgo, rotation});
168
+
169
+ this._sortAlgo = sortAlgo;
170
+
171
+ // User provided bins and Rectangles
172
+ this._availBins = [];
173
+ this._availRect = [];
174
+
175
+ // Aux vars used during packing
176
+ this._sortedRect = [];
177
+ }
178
+
179
+ addBin(width, height, count = 1, options = {}) {
180
+ this._availBins.push([width, height, count, options]);
181
+ }
182
+
183
+ addRect(width, height, rid = null) {
184
+ this._availRect.push([width, height, rid]);
185
+ }
186
+ addRectOffline(width, height, rid = null) {
187
+ this._availRect.push([width, height, rid]);
188
+ }
189
+
190
+ _isEverythingReady() {
191
+ return this._availRect.length > 0 && this._availBins.length > 0;
192
+ }
193
+
194
+ pack() {
195
+ this.reset();
196
+
197
+ if (!this._isEverythingReady()) {
198
+ // maybe we should throw an error here?
199
+ return;
200
+ }
201
+
202
+ // Add available bins to packer
203
+ for (let i = 0; i < this._availBins.length; i++) {
204
+ const [width, height, count, extraOptions] = this._availBins[i];
205
+ super.addBin(width, height, count, extraOptions);
206
+ }
207
+
208
+ // If enabled sort rectangles
209
+ this._sortedRect = this._sortAlgo(this._availRect);
210
+
211
+ // Start packing
212
+ for (const r of this._sortedRect) {
213
+ super.addRect(...r);
214
+ }
215
+ }
216
+ }
217
+
218
+ const PackerOnlineBase = PackerMixin(PackerOnline);
219
+ class Packer extends PackerOnlineBase {
220
+ constructor(...args) {
221
+ super(...args);
222
+ }
223
+ }
224
+
225
+ const PackerBNFMixin = Base => class extends Base {
226
+ constructor(...args) {
227
+ super(...args);
228
+ }
229
+
230
+ addRect(width, height, rid = null) {
231
+ while (true) {
232
+ if (this._openBins.length === 0) {
233
+ const newBin = this._newOpenBin(width, height, rid);
234
+ if (!newBin) return null;
235
+ }
236
+
237
+ const rect = this._openBins[0].addRect(width, height, rid);
238
+ if (rect) return rect;
239
+
240
+ const closedBin = this._openBins.shift();
241
+ this._closedBins.push(closedBin);
242
+ }
243
+ }
244
+ };
245
+
246
+ const PackerBFFMixin = Base => class extends Base {
247
+ constructor(...args) {
248
+ super(...args);
249
+ }
250
+
251
+ addRect(width, height, rid = null) {
252
+ for (const bin of this._openBins) {
253
+ const rect = bin.addRect(width, height, rid);
254
+ if (rect) return rect;
255
+ }
256
+
257
+ while (true) {
258
+ const newBin = this._newOpenBin(width, height, rid);
259
+ if (!newBin) return null;
260
+
261
+ const rect = newBin.addRect(width, height, rid);
262
+ if (rect) return rect;
263
+ }
264
+ }
265
+ }
266
+ // Enum implementation
267
+
268
+ const PackerBBFMixin = Base => class extends Base {
269
+ constructor(...args) {
270
+ super(...args);
271
+ }
272
+
273
+ addRect(width, height, rid = null) {
274
+ // Try packing into open bins
275
+ const fitBins = this._openBins
276
+ .map(b => [b.fitness(width, height), b])
277
+ .filter(([fitness]) => fitness !== null);
278
+
279
+ if (fitBins.length > 0) {
280
+ const [_, bestBin] = fitBins.reduce((min, curr) =>
281
+ curr[0] < min[0] ? curr : min
282
+ );
283
+ bestBin.addRect(width, height, rid);
284
+ return true;
285
+ }
286
+
287
+ // Try packing into empty bins
288
+ while (true) {
289
+ const newBin = this._newOpenBin(width, height, rid);
290
+ if (!newBin) return false;
291
+
292
+ if ( newBin.addRect(width, height, rid)) {
293
+ return true;
294
+ }
295
+ }
296
+ }
297
+ };
298
+
299
+
300
+
301
+
302
+
303
+ const PackerBNFBase = PackerMixin(PackerBNFMixin(PackerOnline));
304
+ class PackerBNF extends PackerBNFBase {
305
+ constructor(...args) {
306
+ super(...args);
307
+ }
308
+ }
309
+
310
+
311
+ const PackerBFFBase = PackerMixin(PackerBFFMixin(PackerOnline));
312
+ class PackerBFF extends PackerBFFBase {
313
+ constructor(...args) {
314
+ super(...args);
315
+ }
316
+ }
317
+
318
+
319
+
320
+ const PackerBBFBase = PackerMixin(PackerBBFMixin(PackerOnline));
321
+ class PackerBBF extends PackerBBFBase {
322
+ constructor(...args) {
323
+ super(...args);
324
+ }
325
+ }
326
+
327
+
328
+
329
+
330
+ const PackerOnlineBNFBase = PackerBNFMixin(PackerOnline);
331
+ class PackerOnlineBNF extends PackerOnlineBNFBase {
332
+ constructor(...args) {
333
+ super(...args);
334
+ }
335
+ }
336
+
337
+ const PackerOnlineBFFBase = PackerBFFMixin(PackerOnline);
338
+ class PackerOnlineBFF extends PackerOnlineBFFBase {
339
+ constructor(...args) {
340
+ super(...args);
341
+ }
342
+ }
343
+
344
+
345
+ const PackerOnlineBBFBase = PackerBBFMixin(PackerOnline);
346
+ class PackerOnlineBBF extends PackerOnlineBBFBase {
347
+ constructor(...args) {
348
+ super(...args);
349
+ }
350
+ }
351
+
352
+
353
+ const PackerGlobalBase = PackerBNFMixin(Packer);
354
+ class PackerGlobal extends PackerGlobalBase {
355
+ /**
356
+ * GLOBAL: For each bin pack the rectangle with the best fitness.
357
+ */
358
+ constructor({ packAlgo = GuillotineBssfSas, rotation = true } = {}) {
359
+ super({ packAlgo, sortAlgo: SORT_NONE, rotation });
360
+ }
361
+
362
+ _findBestFit(pbin) {
363
+ /**
364
+ * Return best fitness rectangle from rectangles packing _sortedRect list
365
+ *
366
+ * @param {PackingAlgorithm} pbin - Packing bin
367
+ * @returns {number|null} key of the rectangle with best fitness
368
+ */
369
+ const fit = Object.entries(this._sortedRect)
370
+ .map(([k, r]) => [pbin.fitness(r[0], r[1]), k])
371
+ .filter(([fitness]) => fitness !== null);
372
+
373
+ if (fit.length === 0) return null;
374
+
375
+ const [_, rect] = fit.reduce((min, curr) =>
376
+ curr[0] < min[0] ? curr : min
377
+ );
378
+ return rect;
379
+ }
380
+
381
+ _newOpenBin(remainingRect) {
382
+ /**
383
+ * Extract the next bin where at least one of the rectangles in
384
+ * remainingRect fits
385
+ *
386
+ * @param {Object} remainingRect - rectangles not placed yet
387
+ * @returns {PackingAlgorithm|null} Initialized empty packing bin or null if no bin found
388
+ */
389
+ const factoriesToDelete = new Set();
390
+ let newBin = null;
391
+
392
+ for (const [key, binFac] of Object.entries(this._emptyBins)) {
393
+ // Only return the new bin if at least one of the remaining
394
+ // rectangles fit inside.
395
+ let aRectangleFits = false;
396
+ for (const rect of Object.values(remainingRect)) {
397
+ if (binFac.fitsInside(rect[0], rect[1])) {
398
+ aRectangleFits = true;
399
+ break;
400
+ }
401
+ }
402
+
403
+ if (!aRectangleFits) {
404
+ factoriesToDelete.add(key);
405
+ continue;
406
+ }
407
+
408
+ // Create bin and add to openBins
409
+ newBin = binFac.newBin();
410
+ if (!newBin) continue;
411
+ this._openBins.push(newBin);
412
+
413
+ // If the factory was depleted mark for deletion
414
+ if (binFac.isEmpty()) {
415
+ factoriesToDelete.add(key);
416
+ }
417
+
418
+ break;
419
+ }
420
+
421
+ // Delete marked factories
422
+ for (const f of factoriesToDelete) {
423
+ delete this._emptyBins[f];
424
+ }
425
+
426
+ return newBin;
427
+ }
428
+
429
+ pack() {
430
+ this.reset();
431
+
432
+ if (!this._isEverythingReady()) {
433
+ return;
434
+ }
435
+
436
+ // Add available bins to packer
437
+ // for (const b of this._availBins) {
438
+ // const [width, height, count, extraOptions] = b;
439
+ // super.addBin(width, height, count, extraOptions);
440
+ // }
441
+
442
+ // Store rectangles into dict for fast deletion
443
+ this._sortedRect = Object.fromEntries(
444
+ this._sortAlgo(this._availRect).map((r, i) => [i, r])
445
+ );
446
+
447
+ // For each bin pack the rectangles with lowest fitness until it is filled or
448
+ // the rectangles exhausted, then open the next bin where at least one rectangle
449
+ // will fit and repeat the process until there aren't more rectangles or bins
450
+ // available.
451
+ while (Object.keys(this._sortedRect).length > 0) {
452
+ // Find one bin where at least one of the remaining rectangles fit
453
+ const pbin = this._newOpenBin(this._sortedRect);
454
+ if (!pbin) break;
455
+
456
+ // Pack as many rectangles as possible into the open bin
457
+ while (true) {
458
+ // Find 'fittest' rectangle
459
+ const bestRectKey = this._findBestFit(pbin);
460
+ if (!bestRectKey) {
461
+ const closedBin = this._openBins.shift();
462
+ this._closedBins.push(closedBin);
463
+ break; // None of the remaining rectangles can be packed in this bin
464
+ }
465
+
466
+ const bestRect = this._sortedRect[bestRectKey];
467
+ delete this._sortedRect[bestRectKey];
468
+
469
+ PackerBNFMixin.prototype.addRect.call(this, ...bestRect);
470
+ }
471
+ }
472
+ }
473
+
474
+ }
475
+
476
+
477
+ /**
478
+ * Packer factory helper function
479
+ * @param {PackingMode} mode - Packing mode (Online or Offline)
480
+ * @param {PackingBin} binAlgo - Bin selection heuristic
481
+ * @param {Function} packAlgo - Algorithm used (default: GuillotineBssfSas)
482
+ * @param {Function} sortAlgo - Sorting algorithm (default: SORT_AREA)
483
+ * @param {boolean} rotation - Enable or disable rectangle rotation
484
+ * @returns {Packer} Initialized packer instance
485
+ */
486
+ function newPacker({
487
+ mode = PackingMode.Offline,
488
+ binAlgo = PackingBin.BBF,
489
+ packAlgo = GuillotineBssfSas,
490
+ sortAlgo = SORT_AREA,
491
+ rotation = true
492
+ }={}) {
493
+ let packerClass = null;
494
+
495
+ // Online Mode
496
+ if (mode === PackingMode.Online) {
497
+ sortAlgo = null;
498
+ switch (binAlgo) {
499
+ case PackingBin.BNF:
500
+ packerClass = PackerOnlineBNF;
501
+ break;
502
+ case PackingBin.BFF:
503
+ packerClass = PackerOnlineBFF;
504
+ break;
505
+ case PackingBin.BBF:
506
+ packerClass = PackerOnlineBBF;
507
+ break;
508
+ default:
509
+ throw new Error("Unsupported bin selection heuristic");
510
+ }
511
+ }
512
+ // Offline Mode
513
+ else if (mode === PackingMode.Offline) {
514
+ switch (binAlgo) {
515
+ case PackingBin.BNF:
516
+ packerClass = PackerBNF;
517
+ break;
518
+ case PackingBin.BFF:
519
+ packerClass = PackerBFF;
520
+ break;
521
+ case PackingBin.BBF:
522
+ packerClass = PackerBBF;
523
+ break;
524
+ case PackingBin.Global:
525
+ packerClass = PackerGlobal;
526
+ sortAlgo = null;
527
+ break;
528
+ default:
529
+ throw new Error("Unsupported bin selection heuristic");
530
+ }
531
+ }
532
+ else {
533
+ throw new Error("Unknown packing mode");
534
+ }
535
+
536
+ // Create and return the appropriate packer instance
537
+ if (sortAlgo) {
538
+ return new packerClass({
539
+ packAlgo,
540
+ sortAlgo,
541
+ rotation
542
+ });
543
+ } else {
544
+ return new packerClass({
545
+ packAlgo,
546
+ rotation
547
+ });
548
+ }
549
+ }
550
+
551
+ // Export the classes and sorting functions
552
+ module.exports = {
553
+ float2dec,
554
+ SORT_AREA,
555
+ SORT_PERI,
556
+ SORT_DIFF,
557
+ SORT_SSIDE,
558
+ SORT_LSIDE,
559
+ SORT_RATIO,
560
+ SORT_NONE,
561
+ BinFactory,
562
+ PackerBNFMixin,
563
+ PackerBFFMixin,
564
+ PackerBBFMixin,
565
+ PackerOnline,
566
+ Packer,
567
+ PackerBNF,
568
+ PackerBFF,
569
+ PackerBBF,
570
+ PackerOnlineBNF,
571
+ PackerOnlineBFF,
572
+ PackerOnlineBBF,
573
+ PackerGlobal,
574
+ PackingMode,
575
+ PackingBin,
576
+ newPacker
577
+ };
578
+
@@ -0,0 +1,144 @@
1
+ class PackerBBFStandalone {
2
+ constructor({ packAlgo = GuillotineBssfSas, sortAlgo = SORT_NONE, rotation = true } = {}) {
3
+ this._rotation = rotation;
4
+ this._packAlgo = packAlgo;
5
+ this._sortAlgo = sortAlgo;
6
+
7
+ // User provided bins and Rectangles
8
+ this._availBins = [];
9
+ this._availRect = [];
10
+
11
+ // Aux vars used during packing
12
+ this._sortedRect = [];
13
+
14
+ this.reset();
15
+ }
16
+
17
+ *[Symbol.iterator]() {
18
+ yield* [...this._closedBins, ...this._openBins];
19
+ }
20
+
21
+ get length() {
22
+ return this._closedBins.length + this._openBins.length;
23
+ }
24
+
25
+ reset() {
26
+ this._closedBins = [];
27
+ this._openBins = [];
28
+ this._emptyBins = new Map();
29
+ this._binCount = 0;
30
+ }
31
+
32
+ _newOpenBin(width = null, height = null, rid = null) {
33
+ const factoriesToDelete = new Set();
34
+ let newBin = null;
35
+
36
+ for (const [key, binFac] of Object.entries(this._emptyBins)) {
37
+ if (!binFac.fitsInside(width, height)) continue;
38
+
39
+ newBin = binFac.newBin();
40
+ if (!newBin) continue;
41
+
42
+ this._openBins.push(newBin);
43
+
44
+ if (binFac.isEmpty()) {
45
+ factoriesToDelete.add(key);
46
+ }
47
+ break;
48
+ }
49
+
50
+ factoriesToDelete.forEach(f => delete this._emptyBins[f]);
51
+ return newBin;
52
+ }
53
+
54
+ addBin(width, height, count = 1, options = {}) {
55
+ // For initial bin setup
56
+ this._availBins.push([width, height, count, options]);
57
+
58
+ // For runtime bin management
59
+ options.rot = this._rotation;
60
+ const binFactory = new BinFactory(width, height, count, this._packAlgo, options);
61
+ this._emptyBins[this._binCount++] = binFactory;
62
+ }
63
+
64
+ addRect(width, height, rid = null) {
65
+ // For initial rectangle setup
66
+ this._availRect.push([width, height, rid]);
67
+ }
68
+
69
+ _addRectRuntime(width, height, rid = null) {
70
+ // Try packing into open bins
71
+ const fitBins = this._openBins
72
+ .map(b => [b.fitness(width, height), b])
73
+ .filter(([fitness]) => fitness !== null);
74
+
75
+ if (fitBins.length > 0) {
76
+ const [_, bestBin] = fitBins.reduce((min, curr) =>
77
+ curr[0] < min[0] ? curr : min
78
+ );
79
+ return bestBin.addRect(width, height, rid);
80
+ }
81
+
82
+ // Try packing into empty bins
83
+ while (true) {
84
+ const newBin = this._newOpenBin(width, height, rid);
85
+ if (!newBin) return null;
86
+
87
+ if ( newBin.addRect(width, height, rid)) {
88
+ return true;
89
+ }
90
+ }
91
+ }
92
+
93
+ rectList() {
94
+ const rectangles = [];
95
+ let binCount = 0;
96
+
97
+ for (const bin of this) {
98
+ for (const rect of bin) {
99
+ rectangles.push([binCount, rect.x, rect.y, rect.width, rect.height, rect.rid]);
100
+ }
101
+ binCount++;
102
+ }
103
+
104
+ return rectangles;
105
+ }
106
+
107
+ binList() {
108
+ return [...this].map(b => [b.width, b.height]);
109
+ }
110
+
111
+ validatePacking() {
112
+ for (const b of this) {
113
+ b.validatePacking();
114
+ }
115
+ }
116
+
117
+ _isEverythingReady() {
118
+ return this._availRect.length > 0 && this._availBins.length > 0;
119
+ }
120
+
121
+ pack() {
122
+ this.reset();
123
+
124
+ if (!this._isEverythingReady()) {
125
+ return;
126
+ }
127
+
128
+ // Add available bins to packer
129
+ for (const b of this._availBins) {
130
+ const [width, height, count, extraOptions] = b;
131
+ this.addBin(width, height, count, extraOptions);
132
+ }
133
+
134
+ // If enabled sort rectangles
135
+ this._sortedRect = this._sortAlgo(this._availRect);
136
+
137
+ // Start packing
138
+ for (const r of this._sortedRect) {
139
+ this._addRectRuntime(...r);
140
+ }
141
+ }
142
+ }
143
+
144
+ export { PackerBBF as PackerBBFStandalone };