@mark1russell7/layout-contract 0.9.8 → 0.10.0
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 +12 -7
- package/build/index.d.ts +314 -11
- package/build/index.d.ts.map +1 -1
- package/build/index.js +784 -24
- package/build/index.js.map +1 -1
- package/build/{measures-CJZw-Y3H.d.ts → measures-J0yY_JvV.d.ts} +32 -2
- package/build/measures-J0yY_JvV.d.ts.map +1 -0
- package/build/text.d.ts +28 -2
- package/build/text.d.ts.map +1 -1
- package/build/text.js +93 -24
- package/build/text.js.map +1 -1
- package/package.json +2 -2
- package/src/balance.ts +11 -4
- package/src/cell.ts +104 -0
- package/src/curves.ts +200 -0
- package/src/geometry.ts +136 -0
- package/src/hash.ts +2 -2
- package/src/index.ts +4 -0
- package/src/input.ts +5 -0
- package/src/measure-registry.ts +192 -0
- package/src/measure-survey.ts +149 -0
- package/src/measures.ts +4 -4
- package/src/output.ts +15 -3
- package/src/resize.ts +13 -1
- package/src/rules.ts +82 -18
- package/src/text.ts +100 -13
- package/build/measures-CJZw-Y3H.d.ts.map +0 -1
package/src/balance.ts
CHANGED
|
@@ -11,6 +11,8 @@ export interface PlacedBox extends Rect {
|
|
|
11
11
|
export interface Balance {
|
|
12
12
|
/** The standard deviation of the nearest-neighbour gaps divided by their mean. */
|
|
13
13
|
readonly gapCv: number;
|
|
14
|
+
/** The mean of the nearest-neighbour gaps, in layout units. With fewer than 2 boxes, the value is 0. */
|
|
15
|
+
readonly gapMean: number;
|
|
14
16
|
/** The distance from the centroid of the free area to the center of the container, as a share of the half-diagonal. */
|
|
15
17
|
readonly centroidOffset: number;
|
|
16
18
|
/** The empty share of the strip at each side of the container. */
|
|
@@ -25,6 +27,7 @@ export const BALANCE_SIDE_DEPTH = 0.25;
|
|
|
25
27
|
/** A suffix of a balance or stability measure. A stage adds its prefix, for example `pack.balance.gapCv`. */
|
|
26
28
|
export type BalanceMeasureSuffix =
|
|
27
29
|
| "balance.gapCv"
|
|
30
|
+
| "balance.gapMean"
|
|
28
31
|
| "balance.centroidOffset"
|
|
29
32
|
| "balance.side.top"
|
|
30
33
|
| "balance.side.right"
|
|
@@ -37,6 +40,7 @@ export type BalanceMeasureSuffix =
|
|
|
37
40
|
/** The suffixes of the balance and stability measures, in the order of `docs/BALANCE.md`. */
|
|
38
41
|
export const BALANCE_MEASURE_SUFFIXES: readonly BalanceMeasureSuffix[] = /* @__PURE__ */ Object.freeze([
|
|
39
42
|
"balance.gapCv",
|
|
43
|
+
"balance.gapMean",
|
|
40
44
|
"balance.centroidOffset",
|
|
41
45
|
"balance.side.top",
|
|
42
46
|
"balance.side.right",
|
|
@@ -141,7 +145,7 @@ export function balanceOf(boxes: readonly Rect[], container: Rect): Balance {
|
|
|
141
145
|
side[s] = stripArea > 0 ? Math.min(1, Math.max(0, 1 - filled / stripArea)) : 0;
|
|
142
146
|
}
|
|
143
147
|
const values = SIDES.map((s) => side[s]);
|
|
144
|
-
return { gapCv, centroidOffset, side, sideRange: Math.max(...values) - Math.min(...values) };
|
|
148
|
+
return { gapCv, gapMean: mean, centroidOffset, side, sideRange: Math.max(...values) - Math.min(...values) };
|
|
145
149
|
}
|
|
146
150
|
|
|
147
151
|
/** The options of `procrustesOf`. */
|
|
@@ -207,6 +211,7 @@ export function perChange(move: number, changed: number, count: number): number
|
|
|
207
211
|
export function balanceMeasures<S extends string>(stage: S, balance: Balance): Record<`${S}.${BalanceMeasureSuffix}`, number> {
|
|
208
212
|
const m: Record<string, number> = {
|
|
209
213
|
[`${stage}.balance.gapCv`]: balance.gapCv,
|
|
214
|
+
[`${stage}.balance.gapMean`]: balance.gapMean,
|
|
210
215
|
[`${stage}.balance.centroidOffset`]: balance.centroidOffset,
|
|
211
216
|
[`${stage}.balance.sideRange`]: balance.sideRange,
|
|
212
217
|
};
|
|
@@ -217,6 +222,7 @@ export function balanceMeasures<S extends string>(stage: S, balance: Balance): R
|
|
|
217
222
|
/**
|
|
218
223
|
* This function gives the specs of the balance and stability measures, with the prefix of the stage.
|
|
219
224
|
* The balance measures read the area of each box, so they support only `rect`. The stability measures read only the centers.
|
|
225
|
+
* `balance.gapMean` has no better side. An objective gives it a target, so its role is `diagnostic`, and the joint selector does not rank by it.
|
|
220
226
|
*/
|
|
221
227
|
export function balanceMeasureSpecs<S extends string>(stage: S): readonly MeasureSpec<`${S}.${BalanceMeasureSuffix}`>[] {
|
|
222
228
|
const id = (suffix: BalanceMeasureSuffix): `${S}.${BalanceMeasureSuffix}` => `${stage}.${suffix}`;
|
|
@@ -224,9 +230,10 @@ export function balanceMeasureSpecs<S extends string>(stage: S): readonly Measur
|
|
|
224
230
|
const centers = SHAPE_KIND_IDS;
|
|
225
231
|
return Object.freeze([
|
|
226
232
|
{ id: id("balance.gapCv"), unit: "ratio", direction: "lower", min: 0, max: Infinity, minEffect: 0.01, family: "balance", shapes: rect },
|
|
227
|
-
{ id: id("balance.
|
|
228
|
-
|
|
229
|
-
{ id: id(
|
|
233
|
+
{ id: id("balance.gapMean"), unit: "layout units", direction: "higher", min: 0, max: Infinity, family: "balance", role: "diagnostic", shapes: rect },
|
|
234
|
+
{ id: id("balance.centroidOffset"), unit: "share", direction: "lower", min: 0, max: 1, minEffect: 0.01, family: "balance", shapes: rect },
|
|
235
|
+
...SIDES.map((s) => ({ id: id(`balance.side.${s}`), unit: "share", direction: "lower" as const, min: 0, max: 1, family: "balance", role: "diagnostic" as const, shapes: rect })),
|
|
236
|
+
{ id: id("balance.sideRange"), unit: "share", direction: "lower", min: 0, max: 1, minEffect: 0.02, family: "balance", shapes: rect },
|
|
230
237
|
{ id: id("stability.procrustes"), unit: "W for each change share", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, minEffect: 0.005, family: "stability", role: "change-guard", shapes: centers },
|
|
231
238
|
{ id: id("stability.seed"), unit: "W", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, minEffect: 0.005, family: "stability", shapes: centers },
|
|
232
239
|
]);
|
package/src/cell.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { regionArea, regionPerimeter, type Region } from "./geometry.ts";
|
|
2
|
+
import { measureEntry, type MeasureEntry } from "./measure-registry.ts";
|
|
3
|
+
import type { MeasureSpec } from "./measures.ts";
|
|
4
|
+
import type { ShapeKind } from "./shapes.ts";
|
|
5
|
+
|
|
6
|
+
/** One placed item for the cell measures: the area that the item asks for, and the region that it got. */
|
|
7
|
+
export interface CellItem {
|
|
8
|
+
/**
|
|
9
|
+
* The weight of the item, for example the area `w` by `h` of its box in the input. It is a finite number above 0.
|
|
10
|
+
* The targets do not need a sum of 1, because `cellsOf` divides each target by the sum of the targets.
|
|
11
|
+
*/
|
|
12
|
+
readonly target: number;
|
|
13
|
+
/** The region that the item got, in any frame. A box without a shape gives its rectangle. */
|
|
14
|
+
readonly cell: Region;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The cell measures of a set of items: `docs/CELLS.md` gives the definitions. */
|
|
18
|
+
export interface Cells {
|
|
19
|
+
/** Half the sum of the differences of the cell share and the target share, from 0 to 1. */
|
|
20
|
+
readonly areaError: number;
|
|
21
|
+
/** The mean of the perimeter squared over 4 PI times the area of each cell, 1 or more. */
|
|
22
|
+
readonly compactness: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The suffix of a cell measure id. The id is the stage, a point and the suffix, for example `pack.cell.areaError`. */
|
|
26
|
+
export type CellMeasureSuffix = "cell.areaError" | "cell.compactness";
|
|
27
|
+
|
|
28
|
+
/** The suffixes of the cell measures, in the order of `cellMeasureSpecs`. */
|
|
29
|
+
export const CELL_MEASURE_SUFFIXES: readonly CellMeasureSuffix[] = /* @__PURE__ */ Object.freeze(["cell.areaError", "cell.compactness"] as const);
|
|
30
|
+
|
|
31
|
+
/** The compactness of a square: 4 over PI. */
|
|
32
|
+
export const SQUARE_COMPACTNESS: number = 4 / Math.PI;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* This function gives the cell measures of the placed items in a container of the area `containerArea`.
|
|
36
|
+
*
|
|
37
|
+
* - The cell share of an item is the area of its cell over `containerArea`. The target share is its `target` over the sum of the targets.
|
|
38
|
+
* - `containerArea` is the area of the container region. For a container with a shape, give `regionArea` of the shape, not `w` by `h`.
|
|
39
|
+
* - `areaError` is half the sum of the absolute differences of the two shares. Cells that fill the container in the target shares give 0.
|
|
40
|
+
* Cells that overlap or go out of the container can give a sum over 1. Those cells break the hard rules, and the value stops at 1.
|
|
41
|
+
* - `compactness` is the mean of `P * P / (4 * PI * A)` over the cells, for the perimeter `P` and the area `A` of each cell.
|
|
42
|
+
* A circle gives 1, and a square gives 4 over PI. A cell with the area 0 gives `Infinity`.
|
|
43
|
+
* - No items give the best values: an `areaError` of 0 and a `compactness` of 1. The hard rule `complete` counts the items that are not placed.
|
|
44
|
+
*
|
|
45
|
+
* A target that is not a finite number above 0, and a container area that is not a finite number above 0, give a `RangeError`.
|
|
46
|
+
*/
|
|
47
|
+
export function cellsOf(items: readonly CellItem[], containerArea: number): Cells {
|
|
48
|
+
if (!(Number.isFinite(containerArea) && containerArea > 0)) throw new RangeError(`cellsOf: the container area is a finite number above 0, not ${containerArea}.`);
|
|
49
|
+
if (items.length === 0) return { areaError: 0, compactness: 1 };
|
|
50
|
+
let targets = 0;
|
|
51
|
+
for (const item of items) {
|
|
52
|
+
if (!(Number.isFinite(item.target) && item.target > 0)) throw new RangeError(`cellsOf: a target is a finite number above 0, not ${item.target}.`);
|
|
53
|
+
targets += item.target;
|
|
54
|
+
}
|
|
55
|
+
let error = 0;
|
|
56
|
+
let compact = 0;
|
|
57
|
+
for (const item of items) {
|
|
58
|
+
const area = regionArea(item.cell);
|
|
59
|
+
error += Math.abs(area / containerArea - item.target / targets);
|
|
60
|
+
const p = regionPerimeter(item.cell);
|
|
61
|
+
compact += area > 0 ? (p * p) / (4 * Math.PI * area) : Infinity;
|
|
62
|
+
}
|
|
63
|
+
return { areaError: Math.min(1, error / 2), compactness: compact / items.length };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** This function gives the cell values as measures, with the prefix of the stage, for example `pack.cell.areaError`. */
|
|
67
|
+
export function cellMeasures<S extends string>(stage: S, cells: Cells): Record<`${S}.${CellMeasureSuffix}`, number> {
|
|
68
|
+
return {
|
|
69
|
+
[`${stage}.cell.areaError`]: cells.areaError,
|
|
70
|
+
[`${stage}.cell.compactness`]: cells.compactness,
|
|
71
|
+
} as Record<`${S}.${CellMeasureSuffix}`, number>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* This function gives the specs of the cell measures, with the prefix of the stage. The family is `cell`.
|
|
76
|
+
* The measures read the exact area and perimeter of each cell, so they support `rect`, `polygon` and `circle`. A `free` box has only its bounding box, so it is not supported.
|
|
77
|
+
*/
|
|
78
|
+
export function cellMeasureSpecs<S extends string>(stage: S): readonly MeasureSpec<`${S}.${CellMeasureSuffix}`>[] {
|
|
79
|
+
const shapes: readonly ShapeKind[] = ["rect", "polygon", "circle"];
|
|
80
|
+
return Object.freeze([
|
|
81
|
+
{ id: `${stage}.cell.areaError`, unit: "share", direction: "lower", min: 0, max: 1, floor: 0, tol: 1e-9, minEffect: 0.01, family: "cell", shapes },
|
|
82
|
+
{ id: `${stage}.cell.compactness`, unit: "ratio", direction: "lower", min: 1, max: Infinity, minEffect: 0.01, family: "cell", shapes },
|
|
83
|
+
] as MeasureSpec<`${S}.${CellMeasureSuffix}`>[]);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The npm name of the package that computes the cell measures. */
|
|
87
|
+
export const CELL_SOURCE = "@mark1russell7/layout-contract";
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* This function gives the registry entries of the cell measures, with the prefix of the stage.
|
|
91
|
+
* `areaError` uses the rule `range`. `compactness` uses the rule `scale`: a square has the loss 0.5.
|
|
92
|
+
* The cost of each is `n`. Each makes one pass over the corners of the cells. The cells of a Voronoi diagram have a count of corners in the order of `n`.
|
|
93
|
+
*/
|
|
94
|
+
export function cellMeasureEntries<S extends string>(stage: S): readonly MeasureEntry<`${S}.${CellMeasureSuffix}`>[] {
|
|
95
|
+
const [area, compact] = cellMeasureSpecs(stage);
|
|
96
|
+
return Object.freeze([
|
|
97
|
+
measureEntry(area!, { source: CELL_SOURCE, cost: "n" }),
|
|
98
|
+
measureEntry(compact!, {
|
|
99
|
+
source: CELL_SOURCE,
|
|
100
|
+
cost: "n",
|
|
101
|
+
normalize: { kind: "scale", half: SQUARE_COMPACTNESS - 1, reason: "A square cell has the loss 0.5, and a circle has the loss 0." },
|
|
102
|
+
}),
|
|
103
|
+
]);
|
|
104
|
+
}
|
package/src/curves.ts
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// Curves through the cells of a square grid: Hilbert, Moore and Morton (Z order). `docs/CURVES.md` gives the rules.
|
|
2
|
+
//
|
|
3
|
+
// A curve of side 2h has four parts. Part k fills the quadrant `order[k]` with a curve of side h, and the
|
|
4
|
+
// symmetry of part k maps that curve onto its quadrant. The top level uses the symmetries `root`, and each level
|
|
5
|
+
// below it uses the symmetries `child`. A curve of side 1 is the one cell (0, 0).
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A symmetry of a square: one of its 8 rotations and reflections. The names tell where a point `(s, t)` goes in a square
|
|
9
|
+
* of side `size`.
|
|
10
|
+
*/
|
|
11
|
+
export type CurveSymmetry =
|
|
12
|
+
/** The point stays: `(s, t)`. */
|
|
13
|
+
| "same"
|
|
14
|
+
/** The reflection in the diagonal from `(0, 0)`: `(t, s)`. */
|
|
15
|
+
| "swap"
|
|
16
|
+
/** The reflection in the other diagonal: `(size - t, size - s)`. */
|
|
17
|
+
| "back"
|
|
18
|
+
/** The turn by a half circle: `(size - s, size - t)`. */
|
|
19
|
+
| "half"
|
|
20
|
+
/** The quarter turn from the axis `s` to the axis `t`: `(size - t, s)`. */
|
|
21
|
+
| "rise"
|
|
22
|
+
/** The quarter turn from the axis `t` to the axis `s`: `(t, size - s)`. */
|
|
23
|
+
| "fall"
|
|
24
|
+
/** The reflection that changes `s`: `(size - s, t)`. */
|
|
25
|
+
| "flip-s"
|
|
26
|
+
/** The reflection that changes `t`: `(s, size - t)`. */
|
|
27
|
+
| "flip-t";
|
|
28
|
+
|
|
29
|
+
/** The 8 symmetries of a square, in a fixed order. */
|
|
30
|
+
export const CURVE_SYMMETRIES: readonly CurveSymmetry[] = Object.freeze(["same", "swap", "back", "half", "rise", "fall", "flip-s", "flip-t"]);
|
|
31
|
+
|
|
32
|
+
/** A quadrant of a square: `[0, 0]` is the low left quadrant, and `[1, 0]` is the quadrant with the high `s` and the low `t`. */
|
|
33
|
+
export type CurveQuadrant = readonly [0 | 1, 0 | 1];
|
|
34
|
+
|
|
35
|
+
/** The symmetries of the four parts of one level of a curve, in the order of the parts. */
|
|
36
|
+
export type CurvePattern = readonly [CurveSymmetry, CurveSymmetry, CurveSymmetry, CurveSymmetry];
|
|
37
|
+
|
|
38
|
+
/** A curve as data. It has the quadrant of each part in the order of the curve, and the symmetry of each part. */
|
|
39
|
+
export interface CurveSpec {
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly order: readonly [CurveQuadrant, CurveQuadrant, CurveQuadrant, CurveQuadrant];
|
|
42
|
+
readonly root: CurvePattern;
|
|
43
|
+
readonly child: CurvePattern;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The order of the parts of the Hilbert and Moore curves: low left, high left, high right and low right. */
|
|
47
|
+
const LOOP_ORDER: CurveSpec["order"] = Object.freeze([
|
|
48
|
+
Object.freeze([0, 0] as const),
|
|
49
|
+
Object.freeze([0, 1] as const),
|
|
50
|
+
Object.freeze([1, 1] as const),
|
|
51
|
+
Object.freeze([1, 0] as const),
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
/** The parts of the Hilbert curve. The curve goes in at the corner `(0, 0)` and out at the corner `(size, 0)`. */
|
|
55
|
+
export const HILBERT_PATTERN: CurvePattern = Object.freeze(["swap", "same", "same", "back"] as const);
|
|
56
|
+
|
|
57
|
+
/** The top level of the Moore curve: four Hilbert curves in a loop. The loop goes in and out at the middle of the side `t = 0`. */
|
|
58
|
+
export const MOORE_PATTERN: CurvePattern = Object.freeze(["rise", "rise", "fall", "fall"] as const);
|
|
59
|
+
|
|
60
|
+
/** The Hilbert curve. Two cells in a row along the curve share a side. */
|
|
61
|
+
export const HILBERT_CURVE: CurveSpec = Object.freeze({ name: "hilbert", order: LOOP_ORDER, root: HILBERT_PATTERN, child: HILBERT_PATTERN });
|
|
62
|
+
|
|
63
|
+
/** The Moore curve. Two cells in a row share a side, and the last cell shares a side with the first cell. */
|
|
64
|
+
export const MOORE_CURVE: CurveSpec = Object.freeze({ name: "moore", order: LOOP_ORDER, root: MOORE_PATTERN, child: HILBERT_PATTERN });
|
|
65
|
+
|
|
66
|
+
/** The Morton curve (the Z order). The index of a cell has the bits of `x` at the even places and the bits of `y` at the odd places. */
|
|
67
|
+
export const MORTON_CURVE: CurveSpec = Object.freeze({
|
|
68
|
+
name: "morton",
|
|
69
|
+
order: Object.freeze([Object.freeze([0, 0] as const), Object.freeze([1, 0] as const), Object.freeze([0, 1] as const), Object.freeze([1, 1] as const)] as const),
|
|
70
|
+
root: Object.freeze(["same", "same", "same", "same"] as const),
|
|
71
|
+
child: Object.freeze(["same", "same", "same", "same"] as const),
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
/** The largest side of a curve grid: 2 to the power 26. Thus each index is less than 2 to the power 52, and is exact. */
|
|
75
|
+
export const CURVE_MAX_SIDE: number = 2 ** 26;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* This function gives a point of the square `[0, size] x [0, size]` after a symmetry. The cell `(x, y)` of a grid of
|
|
79
|
+
* side `n` goes to a cell of the same grid with `size = n - 1`.
|
|
80
|
+
*/
|
|
81
|
+
export function applySymmetry(symmetry: CurveSymmetry, s: number, t: number, size = 1): [number, number] {
|
|
82
|
+
switch (symmetry) {
|
|
83
|
+
case "same":
|
|
84
|
+
return [s, t];
|
|
85
|
+
case "swap":
|
|
86
|
+
return [t, s];
|
|
87
|
+
case "back":
|
|
88
|
+
return [size - t, size - s];
|
|
89
|
+
case "half":
|
|
90
|
+
return [size - s, size - t];
|
|
91
|
+
case "rise":
|
|
92
|
+
return [size - t, s];
|
|
93
|
+
case "fall":
|
|
94
|
+
return [t, size - s];
|
|
95
|
+
case "flip-s":
|
|
96
|
+
return [size - s, t];
|
|
97
|
+
case "flip-t":
|
|
98
|
+
return [s, size - t];
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** This function gives the symmetry that undoes `symmetry`. Each symmetry undoes itself, but `rise` and `fall` undo each other. */
|
|
103
|
+
export function inverseSymmetry(symmetry: CurveSymmetry): CurveSymmetry {
|
|
104
|
+
return symmetry === "rise" ? "fall" : symmetry === "fall" ? "rise" : symmetry;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** This function gives the count of levels of a side. A side that is not a power of 2 from 1 to `CURVE_MAX_SIDE` is a `RangeError`. */
|
|
108
|
+
function levelsOf(side: number): number {
|
|
109
|
+
if (!Number.isInteger(side) || side < 1 || side > CURVE_MAX_SIDE || (side & (side - 1)) !== 0) {
|
|
110
|
+
throw new RangeError(`The side of a curve grid must be a power of 2 from 1 to ${CURVE_MAX_SIDE}, not ${side}.`);
|
|
111
|
+
}
|
|
112
|
+
return Math.round(Math.log2(side));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* This function gives the cell `[x, y]` at the place `index` along a curve on a grid of `side` cells on each side.
|
|
117
|
+
* The side is a power of 2, and the index is a whole number from 0 to `side * side - 1`. Other values are a `RangeError`.
|
|
118
|
+
* The cost is `O(log side)`.
|
|
119
|
+
*/
|
|
120
|
+
export function curveCell(curve: CurveSpec, index: number, side: number): [number, number] {
|
|
121
|
+
const levels = levelsOf(side);
|
|
122
|
+
if (!Number.isInteger(index) || index < 0 || index >= side * side) throw new RangeError(`The index ${index} is not a cell of a grid of side ${side}.`);
|
|
123
|
+
let x = 0;
|
|
124
|
+
let y = 0;
|
|
125
|
+
let rest = index;
|
|
126
|
+
// From the lowest level up: the cell in the part of side h goes to its quadrant of the part of side 2h.
|
|
127
|
+
for (let level = 0, h = 1; level < levels; level += 1, h *= 2) {
|
|
128
|
+
const part = rest % 4;
|
|
129
|
+
rest = Math.floor(rest / 4);
|
|
130
|
+
const pattern = level === levels - 1 ? curve.root : curve.child;
|
|
131
|
+
[x, y] = applySymmetry(pattern[part]!, x, y, h - 1);
|
|
132
|
+
const [qx, qy] = curve.order[part]!;
|
|
133
|
+
x += qx * h;
|
|
134
|
+
y += qy * h;
|
|
135
|
+
}
|
|
136
|
+
return [x, y];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* This function gives the place along a curve of the cell `(x, y)` of a grid of `side` cells on each side. It is the inverse
|
|
141
|
+
* of `curveCell`. A side that is not a power of 2, or a cell outside the grid, is a `RangeError`. The cost is `O(log side)`.
|
|
142
|
+
*/
|
|
143
|
+
export function curveIndex(curve: CurveSpec, x: number, y: number, side: number): number {
|
|
144
|
+
const levels = levelsOf(side);
|
|
145
|
+
for (const value of [x, y]) {
|
|
146
|
+
if (!Number.isInteger(value) || value < 0 || value >= side) throw new RangeError(`The cell (${x}, ${y}) is not in a grid of side ${side}.`);
|
|
147
|
+
}
|
|
148
|
+
let index = 0;
|
|
149
|
+
let s = x;
|
|
150
|
+
let t = y;
|
|
151
|
+
// From the top level down: find the quadrant, then undo the symmetry of its part.
|
|
152
|
+
for (let level = levels - 1, h = side / 2; level >= 0; level -= 1, h /= 2) {
|
|
153
|
+
const qx = s >= h ? 1 : 0;
|
|
154
|
+
const qy = t >= h ? 1 : 0;
|
|
155
|
+
const part = curve.order.findIndex(([ox, oy]) => ox === qx && oy === qy);
|
|
156
|
+
const pattern = level === levels - 1 ? curve.root : curve.child;
|
|
157
|
+
[s, t] = applySymmetry(inverseSymmetry(pattern[part]!), s - qx * h, t - qy * h, h - 1);
|
|
158
|
+
index += part * h * h;
|
|
159
|
+
}
|
|
160
|
+
return index;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** This function gives the place along the Hilbert curve of the cell `(x, y)` of a grid of side `side`. */
|
|
164
|
+
export function hilbertIndex(x: number, y: number, side: number): number {
|
|
165
|
+
return curveIndex(HILBERT_CURVE, x, y, side);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** This function gives the cell at the place `index` along the Hilbert curve on a grid of side `side`. */
|
|
169
|
+
export function hilbertCell(index: number, side: number): [number, number] {
|
|
170
|
+
return curveCell(HILBERT_CURVE, index, side);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** This function gives the place along the Moore curve of the cell `(x, y)` of a grid of side `side`. */
|
|
174
|
+
export function mooreIndex(x: number, y: number, side: number): number {
|
|
175
|
+
return curveIndex(MOORE_CURVE, x, y, side);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** This function gives the cell at the place `index` along the Moore curve on a grid of side `side`. */
|
|
179
|
+
export function mooreCell(index: number, side: number): [number, number] {
|
|
180
|
+
return curveCell(MOORE_CURVE, index, side);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** This function gives the place along the Morton curve of the cell `(x, y)` of a grid of side `side`. */
|
|
184
|
+
export function mortonIndex(x: number, y: number, side: number): number {
|
|
185
|
+
return curveIndex(MORTON_CURVE, x, y, side);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** This function gives the cell at the place `index` along the Morton curve on a grid of side `side`. */
|
|
189
|
+
export function mortonCell(index: number, side: number): [number, number] {
|
|
190
|
+
return curveCell(MORTON_CURVE, index, side);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* This function gives each cell of a grid of side `side` in the order of a curve. The cost is `O(side^2 log side)`.
|
|
195
|
+
* A side that is not a power of 2 is a `RangeError`.
|
|
196
|
+
*/
|
|
197
|
+
export function curveCells(curve: CurveSpec, side: number): [number, number][] {
|
|
198
|
+
levelsOf(side);
|
|
199
|
+
return Array.from({ length: side * side }, (_, index) => curveCell(curve, index, side));
|
|
200
|
+
}
|
package/src/geometry.ts
CHANGED
|
@@ -154,6 +154,42 @@ function ringArea(ring: readonly (readonly [number, number])[]): number {
|
|
|
154
154
|
return Math.abs(twice) / 2;
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
+
/**
|
|
158
|
+
* This function gives the perimeter of a region. A `rect` gives `2 * (w + h)`, and a circle gives `2 * PI * r`.
|
|
159
|
+
* A polygon gives the length of its outer ring plus the length of each hole. A ring with fewer than 2 points has the length 0.
|
|
160
|
+
*
|
|
161
|
+
* An ellipse has no closed form. It gives the second formula of Ramanujan, with a relative error below 5e-4 of the true perimeter. The error is largest for a flat ellipse.
|
|
162
|
+
*/
|
|
163
|
+
export function regionPerimeter(region: Region): number {
|
|
164
|
+
switch (region.kind) {
|
|
165
|
+
case "rect":
|
|
166
|
+
return 2 * (region.w + region.h);
|
|
167
|
+
case "circle":
|
|
168
|
+
return 2 * Math.PI * region.r;
|
|
169
|
+
case "ellipse": {
|
|
170
|
+
const a = Math.abs(region.rx);
|
|
171
|
+
const b = Math.abs(region.ry);
|
|
172
|
+
if (a + b === 0) return 0;
|
|
173
|
+
const t = ((a - b) / (a + b)) ** 2;
|
|
174
|
+
return Math.PI * (a + b) * (1 + (3 * t) / (10 + Math.sqrt(4 - 3 * t)));
|
|
175
|
+
}
|
|
176
|
+
case "polygon":
|
|
177
|
+
return (region.holes ?? []).reduce((length, hole) => length + ringLength(hole), ringLength(region.points));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** This function gives the length of the closed ring of a polygon. */
|
|
182
|
+
function ringLength(ring: readonly (readonly [number, number])[]): number {
|
|
183
|
+
if (ring.length < 2) return 0;
|
|
184
|
+
let length = 0;
|
|
185
|
+
for (let i = 0; i < ring.length; i++) {
|
|
186
|
+
const [ax, ay] = ring[i]!;
|
|
187
|
+
const [bx, by] = ring[(i + 1) % ring.length]!;
|
|
188
|
+
length += Math.hypot(bx - ax, by - ay);
|
|
189
|
+
}
|
|
190
|
+
return length;
|
|
191
|
+
}
|
|
192
|
+
|
|
157
193
|
/** This function gives the region moved by `dx` and `dy`. */
|
|
158
194
|
export function translate(region: Region, dx: number, dy: number): Region {
|
|
159
195
|
switch (region.kind) {
|
|
@@ -182,6 +218,106 @@ export function overlapOf(a: Rect, b: Rect): { readonly x: number; readonly y: n
|
|
|
182
218
|
};
|
|
183
219
|
}
|
|
184
220
|
|
|
221
|
+
/**
|
|
222
|
+
* This function gives the corners of a convex region, or `undefined` for each other region.
|
|
223
|
+
* A `rect` gives its 4 corners. A `polygon` without holes gives its points when it has 3 or more corners, an area over 0, and each turn to the same side.
|
|
224
|
+
* The turns use exact signs. A corner on a straight side is permitted. A circle and an ellipse give `undefined`.
|
|
225
|
+
*/
|
|
226
|
+
export function convexCorners(region: Region): Ring | undefined {
|
|
227
|
+
if (region.kind === "rect") {
|
|
228
|
+
const { x, y, w, h } = region;
|
|
229
|
+
return [
|
|
230
|
+
[x, y],
|
|
231
|
+
[x + w, y],
|
|
232
|
+
[x + w, y + h],
|
|
233
|
+
[x, y + h],
|
|
234
|
+
];
|
|
235
|
+
}
|
|
236
|
+
if (region.kind !== "polygon" || (region.holes !== undefined && region.holes.length > 0)) return undefined;
|
|
237
|
+
const ring = region.points;
|
|
238
|
+
if (ring.length < 3 || !ring.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y))) return undefined;
|
|
239
|
+
let turn = 0;
|
|
240
|
+
for (let i = 0; i < ring.length; i++) {
|
|
241
|
+
const [ax, ay] = ring[i]!;
|
|
242
|
+
const [bx, by] = ring[(i + 1) % ring.length]!;
|
|
243
|
+
const [cx, cy] = ring[(i + 2) % ring.length]!;
|
|
244
|
+
const s = orient2dSign(ax, ay, bx, by, cx, cy);
|
|
245
|
+
if (s === 0) continue;
|
|
246
|
+
if (turn !== 0 && s !== turn) return undefined;
|
|
247
|
+
turn = s;
|
|
248
|
+
}
|
|
249
|
+
return turn === 0 ? undefined : ring;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* This function gives the least overlap of two convex rings over the normals of their sides, in the units of the corners.
|
|
254
|
+
* By the separating axis theorem, a value of 0 or less tells that a line separates the rings. For two rectangles, the value is the lesser axis of `overlapOf`.
|
|
255
|
+
* A side of length 0 gives no normal. The rings come from `convexCorners`.
|
|
256
|
+
*/
|
|
257
|
+
export function convexOverlap(a: Ring, b: Ring): number {
|
|
258
|
+
let least = Infinity;
|
|
259
|
+
for (const ring of [a, b]) {
|
|
260
|
+
for (let i = 0; i < ring.length; i++) {
|
|
261
|
+
const [px, py] = ring[i]!;
|
|
262
|
+
const [qx, qy] = ring[(i + 1) % ring.length]!;
|
|
263
|
+
const length = Math.hypot(qx - px, qy - py);
|
|
264
|
+
if (length === 0) continue;
|
|
265
|
+
const nx = (py - qy) / length;
|
|
266
|
+
const ny = (qx - px) / length;
|
|
267
|
+
const [aLow, aHigh] = project(a, nx, ny);
|
|
268
|
+
const [bLow, bHigh] = project(b, nx, ny);
|
|
269
|
+
least = Math.min(least, Math.min(aHigh, bHigh) - Math.max(aLow, bLow));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return least;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** This function gives the least and the greatest projection of the corners of a ring on the direction (`nx`, `ny`). */
|
|
276
|
+
function project(ring: Ring, nx: number, ny: number): readonly [number, number] {
|
|
277
|
+
let low = Infinity;
|
|
278
|
+
let high = -Infinity;
|
|
279
|
+
for (const [x, y] of ring) {
|
|
280
|
+
const v = x * nx + y * ny;
|
|
281
|
+
if (v < low) low = v;
|
|
282
|
+
if (v > high) high = v;
|
|
283
|
+
}
|
|
284
|
+
return [low, high];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* This function tells if each corner of the ring `inner` is inside the convex ring `outer` made smaller by `inset`, with the tolerance `tolerance`.
|
|
289
|
+
* For a convex `outer`, this test is exact: a polygon is inside a convex region when each of its corners is inside.
|
|
290
|
+
* The ring `outer` comes from `convexCorners`, in either direction of its corners.
|
|
291
|
+
*/
|
|
292
|
+
export function cornersInConvex(inner: Ring, outer: Ring, inset = 0, tolerance = 0): boolean {
|
|
293
|
+
const turn = Math.sign(ringTwiceArea(outer));
|
|
294
|
+
for (let i = 0; i < outer.length; i++) {
|
|
295
|
+
const [px, py] = outer[i]!;
|
|
296
|
+
const [qx, qy] = outer[(i + 1) % outer.length]!;
|
|
297
|
+
const length = Math.hypot(qx - px, qy - py);
|
|
298
|
+
if (length === 0) continue;
|
|
299
|
+
// The left normal of a side points inside when the signed area is over 0. The sign of the area chooses the inward normal.
|
|
300
|
+
const nx = (turn * (py - qy)) / length;
|
|
301
|
+
const ny = (turn * (qx - px)) / length;
|
|
302
|
+
const edge = px * nx + py * ny;
|
|
303
|
+
for (const [x, y] of inner) if (x * nx + y * ny - edge < inset - tolerance) return false;
|
|
304
|
+
}
|
|
305
|
+
return true;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** This function gives two times the signed area of a ring, by the shoelace formula, relative to its first corner. */
|
|
309
|
+
function ringTwiceArea(ring: Ring): number {
|
|
310
|
+
if (ring.length === 0) return 0;
|
|
311
|
+
const [ox, oy] = ring[0]!;
|
|
312
|
+
let twice = 0;
|
|
313
|
+
for (let i = 0; i < ring.length; i++) {
|
|
314
|
+
const [ax, ay] = ring[i]!;
|
|
315
|
+
const [bx, by] = ring[(i + 1) % ring.length]!;
|
|
316
|
+
twice += (ax - ox) * (by - oy) - (bx - ox) * (ay - oy);
|
|
317
|
+
}
|
|
318
|
+
return twice;
|
|
319
|
+
}
|
|
320
|
+
|
|
185
321
|
/** This function gives the cross product of `ab` and `ac`. The sign tells the side of `ab` that has `c`. */
|
|
186
322
|
function orient(a: Point, b: Point, c: Point): number {
|
|
187
323
|
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
|
package/src/hash.ts
CHANGED
|
@@ -96,7 +96,7 @@ function byId(a: { readonly id: string }, b: { readonly id: string }): number {
|
|
|
96
96
|
* Thus two packers with the same result in a different order have the same form.
|
|
97
97
|
* The function throws a `RangeError` when `placements`, `overflow` or `moved` has an id two times.
|
|
98
98
|
*
|
|
99
|
-
* A placement has `w` and `
|
|
99
|
+
* A placement has `w`, `h` and `shape` only when the packer set them, so the form of an output without a resize does not change.
|
|
100
100
|
*/
|
|
101
101
|
export function packOutputForm(output: PackOutput): unknown {
|
|
102
102
|
uniqueIds("placements", output.placements.map((p) => p.id));
|
|
@@ -104,7 +104,7 @@ export function packOutputForm(output: PackOutput): unknown {
|
|
|
104
104
|
uniqueIds("moved", output.moved.map((m) => m.id));
|
|
105
105
|
return {
|
|
106
106
|
placements: output.placements
|
|
107
|
-
.map((p) => ({ id: p.id, x: p.x, y: p.y, turn: p.turn ?? 0, ...(p.w === undefined ? {} : { w: p.w }), ...(p.h === undefined ? {} : { h: p.h }) }))
|
|
107
|
+
.map((p) => ({ id: p.id, x: p.x, y: p.y, turn: p.turn ?? 0, ...(p.w === undefined ? {} : { w: p.w }), ...(p.h === undefined ? {} : { h: p.h }), ...(p.shape === undefined ? {} : { shape: p.shape }) }))
|
|
108
108
|
.sort(byId),
|
|
109
109
|
overflow: [...output.overflow].sort(),
|
|
110
110
|
size: { w: output.size.w, h: output.size.h },
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export * from "./geometry.ts";
|
|
2
|
+
export * from "./curves.ts";
|
|
2
3
|
export * from "./shapes.ts";
|
|
3
4
|
export * from "./tolerance.ts";
|
|
4
5
|
export * from "./input.ts";
|
|
@@ -9,6 +10,7 @@ export * from "./turn.ts";
|
|
|
9
10
|
export * from "./resize.ts";
|
|
10
11
|
export * from "./measures.ts";
|
|
11
12
|
export * from "./balance.ts";
|
|
13
|
+
export * from "./cell.ts";
|
|
12
14
|
export * from "./frame.ts";
|
|
13
15
|
export * from "./strategy.ts";
|
|
14
16
|
export * from "./random.ts";
|
|
@@ -21,3 +23,5 @@ export * from "./strategy-space.ts";
|
|
|
21
23
|
export * from "./strategy-catalog.ts";
|
|
22
24
|
export * from "./verdict.ts";
|
|
23
25
|
export * from "./families.ts";
|
|
26
|
+
export * from "./measure-registry.ts";
|
|
27
|
+
export * from "./measure-survey.ts";
|
package/src/input.ts
CHANGED
|
@@ -51,6 +51,11 @@ export interface Resize {
|
|
|
51
51
|
readonly minH?: number;
|
|
52
52
|
readonly maxH?: number;
|
|
53
53
|
readonly aspect?: "keep" | "free";
|
|
54
|
+
/**
|
|
55
|
+
* With `true`, the placement can give the box a shape (`Placement.shape`), for example the polygon cell of a Voronoi treemap.
|
|
56
|
+
* The bounds of the size also limit the bounds of that shape.
|
|
57
|
+
*/
|
|
58
|
+
readonly reshape?: boolean;
|
|
54
59
|
}
|
|
55
60
|
|
|
56
61
|
/** A box of an input. In the packer, its name is item. */
|