@mark1russell7/packing 0.1.2 → 0.1.3
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.
- package/README.md +32 -0
- package/build/index.d.ts +338 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +986 -2
- package/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/adapters.ts +261 -0
- package/src/check.ts +84 -0
- package/src/contract.ts +203 -0
- package/src/convert.ts +51 -0
- package/src/frame.ts +262 -0
- package/src/index.ts +41 -0
- package/src/pack.ts +2 -1
- package/src/registry.ts +23 -0
- package/src/strategy.ts +214 -0
package/src/frame.ts
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
// The internal frame of the adapters of 0.1: the conversion of a PackInput to the Rect objects of 0.1, and back.
|
|
2
|
+
// Each item grows by its margin and by half the gap on each side. Each obstacle grows by half the gap. Thus two items
|
|
3
|
+
// are `mA + gap + mB` apart. The area of the frame is the container less the inset, grown by half the gap on each side.
|
|
4
|
+
|
|
5
|
+
import { EPS, marginOf, type Item, type Obstacle, type PackInput, type PackOutput, type Placement, type Region, type StageTrace } from "./contract.ts";
|
|
6
|
+
import { Rect } from "./rect.ts";
|
|
7
|
+
|
|
8
|
+
const clock = (globalThis as { performance?: { now(): number } }).performance;
|
|
9
|
+
|
|
10
|
+
/** This function gives the time in milliseconds. */
|
|
11
|
+
export function now(): number {
|
|
12
|
+
return clock ? clock.now() : Date.now();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** This function gives the bounding box of a region. */
|
|
16
|
+
export function boundsOf(region: Region): { x: number; y: number; w: number; h: number } {
|
|
17
|
+
switch (region.kind) {
|
|
18
|
+
case "rect":
|
|
19
|
+
return { x: region.x, y: region.y, w: region.w, h: region.h };
|
|
20
|
+
case "circle":
|
|
21
|
+
return { x: region.cx - region.r, y: region.cy - region.r, w: 2 * region.r, h: 2 * region.r };
|
|
22
|
+
case "ellipse":
|
|
23
|
+
return { x: region.cx - region.rx, y: region.cy - region.ry, w: 2 * region.rx, h: 2 * region.ry };
|
|
24
|
+
case "polygon": {
|
|
25
|
+
const xs = region.points.map((p) => p[0]);
|
|
26
|
+
const ys = region.points.map((p) => p[1]);
|
|
27
|
+
const x = Math.min(...xs);
|
|
28
|
+
const y = Math.min(...ys);
|
|
29
|
+
return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The rectangle of a container: its origin and its size. A free side has the size `Infinity`. */
|
|
35
|
+
export interface Bounds {
|
|
36
|
+
x: number;
|
|
37
|
+
y: number;
|
|
38
|
+
w: number;
|
|
39
|
+
h: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** This function gives the rectangle of a container. A rectangle shape gives the origin and the sizes of the fixed sides. */
|
|
43
|
+
export function containerBounds(input: PackInput): Bounds {
|
|
44
|
+
const { container } = input;
|
|
45
|
+
const shape = container.shape === undefined ? undefined : boundsOf(container.shape);
|
|
46
|
+
const fixedW = container.fixed === "size" || container.fixed === "width";
|
|
47
|
+
const fixedH = container.fixed === "size" || container.fixed === "height";
|
|
48
|
+
const w = shape?.w ?? container.w;
|
|
49
|
+
const h = shape?.h ?? container.h;
|
|
50
|
+
if (fixedW && w === undefined) throw new TypeError(`A container with fixed "${container.fixed}" needs a width.`);
|
|
51
|
+
if (fixedH && h === undefined) throw new TypeError(`A container with fixed "${container.fixed}" needs a height.`);
|
|
52
|
+
return { x: shape?.x ?? 0, y: shape?.y ?? 0, w: fixedW ? w! : Infinity, h: fixedH ? h! : Infinity };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** One rectangle of the frame, and the item or the obstacle that it measures. */
|
|
56
|
+
export interface Entry {
|
|
57
|
+
rect: Rect<number>;
|
|
58
|
+
item?: Item;
|
|
59
|
+
obstacle?: Obstacle;
|
|
60
|
+
/** The offset from the corner of the rectangle to the corner of the item or the obstacle. */
|
|
61
|
+
dx: number;
|
|
62
|
+
dy: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The rectangles of 0.1 for one input. */
|
|
66
|
+
export interface Frame {
|
|
67
|
+
/** The container coordinates of the origin of the frame. */
|
|
68
|
+
ox: number;
|
|
69
|
+
oy: number;
|
|
70
|
+
/** The size of the area of the frame. A free side has the size `Infinity`. */
|
|
71
|
+
w: number;
|
|
72
|
+
h: number;
|
|
73
|
+
bounds: Bounds;
|
|
74
|
+
inset: number;
|
|
75
|
+
/** The items in the order of their rank, then the obstacles. */
|
|
76
|
+
entries: Entry[];
|
|
77
|
+
/** The ids of the items that are too large for the area. The frame has no rectangle for them. */
|
|
78
|
+
tooLarge: string[];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** This function gives the items in the order of their rank. The index in the array is the rank of an item without one. */
|
|
82
|
+
export function byRank(items: readonly Item[]): Item[] {
|
|
83
|
+
return items
|
|
84
|
+
.map((item, index) => ({ item, rank: item.rank ?? index }))
|
|
85
|
+
.toSorted((a, b) => a.rank - b.rank)
|
|
86
|
+
.map((e) => e.item);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* This function makes the frame of an input. A locked item with a position and an obstacle without `move` are locked
|
|
91
|
+
* rectangles. An obstacle with `move` is a free rectangle only when `movable` is `true`.
|
|
92
|
+
*/
|
|
93
|
+
export function buildFrame(input: PackInput, movable = false): Frame {
|
|
94
|
+
const bounds = containerBounds(input);
|
|
95
|
+
const inset = input.container.inset ?? 0;
|
|
96
|
+
const half = (input.gap ?? 0) / 2;
|
|
97
|
+
const ox = bounds.x + inset - half;
|
|
98
|
+
const oy = bounds.y + inset - half;
|
|
99
|
+
const w = bounds.w - 2 * inset + 2 * half;
|
|
100
|
+
const h = bounds.h - 2 * inset + 2 * half;
|
|
101
|
+
const entries: Entry[] = [];
|
|
102
|
+
const tooLarge: string[] = [];
|
|
103
|
+
|
|
104
|
+
for (const item of byRank(input.items)) {
|
|
105
|
+
const m = marginOf(item);
|
|
106
|
+
const rect = new Rect<number>();
|
|
107
|
+
rect.size.set(item.w + m.left + m.right + 2 * half, item.h + m.top + m.bottom + 2 * half);
|
|
108
|
+
const dx = m.left + half;
|
|
109
|
+
const dy = m.top + half;
|
|
110
|
+
if (item.locked === true && item.x !== undefined && item.y !== undefined) {
|
|
111
|
+
rect.locked = true;
|
|
112
|
+
rect.position.set(item.x - dx - ox, item.y - dy - oy);
|
|
113
|
+
} else if (rect.size.x > w + EPS || rect.size.y > h + EPS) {
|
|
114
|
+
tooLarge.push(item.id);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
entries.push({ rect, item, dx, dy });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
for (const obstacle of input.obstacles ?? []) {
|
|
121
|
+
const b = boundsOf(obstacle.region);
|
|
122
|
+
const rect = new Rect<number>();
|
|
123
|
+
rect.size.set(b.w + 2 * half, b.h + 2 * half);
|
|
124
|
+
rect.position.set(b.x - half - ox, b.y - half - oy);
|
|
125
|
+
rect.locked = !(movable && obstacle.move !== undefined);
|
|
126
|
+
entries.push({ rect, obstacle, dx: half, dy: half });
|
|
127
|
+
}
|
|
128
|
+
return { ox, oy, w, h, bounds, inset, entries, tooLarge };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** This function gives the outer rectangle of 0.1 for a frame. A free height starts at 0 and grows. */
|
|
132
|
+
export function outerOf(frame: Frame): Rect<number> {
|
|
133
|
+
const outer = new Rect<number>();
|
|
134
|
+
const fixedSize = Number.isFinite(frame.h);
|
|
135
|
+
outer.size.set(frame.w, fixedSize ? frame.h : 0);
|
|
136
|
+
outer.fixedWidth = true;
|
|
137
|
+
outer.fixedSize = fixedSize;
|
|
138
|
+
return outer;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** This function gives the rectangles of a frame, in the order of the entries. */
|
|
142
|
+
export function rectsOf(frame: Frame): Rect<number>[] {
|
|
143
|
+
return frame.entries.map((e) => e.rect);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* This function reads the output from the rectangles of a frame after a packing of 0.1. A locked item keeps its
|
|
148
|
+
* position exactly. Each other item that the packer did not place goes to the overflow.
|
|
149
|
+
*/
|
|
150
|
+
export function readFrame(input: PackInput, frame: Frame, trace: StageTrace[], moved: PackOutput["moved"] = []): PackOutput {
|
|
151
|
+
const placements: Placement[] = [];
|
|
152
|
+
const overflow: string[] = [...frame.tooLarge];
|
|
153
|
+
for (const e of frame.entries) {
|
|
154
|
+
const item = e.item;
|
|
155
|
+
if (item === undefined) continue;
|
|
156
|
+
if (item.locked === true && item.x !== undefined && item.y !== undefined) placements.push({ id: item.id, x: item.x, y: item.y });
|
|
157
|
+
else if (e.rect.wasPacked) placements.push({ id: item.id, x: e.rect.position.x + e.dx + frame.ox, y: e.rect.position.y + e.dy + frame.oy });
|
|
158
|
+
else overflow.push(item.id);
|
|
159
|
+
}
|
|
160
|
+
return { placements, overflow, size: sizeOf(input, frame, placements, moved), moved, trace };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* This function gives the size of the container after a packing. A fixed side keeps its size. A free side goes to the
|
|
165
|
+
* far edge of the items with their margins and the inset, or of the obstacles.
|
|
166
|
+
*/
|
|
167
|
+
function sizeOf(input: PackInput, frame: Frame, placements: Placement[], moved: PackOutput["moved"]): { w: number; h: number } {
|
|
168
|
+
const items = new Map(input.items.map((i) => [i.id, i]));
|
|
169
|
+
let right = 0;
|
|
170
|
+
let bottom = 0;
|
|
171
|
+
for (const p of placements) {
|
|
172
|
+
const item = items.get(p.id)!;
|
|
173
|
+
const m = marginOf(item);
|
|
174
|
+
right = Math.max(right, p.x + item.w + m.right + frame.inset - frame.bounds.x);
|
|
175
|
+
bottom = Math.max(bottom, p.y + item.h + m.bottom + frame.inset - frame.bounds.y);
|
|
176
|
+
}
|
|
177
|
+
const movedById = new Map(moved.map((m) => [m.id, m]));
|
|
178
|
+
for (const o of input.obstacles ?? []) {
|
|
179
|
+
const b = boundsOf(o.region);
|
|
180
|
+
const at = movedById.get(o.id) ?? b;
|
|
181
|
+
right = Math.max(right, at.x + b.w - frame.bounds.x);
|
|
182
|
+
bottom = Math.max(bottom, at.y + b.h - frame.bounds.y);
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
w: Number.isFinite(frame.bounds.w) ? frame.bounds.w : right,
|
|
186
|
+
h: Number.isFinite(frame.bounds.h) ? frame.bounds.h : bottom,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** This function gives a region with the axes changed: x for y, and w for h. */
|
|
191
|
+
export function transposeRegion(region: Region): Region {
|
|
192
|
+
switch (region.kind) {
|
|
193
|
+
case "rect":
|
|
194
|
+
return { kind: "rect", x: region.y, y: region.x, w: region.h, h: region.w };
|
|
195
|
+
case "circle":
|
|
196
|
+
return { kind: "circle", cx: region.cy, cy: region.cx, r: region.r };
|
|
197
|
+
case "ellipse":
|
|
198
|
+
return { kind: "ellipse", cx: region.cy, cy: region.cx, rx: region.ry, ry: region.rx };
|
|
199
|
+
case "polygon": {
|
|
200
|
+
const swap = (ring: [number, number][]): [number, number][] => ring.map(([x, y]) => [y, x]);
|
|
201
|
+
const turned: Region = { kind: "polygon", points: swap(region.points) };
|
|
202
|
+
if (region.holes) turned.holes = region.holes.map(swap);
|
|
203
|
+
return turned;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** This function gives an item with the axes changed. The ports go, because the adapters of 0.1 do not read them. */
|
|
209
|
+
function transposeItem(item: Item): Item {
|
|
210
|
+
const { ports: _ports, ...rest } = item;
|
|
211
|
+
const turned: Item = { ...rest, w: item.h, h: item.w };
|
|
212
|
+
delete turned.x;
|
|
213
|
+
delete turned.y;
|
|
214
|
+
if (item.y !== undefined) turned.x = item.y;
|
|
215
|
+
if (item.x !== undefined) turned.y = item.x;
|
|
216
|
+
if (item.shape) turned.shape = transposeRegion(item.shape);
|
|
217
|
+
if (item.margin !== undefined && typeof item.margin !== "number") {
|
|
218
|
+
const m = item.margin;
|
|
219
|
+
turned.margin = { top: m.left, right: m.bottom, bottom: m.right, left: m.top };
|
|
220
|
+
}
|
|
221
|
+
return turned;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** This function gives an input with the axes changed. A fixed height becomes a fixed width. */
|
|
225
|
+
export function transposeInput(input: PackInput): PackInput {
|
|
226
|
+
const c = input.container;
|
|
227
|
+
const container: PackInput["container"] = { fixed: c.fixed === "height" ? "width" : c.fixed === "width" ? "height" : c.fixed };
|
|
228
|
+
if (c.h !== undefined) container.w = c.h;
|
|
229
|
+
if (c.w !== undefined) container.h = c.w;
|
|
230
|
+
if (c.aspect !== undefined) container.aspect = 1 / c.aspect;
|
|
231
|
+
if (c.aspectWeight !== undefined) container.aspectWeight = c.aspectWeight;
|
|
232
|
+
if (c.shape !== undefined) container.shape = transposeRegion(c.shape);
|
|
233
|
+
if (c.inset !== undefined) container.inset = c.inset;
|
|
234
|
+
const turned: PackInput = { container, items: input.items.map(transposeItem) };
|
|
235
|
+
if (input.obstacles) turned.obstacles = input.obstacles.map((o) => ({ ...o, region: transposeRegion(o.region) }));
|
|
236
|
+
if (input.gap !== undefined) turned.gap = input.gap;
|
|
237
|
+
return turned;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** This function gives an output with the axes changed. */
|
|
241
|
+
export function transposeOutput(output: PackOutput): PackOutput {
|
|
242
|
+
return {
|
|
243
|
+
placements: output.placements.map((p) => ({ ...p, x: p.y, y: p.x })),
|
|
244
|
+
overflow: [...output.overflow],
|
|
245
|
+
size: { w: output.size.h, h: output.size.w },
|
|
246
|
+
moved: output.moved.map((m) => ({ id: m.id, x: m.y, y: m.x })),
|
|
247
|
+
trace: output.trace,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* This function packs an input with a fixed height through the turn of the axes. It changes x for y in the input.
|
|
253
|
+
* Then it packs with a fixed width, and changes the axes of the output back.
|
|
254
|
+
*/
|
|
255
|
+
export function viaAxes(input: PackInput, previous: PackOutput | undefined, run: (turned: PackInput, previous: PackOutput | undefined) => PackOutput): PackOutput {
|
|
256
|
+
const start = now();
|
|
257
|
+
const turned = transposeInput(input);
|
|
258
|
+
const inner = run(turned, previous === undefined ? undefined : transposeOutput(previous));
|
|
259
|
+
const output = transposeOutput(inner);
|
|
260
|
+
output.trace = [{ id: "axes", ms: now() - start, measures: {} }, ...inner.trace];
|
|
261
|
+
return output;
|
|
262
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -7,3 +7,44 @@ export { packFree, aspectError, type FreeWidthOptions, type FreeWidthResult, typ
|
|
|
7
7
|
export { compareRects, SORT_ORDERS, type SortOrder } from "./order.ts";
|
|
8
8
|
export { pushCascade, type PushOptions } from "./push.ts";
|
|
9
9
|
export { packingMetrics, type MetricsOptions, type PackingMetrics } from "./metrics.ts";
|
|
10
|
+
export {
|
|
11
|
+
DEFAULT_TOLERANCE,
|
|
12
|
+
EPS,
|
|
13
|
+
RECORD_EPS,
|
|
14
|
+
marginOf,
|
|
15
|
+
turnItem,
|
|
16
|
+
turnPoint,
|
|
17
|
+
turnPort,
|
|
18
|
+
turnRegion,
|
|
19
|
+
type Container,
|
|
20
|
+
type Item,
|
|
21
|
+
type Margin,
|
|
22
|
+
type Obstacle,
|
|
23
|
+
type PackInput,
|
|
24
|
+
type PackOutput,
|
|
25
|
+
type Placement,
|
|
26
|
+
type Port,
|
|
27
|
+
type Region,
|
|
28
|
+
type StageTrace,
|
|
29
|
+
type Tolerance,
|
|
30
|
+
} from "./contract.ts";
|
|
31
|
+
export {
|
|
32
|
+
UnsupportedCell,
|
|
33
|
+
assertSupported,
|
|
34
|
+
cellOf,
|
|
35
|
+
createContext,
|
|
36
|
+
mulberry32,
|
|
37
|
+
supportsCell,
|
|
38
|
+
unsupportedOf,
|
|
39
|
+
type Cell,
|
|
40
|
+
type Dimension,
|
|
41
|
+
type DimensionValue,
|
|
42
|
+
type PackContext,
|
|
43
|
+
type SizeSearch,
|
|
44
|
+
type Strategy,
|
|
45
|
+
type Supports,
|
|
46
|
+
} from "./strategy.ts";
|
|
47
|
+
export { logSweep, push, rows, shelf, skyline, type LayoutStrategyOptions, type PushStrategyOptions } from "./adapters.ts";
|
|
48
|
+
export { fromRects, toRects } from "./convert.ts";
|
|
49
|
+
export { packWith, strategies, strategy } from "./registry.ts";
|
|
50
|
+
export { checkHard, type HardBreaks } from "./check.ts";
|
package/src/pack.ts
CHANGED
|
@@ -70,7 +70,8 @@ function packRow<T>(rects: Rect<T>[], outer: Rect<T>, order: SortOrder): boolean
|
|
|
70
70
|
if (fillGaps && row.length > 1) {
|
|
71
71
|
const rectInRow = row[row.length - 1]!;
|
|
72
72
|
const outerLeft = new Rect<T>();
|
|
73
|
-
|
|
73
|
+
// The position of the region is relative to the outer rectangle, as packInto adds the position of the outer rectangle
|
|
74
|
+
outerLeft.position.set(rectInRow.position.x - outer.position.x, rectInRow.bottom() - outer.position.y);
|
|
74
75
|
outerLeft.size.set(rectInRow.size.x, rowRect.size.y - rectInRow.size.y);
|
|
75
76
|
outerLeft.fixedWidth = true;
|
|
76
77
|
outerLeft.fixedSize = true;
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { push, rows, shelf, skyline } from "./adapters.ts";
|
|
2
|
+
import type { PackInput, PackOutput } from "./contract.ts";
|
|
3
|
+
import { createContext, type Strategy } from "./strategy.ts";
|
|
4
|
+
|
|
5
|
+
/** Each strategy of the package. The benchmark starts each one on each input of the corpus. */
|
|
6
|
+
export const strategies: readonly Strategy[] = Object.freeze([rows, skyline, shelf, push] as Strategy[]);
|
|
7
|
+
|
|
8
|
+
/** This function gives the strategy with an id. It throws a `RangeError` for an id that the registry does not have. */
|
|
9
|
+
export function strategy(id: string): Strategy {
|
|
10
|
+
const found = strategies.find((s) => s.id === id);
|
|
11
|
+
if (found === undefined) throw new RangeError(`The registry has no strategy "${id}".`);
|
|
12
|
+
return found;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* This function packs an input with the strategy of an id. The options go over the defaults of the strategy. The
|
|
17
|
+
* context gets `mulberry32` with the seed. The default seed is 0.
|
|
18
|
+
*/
|
|
19
|
+
export function packWith(id: string, input: PackInput, options?: unknown, seed = 0): PackOutput {
|
|
20
|
+
const s = strategy(id);
|
|
21
|
+
const merged: unknown = { ...(s.defaults as object), ...(options as object | undefined) };
|
|
22
|
+
return s.pack(input, merged, createContext(seed));
|
|
23
|
+
}
|
package/src/strategy.ts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import type { Container, PackInput, PackOutput, Region } from "./contract.ts";
|
|
2
|
+
|
|
3
|
+
/** For each dimension of the taxonomy, the values that a strategy supports. `docs/research/TAXONOMY.md` gives the values. */
|
|
4
|
+
export interface Supports {
|
|
5
|
+
containerSize: ("fixed" | "freeHeight" | "freeWidth" | "freeAspect" | "freeArea")[];
|
|
6
|
+
containerShape: ("rect" | "convex" | "polygon" | "circle" | "ellipse" | "holes")[];
|
|
7
|
+
/** The movement of the obstacles. An empty list supports only an input with no obstacle and no locked item. */
|
|
8
|
+
obstacleMove: ("fixed" | "costly" | "free")[];
|
|
9
|
+
itemShape: ("rect" | "circle" | "convex" | "polygon" | "mixed")[];
|
|
10
|
+
rotation: ("none" | "quarter" | "any")[];
|
|
11
|
+
order: ("free" | "soft" | "hard")[];
|
|
12
|
+
groups: ("none" | "flat" | "nested")[];
|
|
13
|
+
mode: ("offline" | "online" | "incremental")[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A dimension of `Supports`. */
|
|
17
|
+
export type Dimension = keyof Supports;
|
|
18
|
+
|
|
19
|
+
/** A value of a dimension of `Supports`. */
|
|
20
|
+
export type DimensionValue<D extends Dimension = Dimension> = Supports[D][number];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The cell of an input: one value for each packer dimension that the input tells. The input does not tell the mode.
|
|
24
|
+
* Without obstacles and locked items, the cell has no `obstacleMove`.
|
|
25
|
+
*/
|
|
26
|
+
export interface Cell {
|
|
27
|
+
containerSize: DimensionValue<"containerSize">;
|
|
28
|
+
containerShape: DimensionValue<"containerShape">;
|
|
29
|
+
obstacleMove?: DimensionValue<"obstacleMove">;
|
|
30
|
+
itemShape: DimensionValue<"itemShape">;
|
|
31
|
+
rotation: DimensionValue<"rotation">;
|
|
32
|
+
order: DimensionValue<"order">;
|
|
33
|
+
groups: DimensionValue<"groups">;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The context of one packing. */
|
|
37
|
+
export interface PackContext {
|
|
38
|
+
/** The seed. A strategy gets each random number from `rng`, not from `Math.random`. */
|
|
39
|
+
seed: number;
|
|
40
|
+
/** The random numbers in `[0, 1)`, from `mulberry32` with `seed`. */
|
|
41
|
+
rng: () => number;
|
|
42
|
+
/** A limit for the strategies that search. The strategy gives its best result at the limit. */
|
|
43
|
+
budget?: { ms?: number; steps?: number };
|
|
44
|
+
/** The previous output, for the mode `incremental`. */
|
|
45
|
+
previous?: PackOutput;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A packing strategy behind the Packer interface. */
|
|
49
|
+
export interface Strategy<O = unknown> {
|
|
50
|
+
/** A stable name, for example `shelf`. The records use it. */
|
|
51
|
+
id: string;
|
|
52
|
+
/** The family of the catalog, for example `shelf` or `skyline`. */
|
|
53
|
+
family: string;
|
|
54
|
+
/** The ids of the catalog rows that this strategy builds. */
|
|
55
|
+
catalog: string[];
|
|
56
|
+
/** The cells that the strategy supports. */
|
|
57
|
+
supports: Supports;
|
|
58
|
+
/** The default options. A record writes the options in full. */
|
|
59
|
+
defaults: O;
|
|
60
|
+
/** The value `true` tells that the result depends only on the input, the options and the seed. */
|
|
61
|
+
deterministic: boolean;
|
|
62
|
+
/** This method packs an input. It throws `UnsupportedCell` for an input outside the cells of `supports`. */
|
|
63
|
+
pack(input: PackInput, options: O, context: PackContext): PackOutput;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A size search: it gives a strategy of a fixed width the cells `freeAspect` and `freeArea`. */
|
|
67
|
+
export interface SizeSearch {
|
|
68
|
+
id: string;
|
|
69
|
+
/** This method searches the size of the container for an input with `fixed` set to `none`. `options` go to `inner`. */
|
|
70
|
+
search(input: PackInput, inner: Strategy, context: PackContext, options?: unknown): PackOutput;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The error of a strategy for an input outside its cells. The benchmark records this result. It is not a failure of the
|
|
75
|
+
* strategy.
|
|
76
|
+
*/
|
|
77
|
+
export class UnsupportedCell extends Error {
|
|
78
|
+
/** The dimension of the taxonomy. */
|
|
79
|
+
readonly dimension: Dimension;
|
|
80
|
+
/** The value of the input that the strategy does not support. */
|
|
81
|
+
readonly value: string;
|
|
82
|
+
|
|
83
|
+
constructor(dimension: Dimension, value: string) {
|
|
84
|
+
super(`The strategy does not support the value "${value}" of the dimension "${dimension}".`);
|
|
85
|
+
this.name = "UnsupportedCell";
|
|
86
|
+
this.dimension = dimension;
|
|
87
|
+
this.value = value;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** This function gives a generator of random numbers in `[0, 1)`: `mulberry32` of `docs/FORMAT.md`. */
|
|
92
|
+
export function mulberry32(seed: number): () => number {
|
|
93
|
+
let s = seed >>> 0;
|
|
94
|
+
return () => {
|
|
95
|
+
s = (s + 0x6d2b79f5) | 0;
|
|
96
|
+
let t = Math.imul(s ^ (s >>> 15), 1 | s);
|
|
97
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
98
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** This function makes the context of one packing from a seed. */
|
|
103
|
+
export function createContext(seed = 0, more: Omit<PackContext, "seed" | "rng"> = {}): PackContext {
|
|
104
|
+
return { ...more, seed, rng: mulberry32(seed) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** This function tells if a polygon ring is convex. A ring with fewer than 3 points is convex. */
|
|
108
|
+
function isConvex(points: readonly [number, number][]): boolean {
|
|
109
|
+
let sign = 0;
|
|
110
|
+
const n = points.length;
|
|
111
|
+
for (let i = 0; i < n; i++) {
|
|
112
|
+
const [ax, ay] = points[i]!;
|
|
113
|
+
const [bx, by] = points[(i + 1) % n]!;
|
|
114
|
+
const [cx, cy] = points[(i + 2) % n]!;
|
|
115
|
+
const cross = (bx - ax) * (cy - by) - (by - ay) * (cx - bx);
|
|
116
|
+
if (cross === 0) continue;
|
|
117
|
+
if (sign === 0) sign = Math.sign(cross);
|
|
118
|
+
else if (Math.sign(cross) !== sign) return false;
|
|
119
|
+
}
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** This function gives the value of `containerShape` of one region. */
|
|
124
|
+
function shapeOf(region: Region): DimensionValue<"containerShape"> {
|
|
125
|
+
switch (region.kind) {
|
|
126
|
+
case "rect":
|
|
127
|
+
case "circle":
|
|
128
|
+
case "ellipse":
|
|
129
|
+
return region.kind;
|
|
130
|
+
case "polygon":
|
|
131
|
+
if (region.holes && region.holes.length > 0) return "holes";
|
|
132
|
+
return isConvex(region.points) ? "convex" : "polygon";
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** This function gives the value of `itemShape` of one item shape. An ellipse is convex. */
|
|
137
|
+
function itemShapeOf(region: Region | undefined): DimensionValue<"itemShape"> {
|
|
138
|
+
if (region === undefined) return "rect";
|
|
139
|
+
switch (region.kind) {
|
|
140
|
+
case "rect":
|
|
141
|
+
case "circle":
|
|
142
|
+
return region.kind;
|
|
143
|
+
case "ellipse":
|
|
144
|
+
return "convex";
|
|
145
|
+
case "polygon":
|
|
146
|
+
return !region.holes?.length && isConvex(region.points) ? "convex" : "polygon";
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* This function gives the cell of an input: the values of the packer dimensions that the input tells.
|
|
152
|
+
*
|
|
153
|
+
* - `containerSize` comes from `fixed`. The value `none` gives `freeArea` when `aspectWeight` is 0, and `freeAspect` if not.
|
|
154
|
+
* - `containerShape` comes from the shape. A rectangle container with an obstacle of another region gives `holes`.
|
|
155
|
+
* - `obstacleMove` is the hardest value of the obstacles and the locked items: `costly`, then `free`, then `fixed`.
|
|
156
|
+
* - `order` is `soft` when an item has a rank, and `free` if not. The input does not tell a hard order.
|
|
157
|
+
* - `groups` is `nested` when an item has a parent, `flat` when an item has a group, and `none` if not.
|
|
158
|
+
*/
|
|
159
|
+
export function cellOf(input: PackInput): Cell {
|
|
160
|
+
const { container, items } = input;
|
|
161
|
+
const obstacles = input.obstacles ?? [];
|
|
162
|
+
|
|
163
|
+
const sizes: Record<Container["fixed"], DimensionValue<"containerSize">> = {
|
|
164
|
+
size: "fixed",
|
|
165
|
+
width: "freeHeight",
|
|
166
|
+
height: "freeWidth",
|
|
167
|
+
none: container.aspectWeight === 0 ? "freeArea" : "freeAspect",
|
|
168
|
+
};
|
|
169
|
+
const containerSize = sizes[container.fixed];
|
|
170
|
+
|
|
171
|
+
let containerShape = container.shape ? shapeOf(container.shape) : "rect";
|
|
172
|
+
if (containerShape === "rect" && obstacles.some((o) => o.region.kind !== "rect")) containerShape = "holes";
|
|
173
|
+
|
|
174
|
+
let obstacleMove: DimensionValue<"obstacleMove"> | undefined = items.some((i) => i.locked === true) ? "fixed" : undefined;
|
|
175
|
+
for (const o of obstacles) {
|
|
176
|
+
const move = o.move === undefined ? "fixed" : o.move.cost > 0 ? "costly" : "free";
|
|
177
|
+
if (move === "costly" || obstacleMove === undefined || (move === "free" && obstacleMove === "fixed")) obstacleMove = move;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const shapes = new Set(items.map((i) => itemShapeOf(i.shape)));
|
|
181
|
+
const itemShape = shapes.size > 1 ? "mixed" : ([...shapes][0] ?? "rect");
|
|
182
|
+
|
|
183
|
+
const cell: Cell = {
|
|
184
|
+
containerSize,
|
|
185
|
+
containerShape,
|
|
186
|
+
itemShape,
|
|
187
|
+
rotation: items.some((i) => i.turnable === true) ? "quarter" : "none",
|
|
188
|
+
order: items.some((i) => i.rank !== undefined) ? "soft" : "free",
|
|
189
|
+
groups: items.some((i) => i.parent !== undefined) ? "nested" : items.some((i) => i.group !== undefined) ? "flat" : "none",
|
|
190
|
+
};
|
|
191
|
+
if (obstacleMove !== undefined) cell.obstacleMove = obstacleMove;
|
|
192
|
+
return cell;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** This function gives the first dimension of a cell that `supports` does not hold, or `undefined` when it holds each one. */
|
|
196
|
+
export function unsupportedOf(supports: Supports, cell: Partial<Record<Dimension, string>>): { dimension: Dimension; value: string } | undefined {
|
|
197
|
+
for (const dimension of Object.keys(supports) as Dimension[]) {
|
|
198
|
+
const value = cell[dimension];
|
|
199
|
+
if (value === undefined) continue;
|
|
200
|
+
if (!(supports[dimension] as readonly string[]).includes(value)) return { dimension, value };
|
|
201
|
+
}
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** This function tells if `supports` holds each value of a cell. A dimension that the cell does not have is held. */
|
|
206
|
+
export function supportsCell(supports: Supports, cell: Partial<Record<Dimension, string>>): boolean {
|
|
207
|
+
return unsupportedOf(supports, cell) === undefined;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** This function throws `UnsupportedCell` for the first value of the cell of an input that `supports` does not hold. */
|
|
211
|
+
export function assertSupported(supports: Supports, input: PackInput): void {
|
|
212
|
+
const miss = unsupportedOf(supports, cellOf(input));
|
|
213
|
+
if (miss) throw new UnsupportedCell(miss.dimension, miss.value);
|
|
214
|
+
}
|