@mark1russell7/layout-contract 0.11.2 → 0.11.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/layout-contract",
4
- "version": "0.11.2",
4
+ "version": "0.11.4",
5
5
  "description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
6
6
  "keywords": [
7
7
  "layout",
@@ -61,6 +61,7 @@
61
61
  "vitest": "^5.0.3"
62
62
  },
63
63
  "dependencies": {
64
+ "@mark1russell7/collections": "^0.11.5",
64
65
  "@mark1russell7/predicates": "^0.1.1",
65
66
  "@mark1russell7/rigor-generators": "^0.2.0",
66
67
  "@mark1russell7/rigor-statistics": "^0.2.19",
@@ -0,0 +1,219 @@
1
+ // The walk inside a polygon on a grid of cells: a scanline fill of the polygon with its holes, the shortest walk in steps to
2
+ // the 8 next cells, and a straightened path. The walk knows no topic: a floor plan, a map or a picture gives the polygon.
3
+ import { priorityQueue } from "@mark1russell7/collections";
4
+ import type { Ring } from "./geometry.ts";
5
+
6
+ /** A point of a grid walk: an x and a y, in the unit of the polygon. */
7
+ export type GridPoint = readonly [number, number];
8
+
9
+ /**
10
+ * A grid of the cells inside a polygon. A cell is inside when its center is inside the polygon and not inside a hole.
11
+ * The cell at column `c` and row `r` has the index `r * columns + c`.
12
+ */
13
+ export interface CellGrid {
14
+ /** The least x and the least y of the outer ring. */
15
+ readonly origin: GridPoint;
16
+ /** The side of a cell, in the unit of the polygon. */
17
+ readonly cell: number;
18
+ readonly columns: number;
19
+ readonly rows: number;
20
+ /** The value 1 for each cell inside the polygon, else 0. */
21
+ readonly inside: Uint8Array;
22
+ }
23
+
24
+ /** The options of `polygonGrid`. */
25
+ export interface PolygonGridOptions {
26
+ /** The rings of the holes of the polygon. A cell inside a hole is not inside the polygon. */
27
+ readonly holes?: readonly Ring[] | undefined;
28
+ /** The greatest count of cells. When the grid has more cells, the side of a cell doubles until it fits. The default is 4,000,000. */
29
+ readonly largest?: number | undefined;
30
+ }
31
+
32
+ /**
33
+ * This function makes the grid of the cells inside a polygon.
34
+ *
35
+ * @param ring - The outer ring of the polygon
36
+ * @param cell - The side of a cell, in the unit of the polygon. It is a finite number above 0.
37
+ * @param options - The holes of the polygon, and the greatest count of cells
38
+ */
39
+ export function polygonGrid(ring: Ring, cell: number, options: PolygonGridOptions = {}): CellGrid {
40
+ if (!(cell > 0) || !Number.isFinite(cell)) throw new RangeError(`The side of a cell is ${cell}. It must be a finite number above 0.`);
41
+ const largest = options.largest ?? 4_000_000;
42
+ const xs = ring.map(([x]) => x);
43
+ const ys = ring.map(([, y]) => y);
44
+ const origin: GridPoint = [Math.min(...xs), Math.min(...ys)];
45
+ const width = Math.max(...xs) - origin[0];
46
+ const height = Math.max(...ys) - origin[1];
47
+ let side = cell;
48
+ while (Math.ceil(width / side) * Math.ceil(height / side) > largest) side *= 2;
49
+ const columns = Math.max(1, Math.ceil(width / side));
50
+ const rows = Math.max(1, Math.ceil(height / side));
51
+ const grid: CellGrid = { origin, cell: side, columns, rows, inside: new Uint8Array(columns * rows) };
52
+ fillRing(grid, ring, 1);
53
+ for (const hole of options.holes ?? []) fillRing(grid, hole, 0);
54
+ return grid;
55
+ }
56
+
57
+ /** This function sets each cell with its center inside a ring to a value. Each row fills the cells between pairs of edge crossings. */
58
+ function fillRing(grid: CellGrid, ring: Ring, value: number): void {
59
+ const { origin, cell, columns, rows, inside } = grid;
60
+ const ys = ring.map(([, y]) => y);
61
+ const firstRow = Math.max(0, Math.floor((Math.min(...ys) - origin[1]) / cell));
62
+ const lastRow = Math.min(rows - 1, Math.ceil((Math.max(...ys) - origin[1]) / cell));
63
+ for (let row = firstRow; row <= lastRow; row++) {
64
+ const y = origin[1] + (row + 0.5) * cell;
65
+ const crossings: number[] = [];
66
+ ring.forEach(([xa, ya], index) => {
67
+ const [xb, yb] = ring[(index + 1) % ring.length]!;
68
+ if (ya > y !== yb > y) crossings.push(xa + ((y - ya) * (xb - xa)) / (yb - ya));
69
+ });
70
+ crossings.sort((a, b) => a - b);
71
+ for (let k = 0; k + 1 < crossings.length; k += 2) {
72
+ const first = Math.max(0, Math.ceil((crossings[k]! - origin[0]) / cell - 0.5));
73
+ const last = Math.min(columns - 1, Math.floor((crossings[k + 1]! - origin[0]) / cell - 0.5));
74
+ if (last >= first) inside.fill(value, row * columns + first, row * columns + last + 1);
75
+ }
76
+ }
77
+ }
78
+
79
+ /** This function gives the center of a cell of a grid. */
80
+ export function cellCenter(grid: CellGrid, index: number): GridPoint {
81
+ const column = index % grid.columns;
82
+ const row = (index - column) / grid.columns;
83
+ return [grid.origin[0] + (column + 0.5) * grid.cell, grid.origin[1] + (row + 0.5) * grid.cell];
84
+ }
85
+
86
+ /**
87
+ * This function gives the cell inside the polygon that is nearest to a point, within `reach` cells of the cell of the point.
88
+ * It gives -1 when no cell inside the polygon is so near.
89
+ *
90
+ * @param grid - The grid of the polygon
91
+ * @param point - The point
92
+ * @param reach - The greatest count of cells from the cell of the point, on each axis. The default is 4.
93
+ */
94
+ export function cellNear(grid: CellGrid, [x, y]: GridPoint, reach = 4): number {
95
+ const column = Math.floor((x - grid.origin[0]) / grid.cell);
96
+ const row = Math.floor((y - grid.origin[1]) / grid.cell);
97
+ let best = -1;
98
+ let bestDistance = Infinity;
99
+ for (let dr = -reach; dr <= reach; dr++) {
100
+ for (let dc = -reach; dc <= reach; dc++) {
101
+ const c = column + dc;
102
+ const r = row + dr;
103
+ if (c < 0 || r < 0 || c >= grid.columns || r >= grid.rows || grid.inside[r * grid.columns + c] === 0) continue;
104
+ const [cx, cy] = cellCenter(grid, r * grid.columns + c);
105
+ const distance = Math.hypot(cx - x, cy - y);
106
+ if (distance < bestDistance) {
107
+ best = r * grid.columns + c;
108
+ bestDistance = distance;
109
+ }
110
+ }
111
+ }
112
+ return best;
113
+ }
114
+
115
+ /** The result of a search of a grid from one cell: the walk length to each cell, and the cell before it on the walk. */
116
+ export interface GridSearch {
117
+ /** The length of the shortest walk to each cell, in the unit of the polygon. A cell with no walk has `Infinity`. */
118
+ readonly distance: Float64Array;
119
+ /** The cell before each cell on its shortest walk. The start and a cell with no walk have -1. */
120
+ readonly previous: Int32Array;
121
+ }
122
+
123
+ /**
124
+ * This function finds the shortest walk from one cell to each cell of a grid, in steps to the 8 next cells.
125
+ * A diagonal step goes only between two cells inside the polygon, so a walk does not cut a corner of the edge.
126
+ * Such a walk is at most 8.3% longer than the shortest walk in any direction.
127
+ *
128
+ * @param grid - The grid of the polygon
129
+ * @param start - The index of the start cell
130
+ * @param targets - The cells that end the search when the search reaches each of them. No value searches each cell.
131
+ */
132
+ export function searchGrid(grid: CellGrid, start: number, targets?: readonly number[]): GridSearch {
133
+ const { columns, rows, inside, cell } = grid;
134
+ const distance = new Float64Array(columns * rows).fill(Infinity);
135
+ const previous = new Int32Array(columns * rows).fill(-1);
136
+ const done = new Uint8Array(columns * rows);
137
+ let left = targets === undefined ? -1 : new Set(targets).size;
138
+ const wanted = targets === undefined ? undefined : new Set(targets);
139
+ const diagonal = cell * Math.SQRT2;
140
+ const queue = priorityQueue<readonly [number, number]>({ compare: (a, b) => a[0] - b[0] });
141
+ distance[start] = 0;
142
+ queue.offer([0, start]);
143
+ for (let item = queue.pollOrUndefined(); item !== undefined; item = queue.pollOrUndefined()) {
144
+ const [length, index] = item;
145
+ if (done[index] === 1 || length > distance[index]!) continue;
146
+ done[index] = 1;
147
+ if (wanted?.has(index) === true && --left === 0) break;
148
+ const column = index % columns;
149
+ const row = (index - column) / columns;
150
+ for (let dr = -1; dr <= 1; dr++) {
151
+ for (let dc = -1; dc <= 1; dc++) {
152
+ if (dr === 0 && dc === 0) continue;
153
+ const c = column + dc;
154
+ const r = row + dr;
155
+ if (c < 0 || r < 0 || c >= columns || r >= rows) continue;
156
+ const next = r * columns + c;
157
+ if (inside[next] === 0) continue;
158
+ if (dr !== 0 && dc !== 0 && (inside[row * columns + c] === 0 || inside[r * columns + column] === 0)) continue;
159
+ const step = length + (dr !== 0 && dc !== 0 ? diagonal : cell);
160
+ if (step < distance[next]!) {
161
+ distance[next] = step;
162
+ previous[next] = index;
163
+ queue.offer([step, next]);
164
+ }
165
+ }
166
+ }
167
+ }
168
+ return { distance, previous };
169
+ }
170
+
171
+ /** This function gives the cells of the walk from the start of a search to a cell, in their sequence. A cell with no walk gives an empty list. */
172
+ export function walkCells(search: GridSearch, end: number): number[] {
173
+ if (search.distance[end] === Infinity) return [];
174
+ const cells: number[] = [];
175
+ for (let index = end; index !== -1; index = search.previous[index]!) cells.push(index);
176
+ return cells.reverse();
177
+ }
178
+
179
+ /** This function tells if the straight line between two points stays in the cells inside the polygon. It samples the line at each half cell. */
180
+ export function inSight(grid: CellGrid, [xa, ya]: GridPoint, [xb, yb]: GridPoint): boolean {
181
+ const samples = Math.max(1, Math.ceil(Math.hypot(xb - xa, yb - ya) / (grid.cell / 2)));
182
+ for (let k = 0; k <= samples; k++) {
183
+ const x = xa + ((xb - xa) * k) / samples;
184
+ const y = ya + ((yb - ya) * k) / samples;
185
+ const column = Math.floor((x - grid.origin[0]) / grid.cell);
186
+ const row = Math.floor((y - grid.origin[1]) / grid.cell);
187
+ if (column < 0 || row < 0 || column >= grid.columns || row >= grid.rows || grid.inside[row * grid.columns + column] === 0) return false;
188
+ }
189
+ return true;
190
+ }
191
+
192
+ /**
193
+ * This function makes a walk shorter: from each corner, it goes straight to the farthest next point in sight.
194
+ * The first point and the last point stay. Each straight run stays in the cells inside the polygon.
195
+ */
196
+ export function straightenWalk(grid: CellGrid, points: readonly GridPoint[]): GridPoint[] {
197
+ if (points.length <= 2) return [...points];
198
+ const result: GridPoint[] = [points[0]!];
199
+ let anchor = 0;
200
+ while (anchor < points.length - 1) {
201
+ let next = anchor + 1;
202
+ for (let k = points.length - 1; k > anchor + 1; k--) {
203
+ if (inSight(grid, points[anchor]!, points[k]!)) {
204
+ next = k;
205
+ break;
206
+ }
207
+ }
208
+ result.push(points[next]!);
209
+ anchor = next;
210
+ }
211
+ return result;
212
+ }
213
+
214
+ /** This function gives the length of a line through a list of points. */
215
+ export function polylineLength(points: readonly GridPoint[]): number {
216
+ let length = 0;
217
+ for (let k = 1; k < points.length; k++) length += Math.hypot(points[k]![0] - points[k - 1]![0], points[k]![1] - points[k - 1]![1]);
218
+ return length;
219
+ }
package/src/index.ts CHANGED
@@ -14,6 +14,7 @@ export * from "./balance.ts";
14
14
  export * from "./cell.ts";
15
15
  export * from "./frame.ts";
16
16
  export * from "./path.ts";
17
+ export * from "./grid-walk.ts";
17
18
  export * from "./picture.ts";
18
19
  export * from "./nest.ts";
19
20
  export * from "./strategy.ts";