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