@mark1russell7/packing 0.1.1 → 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.
@@ -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
+ }