@mark1russell7/layout-contract 0.2.2 → 0.2.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/README.md +6 -2
- package/build/index.d.ts +56 -2
- package/build/index.d.ts.map +1 -1
- package/build/index.js +310 -4
- package/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/edges.ts +184 -0
- package/src/index.ts +2 -0
- package/src/input.ts +2 -0
- package/src/random.ts +40 -0
- package/src/rules.ts +86 -4
package/README.md
CHANGED
|
@@ -14,9 +14,11 @@ The package has no runtime dependencies.
|
|
|
14
14
|
| The record `layout-record/1` | `LayoutRecord`, `Stage`, `Supports`, `RunFacts`, `RunEnv`, `toLayoutRecord` |
|
|
15
15
|
| The strategies | `StrategyInfo` |
|
|
16
16
|
| The measures | `MeasureSpec`, `Direction`, `JointMeasureId`, `JOINT_MEASURES`, `JOINT_MOVED_MIN`, `Verdict`, `compareMeasure`, `minEffectOf` |
|
|
17
|
+
| The edges step | `edgeStep`, `EdgeShape`, `EdgeStepParams`, `EDGE_DENSITY`, `EDGE_STEP_VERSION` |
|
|
18
|
+
| The random numbers | `mulberry32`, `fnv1a32`, `stepRandom`, `randomInt` |
|
|
17
19
|
| The turn | `turnBox`, `turnPort`, `turnMargin`, `turnRegion`, `turnSide`, `turnPoint` |
|
|
18
20
|
| The tolerances | `EPS`, `RECORD_EPS`, `Tolerance`, `DEFAULT_TOLERANCE` |
|
|
19
|
-
| The hard rules | `countOverlaps`, `countObstacleHits`, `regionHitsRect`, `countOutside`, `countPortsOffBorder`, `packHard`, `PackHard`, `placedRect`, `checkInput` |
|
|
21
|
+
| The hard rules | `countOverlaps`, `countObstacleHits`, `regionHitsRect`, `rectInRegion`, `countOutside`, `ContainerTest`, `countPortsOffBorder`, `packHard`, `PackHard`, `placedRect`, `checkInput` |
|
|
20
22
|
|
|
21
23
|
## The rules
|
|
22
24
|
|
|
@@ -25,6 +27,8 @@ The package has no runtime dependencies.
|
|
|
25
27
|
- **The gap.** The gap is the free space between two boxes with their margins. Routes use it. Two boxes are `mA + gap + mB` apart.
|
|
26
28
|
- **The ports.** A port can have a side. Without a side, the router picks the side. A fixed port has `x` and `y` on the border of the box, relative to its top-left corner.
|
|
27
29
|
- **The hard rules of a pack.** `no-overlap` counts the pairs of boxes and the pairs of a box and an obstacle. A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`. `checkInput` refuses a locked box without a position. Another box without a placement and not in `overflow` breaks `complete`.
|
|
30
|
+
- **The container rule.** `in-container` counts each box that goes out of the container made smaller by `inset`. The box counts with its margin. By default, a shaped container counts as its bounding box.
|
|
31
|
+
- **The exact container.** Give `{ exactContainer: true }` to `packHard` or `countOutside`. Then a box of a shaped container with the size `fixed` must stay inside the shape. A cut corner, a notch and a hole count. A container with a free side keeps the bounding test. The default changes to the exact test at the next breaking version.
|
|
28
32
|
- **The tolerances.** `EPS` (`1e-6`) is for the float compares in an engine. `RECORD_EPS` (`1e-3`) is for the compares on a written file. A record writes the tolerance of each hard rule in its field `tolerance`. The defaults are `overlap` `0.001` and `through` `0.5`.
|
|
29
33
|
|
|
30
34
|
## An example
|
|
@@ -44,4 +48,4 @@ const placed = applyPack(input, output);
|
|
|
44
48
|
const hard = packHard(input, output);
|
|
45
49
|
```
|
|
46
50
|
|
|
47
|
-
The formats are in `docs/FORMAT.md` of `packing` and `docs/LAYOUT-RECORDS.md` of `highways`. The joint measures are in `docs/JOINT-MEASURES.md` of this repository.
|
|
51
|
+
The formats are in `docs/FORMAT.md` of `packing` and `docs/LAYOUT-RECORDS.md` of `highways`. The joint measures are in `docs/JOINT-MEASURES.md` of this repository, and the joint corpus is in `docs/JOINT-CORPUS.md`.
|
package/build/index.d.ts
CHANGED
|
@@ -187,6 +187,8 @@ export interface LayoutInput {
|
|
|
187
187
|
readonly hash?: string;
|
|
188
188
|
/** The generator of the input. `null` or no value tells that a person made the input. */
|
|
189
189
|
readonly generator?: LayoutGenerator | null;
|
|
190
|
+
/** The steps that changed the input after its generator, in their order. `edgeStep` adds one. */
|
|
191
|
+
readonly steps?: readonly LayoutGenerator[];
|
|
190
192
|
readonly cell?: LayoutCell;
|
|
191
193
|
/** The place of the input in a sequence of changes. */
|
|
192
194
|
readonly step?: number;
|
|
@@ -322,12 +324,23 @@ export declare function placedRect(box: LayoutBox): Rect | undefined;
|
|
|
322
324
|
* A box with a shape counts as its bounding box. That area is larger, thus the count is safe.
|
|
323
325
|
*/
|
|
324
326
|
export declare function countOverlaps(boxes: readonly LayoutBox[], tolerance?: number): number;
|
|
327
|
+
/** The options of the container test of `countOutside` and `packHard`. */
|
|
328
|
+
export interface ContainerTest {
|
|
329
|
+
/**
|
|
330
|
+
* With `true`, a box of a shaped container with the size `fixed` must stay inside the shape, not only inside its bounding box.
|
|
331
|
+
* The default is `false`. The default changes to `true` at the next breaking version.
|
|
332
|
+
*/
|
|
333
|
+
readonly exactContainer?: boolean;
|
|
334
|
+
}
|
|
325
335
|
/**
|
|
326
336
|
* This function counts the placed boxes that go out of the container.
|
|
327
337
|
* Each box with its margin must stay inside the container made smaller by `inset`. Only the fixed sides of the size count. A shaped container counts as its bounding box.
|
|
338
|
+
*
|
|
339
|
+
* With `exactContainer`, a box of a shaped container with the size `fixed` also counts when `rectInRegion` tells that it is not inside the shape.
|
|
340
|
+
* For that test, the box grows by `inset` and becomes smaller by `tolerance` on each side. A shaped container with a free side keeps the bounding test only.
|
|
328
341
|
* An input without a container gives 0.
|
|
329
342
|
*/
|
|
330
|
-
export declare function countOutside(input: LayoutInput, tolerance?: number): number;
|
|
343
|
+
export declare function countOutside(input: LayoutInput, tolerance?: number, options?: ContainerTest): number;
|
|
331
344
|
/** This function counts the fixed ports that are not on the border of their box, with the epsilon of a written file. A port without a side does not count. */
|
|
332
345
|
export declare function countPortsOffBorder(boxes: readonly LayoutBox[], eps?: number): number;
|
|
333
346
|
/** The count of the breaks of each hard rule of a pack. */
|
|
@@ -339,6 +352,11 @@ export interface PackHard {
|
|
|
339
352
|
}
|
|
340
353
|
/** This function tells if the inside of `region` and the inside of `rect` have a common point. */
|
|
341
354
|
export declare function regionHitsRect(region: Region, rect: Rect): boolean;
|
|
355
|
+
/**
|
|
356
|
+
* This function tells if all of `rect` is inside `region`. A point on the border counts as inside. No part of `rect` can overlap a hole.
|
|
357
|
+
* The test of a circle, an ellipse or a polygon accepts an error of `EPS` on the border. A polygon can be concave.
|
|
358
|
+
*/
|
|
359
|
+
export declare function rectInRegion(region: Region, rect: Rect): boolean;
|
|
342
360
|
/**
|
|
343
361
|
* This function counts the pairs of a placed box and an obstacle that overlap by more than `tolerance`.
|
|
344
362
|
* The box counts with its margin. A box with a shape counts as its bounding box.
|
|
@@ -351,8 +369,10 @@ export declare function countObstacleHits(boxes: readonly LayoutBox[], obstacles
|
|
|
351
369
|
* A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`.
|
|
352
370
|
* A locked box without a position in the input is a bad input, not a break. `checkInput` finds it.
|
|
353
371
|
* Another box without a placement that is not in `overflow` breaks `complete`.
|
|
372
|
+
*
|
|
373
|
+
* `options` goes to `countOutside` for `in-container`.
|
|
354
374
|
*/
|
|
355
|
-
export declare function packHard(input: LayoutInput, output: PackOutput, tolerance?: number): PackHard;
|
|
375
|
+
export declare function packHard(input: LayoutInput, output: PackOutput, tolerance?: number, options?: ContainerTest): PackHard;
|
|
356
376
|
/**
|
|
357
377
|
* This function gives the problems of an input file. An empty list tells that the file is good.
|
|
358
378
|
* A problem is a bad input, not a break of a hard rule. Thus an engine refuses the input.
|
|
@@ -439,4 +459,38 @@ export interface StrategyInfo<O = unknown, S extends Supports = Supports> {
|
|
|
439
459
|
/** The value is `true` when the result depends only on the input, the options and the seed. */
|
|
440
460
|
readonly deterministic: boolean;
|
|
441
461
|
}
|
|
462
|
+
/** This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`. */
|
|
463
|
+
export declare function mulberry32(seed: number): () => number;
|
|
464
|
+
/** This function gives the FNV-1a hash of 32 bits of the UTF-8 bytes of a string. */
|
|
465
|
+
export declare function fnv1a32(text: string): number;
|
|
466
|
+
/** This function gives the generator of one step of a seeded generator: `mulberry32(fnv1a32("<seed>:<step>"))`. */
|
|
467
|
+
export declare function stepRandom(seed: number, step: string): () => number;
|
|
468
|
+
/** This function gives a whole number from `lo` to `hi`, both included. */
|
|
469
|
+
export declare function randomInt(r: () => number, lo: number, hi: number): number;
|
|
470
|
+
/**
|
|
471
|
+
* The shape of the edges of `edgeStep`. The values are the cells of `edgeShape`, and `hubs`.
|
|
472
|
+
* `hubs` waits for the next breaking change to become a value of `LayoutCell.edgeShape`.
|
|
473
|
+
*/
|
|
474
|
+
export type EdgeShape = "random" | "clustered" | "hubChain" | "hubs" | "longRange" | "tree" | "bundled";
|
|
475
|
+
/** The parameters of `edgeStep`. */
|
|
476
|
+
export interface EdgeStepParams {
|
|
477
|
+
readonly edgeDensity: "sparse" | "medium" | "dense";
|
|
478
|
+
readonly edgeShape: EdgeShape;
|
|
479
|
+
/** The default is `none`. */
|
|
480
|
+
readonly groups?: "none" | "flat" | "nested";
|
|
481
|
+
/** The default is `free`. */
|
|
482
|
+
readonly ports?: "free" | "sides" | "fixed";
|
|
483
|
+
/** The order of the hubs of `hubs` and `tree`: the largest box first, or a random order. The default is `area`. */
|
|
484
|
+
readonly hubBy?: "area" | "random";
|
|
485
|
+
}
|
|
486
|
+
/** The mean count of the edges of each box for each value of `edgeDensity`. */
|
|
487
|
+
export declare const EDGE_DENSITY: Readonly<Record<EdgeStepParams["edgeDensity"], number>>;
|
|
488
|
+
/** The version of `edgeStep`. A change of its output gives a new version. */
|
|
489
|
+
export declare const EDGE_STEP_VERSION = 1;
|
|
490
|
+
/**
|
|
491
|
+
* This function gives the input with edges, groups and ports from its topology alone: a joint input has no positions before the pack.
|
|
492
|
+
* The random numbers come from the steps `edges` and `ports` of `seed`. The function appends its stamp to `steps`, and removes the old `hash`.
|
|
493
|
+
* The rules of each shape are in `docs/JOINT-CORPUS.md`.
|
|
494
|
+
*/
|
|
495
|
+
export declare function edgeStep(input: LayoutInput, params: EdgeStepParams, seed?: number): LayoutInput;
|
|
442
496
|
//# sourceMappingURL=index.d.ts.map
|
package/build/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/geometry.ts","../src/tolerance.ts","../src/input.ts","../src/output.ts","../src/record.ts","../src/rules.ts","../src/turn.ts","../src/measures.ts","../src/strategy.ts"],"mappings":";YACY;;qBAGC,gBAAgB;iBAEZ;WACN;WACA;;;iBAIM;WACN;WACA;WACA;WACA;;;iBAIM;WACN;WACA;WACA;WACA;;;;;;YAOC;WACG;WAAuB;WAAoB;WAAoB;WAAoB;;WAEnF;WACA;WACA;;WAEA;WAAyB;WAAqB;WAAqB;;WACnE;WAA0B;WAAqB;WAAqB;WAAqB;;;YAG5F,kBAAkB;;wBAGd,YAAY,QAAQ,qBAAqB;;wBAOzC,KAAK,MAAM,MAAM,QAAQ,qBAAqB;;wBAM9C,SAAS,QAAQ,SAAS;;wBAyB1B,UAAU,QAAQ,QAAQ,YAAY,aAAa;;;;;wBAoBnD,UAAU,GAAG,MAAM,GAAG;WAAkB;WAAoB;;;qBCtG/D;;;;;qBAMA;;;;;iBAMI;;WAEN;;WAEA;;;;;;qBAOE,mBAAmB;;;;;;iBCjBf;WACN;WACA,OAAO;WACP;WACA;;;iBAIM;WACN;WACA;WACA;;WAEA;WACA;;WAEA;;WAEA;WACA;WACA;;WAEA,QAAQ;WACR,iBAAiB;;WAEjB,SAAS;;WAET;;WAEA,OAAO,SAAS;;;YAIf,OAAO;;iBAGF;WACN;WACA;WACA;WACA;WACA;WACA,OAAO,SAAS;;;iBAIV;WACN;WACA;WACA;;WAEA;;WAEA;;WAEA,QAAQ;;WAER;;;iBAIM;WACN;WACA,QAAQ;WACR;aAAkB;;;;iBAIZ;WACN;WACA;WACA,QAAQ,SAAS;WACjB;;;iBAIM;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;;iBAIM;WACN;WACA;WACA;WACA;WACA;;WAEA;;WAEA;;WAEA,YAAY;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/geometry.ts","../src/tolerance.ts","../src/input.ts","../src/output.ts","../src/record.ts","../src/rules.ts","../src/turn.ts","../src/measures.ts","../src/strategy.ts","../src/random.ts","../src/edges.ts"],"mappings":";YACY;;qBAGC,gBAAgB;iBAEZ;WACN;WACA;;;iBAIM;WACN;WACA;WACA;WACA;;;iBAIM;WACN;WACA;WACA;WACA;;;;;;YAOC;WACG;WAAuB;WAAoB;WAAoB;WAAoB;;WAEnF;WACA;WACA;;WAEA;WAAyB;WAAqB;WAAqB;;WACnE;WAA0B;WAAqB;WAAqB;WAAqB;;;YAG5F,kBAAkB;;wBAGd,YAAY,QAAQ,qBAAqB;;wBAOzC,KAAK,MAAM,MAAM,QAAQ,qBAAqB;;wBAM9C,SAAS,QAAQ,SAAS;;wBAyB1B,UAAU,QAAQ,QAAQ,YAAY,aAAa;;;;;wBAoBnD,UAAU,GAAG,MAAM,GAAG;WAAkB;WAAoB;;;qBCtG/D;;;;;qBAMA;;;;;iBAMI;;WAEN;;WAEA;;;;;;qBAOE,mBAAmB;;;;;;iBCjBf;WACN;WACA,OAAO;WACP;WACA;;;iBAIM;WACN;WACA;WACA;;WAEA;WACA;;WAEA;;WAEA;WACA;WACA;;WAEA,QAAQ;WACR,iBAAiB;;WAEjB,SAAS;;WAET;;WAEA,OAAO,SAAS;;;YAIf,OAAO;;iBAGF;WACN;WACA;WACA;WACA;WACA;WACA,OAAO,SAAS;;;iBAIV;WACN;WACA;WACA;;WAEA;;WAEA;;WAEA,QAAQ;;WAER;;;iBAIM;WACN;WACA,QAAQ;WACR;aAAkB;;;;iBAIZ;WACN;WACA;WACA,QAAQ,SAAS;WACjB;;;iBAIM;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;;iBAIM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H,WAAW,OAAO;;wBCzSlB,SAAS,MAAM,OAAO;;wBAKtB,UAAU,WAAW,WAAW;;wBAKhC,SAAS,MAAM,MAAM,YAAY;;wBAWjC,WAAW,QAAQ,SAAS;;wBAO5B,WAAW,QAAQ,QAAQ,YAAY;;wBAkBvC,QAAQ,KAAK,YAAY;;YCtD7B;;;;;;iBAOK,YAAY;WAClB,IAAI;WACJ;WACA,WAAW;;WAEX;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;aAAgC;;;WAEhC;;;YAIC;;qBAYC,yBAAyB,YAAY;;qBAarC;;YAGD;;;;;;wBAOI,YAAY,MAAM,KAAK,2BAA2B,YAAO;;;;;;wBAWzD,eAAe,mBAAmB,kBAAkB,MAAM,KAAK,0CAA0C;;;;;iBC1ExG,aAAa,aAAa,UAAU,WAAW;;WAErD;;WAEA;;WAEA;;WAEA,UAAU;;WAEV,UAAU;;WAEV;;;wBCjBK,WAAW;;wBAWX,QAAQ;;wBAoBR,WAAW,cAAc;;wBAKzB,UAAU,iBAAiB,YAAY;;;;;YC7B3C;;iBAGK;WACN;WACA,WAAW;;WAEX;;WAEA;;WAEA;;;qBAIE,cAAc,SAAS,OAAO;;qBAG9B;;;;;;wBAgBG,SAAS,OAAO,aAAa,QAAQ,gBAAgB,gBAAiC"}
|
package/build/index.js
CHANGED
|
@@ -307,11 +307,15 @@ function countOverlaps(boxes, tolerance = DEFAULT_TOLERANCE.overlap) {
|
|
|
307
307
|
/**
|
|
308
308
|
* This function counts the placed boxes that go out of the container.
|
|
309
309
|
* Each box with its margin must stay inside the container made smaller by `inset`. Only the fixed sides of the size count. A shaped container counts as its bounding box.
|
|
310
|
+
*
|
|
311
|
+
* With `exactContainer`, a box of a shaped container with the size `fixed` also counts when `rectInRegion` tells that it is not inside the shape.
|
|
312
|
+
* For that test, the box grows by `inset` and becomes smaller by `tolerance` on each side. A shaped container with a free side keeps the bounding test only.
|
|
310
313
|
* An input without a container gives 0.
|
|
311
314
|
*/
|
|
312
|
-
function countOutside(input, tolerance = DEFAULT_TOLERANCE.overlap) {
|
|
315
|
+
function countOutside(input, tolerance = DEFAULT_TOLERANCE.overlap, options = {}) {
|
|
313
316
|
const c = input.container;
|
|
314
317
|
if (c === void 0) return 0;
|
|
318
|
+
const shape = options.exactContainer === true && c.fixed === "size" ? c.shape : void 0;
|
|
315
319
|
const area = c.shape === void 0 ? {
|
|
316
320
|
x: 0,
|
|
317
321
|
y: 0,
|
|
@@ -329,6 +333,7 @@ function countOutside(input, tolerance = DEFAULT_TOLERANCE.overlap) {
|
|
|
329
333
|
const outX = r.x < area.x + inset - tolerance || r.x + r.w > area.x + area.w - inset + tolerance;
|
|
330
334
|
const outY = r.y < area.y + inset - tolerance || r.y + r.h > area.y + area.h - inset + tolerance;
|
|
331
335
|
if (fixW && outX || fixH && outY) count++;
|
|
336
|
+
else if (shape !== void 0 && !rectInRegion(shape, shrink(grow(r, inset), tolerance))) count++;
|
|
332
337
|
}
|
|
333
338
|
return count;
|
|
334
339
|
}
|
|
@@ -373,6 +378,72 @@ function regionHitsRect(region, rect) {
|
|
|
373
378
|
}
|
|
374
379
|
}
|
|
375
380
|
}
|
|
381
|
+
/**
|
|
382
|
+
* This function tells if all of `rect` is inside `region`. A point on the border counts as inside. No part of `rect` can overlap a hole.
|
|
383
|
+
* The test of a circle, an ellipse or a polygon accepts an error of `EPS` on the border. A polygon can be concave.
|
|
384
|
+
*/
|
|
385
|
+
function rectInRegion(region, rect) {
|
|
386
|
+
const x1 = rect.x + rect.w;
|
|
387
|
+
const y1 = rect.y + rect.h;
|
|
388
|
+
const corners = [
|
|
389
|
+
[rect.x, rect.y],
|
|
390
|
+
[x1, rect.y],
|
|
391
|
+
[x1, y1],
|
|
392
|
+
[rect.x, y1]
|
|
393
|
+
];
|
|
394
|
+
switch (region.kind) {
|
|
395
|
+
case "rect": return rect.x >= region.x && rect.y >= region.y && x1 <= region.x + region.w && y1 <= region.y + region.h;
|
|
396
|
+
case "circle": return corners.every(([x, y]) => inEllipse(region.cx, region.cy, region.r, region.r, x, y));
|
|
397
|
+
case "ellipse": return corners.every(([x, y]) => inEllipse(region.cx, region.cy, region.rx, region.ry, x, y));
|
|
398
|
+
case "polygon": {
|
|
399
|
+
const ring = region.points;
|
|
400
|
+
if (ring.length < 3) return false;
|
|
401
|
+
if (![...corners, [rect.x + rect.w / 2, rect.y + rect.h / 2]].every(([x, y]) => onRing(x, y, ring) || pointInRings(x, y, [ring]))) return false;
|
|
402
|
+
const deep = (x, y) => x > rect.x + 1e-6 && x < x1 - 1e-6 && y > rect.y + 1e-6 && y < y1 - 1e-6;
|
|
403
|
+
for (let i = 0; i < ring.length; i++) {
|
|
404
|
+
const a = ring[i];
|
|
405
|
+
const b = ring[(i + 1) % ring.length];
|
|
406
|
+
const m = clipMid(a[0], a[1], b[0], b[1], rect);
|
|
407
|
+
if (m !== void 0 && deep(m[0], m[1])) return false;
|
|
408
|
+
}
|
|
409
|
+
return (region.holes ?? []).every((hole) => !regionHitsRect({
|
|
410
|
+
kind: "polygon",
|
|
411
|
+
points: hole
|
|
412
|
+
}, rect));
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
/** This function gives the rectangle made smaller by `d` on each side. A side does not become smaller than 0. */
|
|
417
|
+
function shrink(r, d) {
|
|
418
|
+
const dx = Math.min(d, r.w / 2);
|
|
419
|
+
const dy = Math.min(d, r.h / 2);
|
|
420
|
+
return {
|
|
421
|
+
x: r.x + dx,
|
|
422
|
+
y: r.y + dy,
|
|
423
|
+
w: r.w - 2 * dx,
|
|
424
|
+
h: r.h - 2 * dy
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
/** This function tells if a point is inside an ellipse or on its border, with an error of `EPS`. */
|
|
428
|
+
function inEllipse(cx, cy, rx, ry, x, y) {
|
|
429
|
+
if (rx <= 0 || ry <= 0) return false;
|
|
430
|
+
const u = (x - cx) / rx;
|
|
431
|
+
const v = (y - cy) / ry;
|
|
432
|
+
return u * u + v * v <= 1.000001;
|
|
433
|
+
}
|
|
434
|
+
/** This function tells if a point is on a ring of a polygon, with an error of `EPS`. */
|
|
435
|
+
function onRing(x, y, ring) {
|
|
436
|
+
for (let i = 0; i < ring.length; i++) {
|
|
437
|
+
const [ax, ay] = ring[i];
|
|
438
|
+
const [bx, by] = ring[(i + 1) % ring.length];
|
|
439
|
+
const dx = bx - ax;
|
|
440
|
+
const dy = by - ay;
|
|
441
|
+
const len2 = dx * dx + dy * dy;
|
|
442
|
+
const t = len2 === 0 ? 0 : Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / len2));
|
|
443
|
+
if (Math.hypot(x - (ax + t * dx), y - (ay + t * dy)) <= 1e-6) return true;
|
|
444
|
+
}
|
|
445
|
+
return false;
|
|
446
|
+
}
|
|
376
447
|
/** An ellipse with the radii `rx` and `ry` scales to a unit circle. The rectangle scales with it. */
|
|
377
448
|
function circleHitsRect(cx, cy, rx, ry, rect) {
|
|
378
449
|
if (rx <= 0 || ry <= 0) return false;
|
|
@@ -442,8 +513,10 @@ function countObstacleHits(boxes, obstacles, tolerance = DEFAULT_TOLERANCE.overl
|
|
|
442
513
|
* A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`.
|
|
443
514
|
* A locked box without a position in the input is a bad input, not a break. `checkInput` finds it.
|
|
444
515
|
* Another box without a placement that is not in `overflow` breaks `complete`.
|
|
516
|
+
*
|
|
517
|
+
* `options` goes to `countOutside` for `in-container`.
|
|
445
518
|
*/
|
|
446
|
-
function packHard(input, output, tolerance = DEFAULT_TOLERANCE.overlap) {
|
|
519
|
+
function packHard(input, output, tolerance = DEFAULT_TOLERANCE.overlap, options = {}) {
|
|
447
520
|
const after = applyPack(input, output);
|
|
448
521
|
const placed = new Set(output.placements.map((p) => p.id));
|
|
449
522
|
const out = new Set(output.overflow);
|
|
@@ -466,7 +539,7 @@ function packHard(input, output, tolerance = DEFAULT_TOLERANCE.overlap) {
|
|
|
466
539
|
"in-container": countOutside({
|
|
467
540
|
...after,
|
|
468
541
|
boxes: kept
|
|
469
|
-
}, tolerance),
|
|
542
|
+
}, tolerance, options),
|
|
470
543
|
"locked-kept": lockedMoved,
|
|
471
544
|
complete: incomplete
|
|
472
545
|
};
|
|
@@ -608,6 +681,239 @@ function compareMeasure(candidate, baseline, spec) {
|
|
|
608
681
|
if (!(Math.abs(delta) > minEffectOf(spec, candidate, baseline))) return "tie";
|
|
609
682
|
return (spec.direction === "lower" ? delta < 0 : delta > 0) ? "better" : "worse";
|
|
610
683
|
}
|
|
611
|
-
|
|
684
|
+
// src/random.ts
|
|
685
|
+
/** This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`. */
|
|
686
|
+
function mulberry32(seed) {
|
|
687
|
+
let s = seed >>> 0;
|
|
688
|
+
return () => {
|
|
689
|
+
s = s + 1831565813 | 0;
|
|
690
|
+
let t = Math.imul(s ^ s >>> 15, 1 | s);
|
|
691
|
+
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
|
|
692
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
/** This function gives the FNV-1a hash of 32 bits of the UTF-8 bytes of a string. */
|
|
696
|
+
function fnv1a32(text) {
|
|
697
|
+
let h = 2166136261;
|
|
698
|
+
for (const b of utf8(text)) h = Math.imul(h ^ b, 16777619) >>> 0;
|
|
699
|
+
return h;
|
|
700
|
+
}
|
|
701
|
+
/** The UTF-8 bytes of a string. The package has no runtime dependencies, thus it does not use `TextEncoder`. */
|
|
702
|
+
function utf8(text) {
|
|
703
|
+
const bytes = [];
|
|
704
|
+
for (const ch of text) {
|
|
705
|
+
const c = ch.codePointAt(0);
|
|
706
|
+
if (c < 128) bytes.push(c);
|
|
707
|
+
else if (c < 2048) bytes.push(192 | c >> 6, 128 | c & 63);
|
|
708
|
+
else if (c < 65536) bytes.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
|
|
709
|
+
else bytes.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
|
|
710
|
+
}
|
|
711
|
+
return bytes;
|
|
712
|
+
}
|
|
713
|
+
/** This function gives the generator of one step of a seeded generator: `mulberry32(fnv1a32("<seed>:<step>"))`. */
|
|
714
|
+
function stepRandom(seed, step) {
|
|
715
|
+
return mulberry32(fnv1a32(`${seed}:${step}`));
|
|
716
|
+
}
|
|
717
|
+
/** This function gives a whole number from `lo` to `hi`, both included. */
|
|
718
|
+
function randomInt(r, lo, hi) {
|
|
719
|
+
return lo + Math.floor(r() * (hi - lo + 1));
|
|
720
|
+
}
|
|
721
|
+
// src/edges.ts
|
|
722
|
+
/** The mean count of the edges of each box for each value of `edgeDensity`. */
|
|
723
|
+
const EDGE_DENSITY = Object.freeze({
|
|
724
|
+
sparse: .5,
|
|
725
|
+
medium: 1.5,
|
|
726
|
+
dense: 4
|
|
727
|
+
});
|
|
728
|
+
/** The version of `edgeStep`. A change of its output gives a new version. */
|
|
729
|
+
const EDGE_STEP_VERSION = 1;
|
|
730
|
+
const CLUSTER = 8;
|
|
731
|
+
const CHAIN = 32;
|
|
732
|
+
const INSIDE = .85;
|
|
733
|
+
const FAN_SHARE = .6;
|
|
734
|
+
const FIXED_SHARE = .2;
|
|
735
|
+
const COLLECTIONS = [
|
|
736
|
+
"users",
|
|
737
|
+
"orders",
|
|
738
|
+
"items",
|
|
739
|
+
"events"
|
|
740
|
+
];
|
|
741
|
+
const round3 = (x) => Math.round(x * 1e3) / 1e3;
|
|
742
|
+
/**
|
|
743
|
+
* This function gives the input with edges, groups and ports from its topology alone: a joint input has no positions before the pack.
|
|
744
|
+
* The random numbers come from the steps `edges` and `ports` of `seed`. The function appends its stamp to `steps`, and removes the old `hash`.
|
|
745
|
+
* The rules of each shape are in `docs/JOINT-CORPUS.md`.
|
|
746
|
+
*/
|
|
747
|
+
function edgeStep(input, params, seed = input.seed ?? 0) {
|
|
748
|
+
if ((input.edges?.length ?? 0) > 0) throw new RangeError("edgeStep: the input has edges already");
|
|
749
|
+
const full = {
|
|
750
|
+
groups: "none",
|
|
751
|
+
ports: "free",
|
|
752
|
+
hubBy: "area",
|
|
753
|
+
...params
|
|
754
|
+
};
|
|
755
|
+
const n = input.boxes.length;
|
|
756
|
+
const r = stepRandom(seed, "edges");
|
|
757
|
+
const perm = input.boxes.map((_, i) => i);
|
|
758
|
+
for (let i = n - 1; i > 0; i--) {
|
|
759
|
+
const j = randomInt(r, 0, i);
|
|
760
|
+
[perm[i], perm[j]] = [perm[j], perm[i]];
|
|
761
|
+
}
|
|
762
|
+
const clusterOf = new Array(n);
|
|
763
|
+
perm.forEach((box, p) => clusterOf[box] = Math.floor(p / CLUSTER));
|
|
764
|
+
const clusters = Math.ceil(n / CLUSTER);
|
|
765
|
+
const members = (c) => perm.slice(c * CLUSTER, (c + 1) * CLUSTER);
|
|
766
|
+
const collectionOf = full.edgeShape === "bundled" ? clusterOf.map((c) => `${COLLECTIONS[c % COLLECTIONS.length]}-${c}`) : input.boxes.map(() => COLLECTIONS[randomInt(r, 0, COLLECTIONS.length - 1)]);
|
|
767
|
+
const area = (i) => input.boxes[i].w * input.boxes[i].h;
|
|
768
|
+
const rank = full.hubBy === "area" ? input.boxes.map((_, i) => i).sort((a, b) => area(b) - area(a) || a - b) : perm;
|
|
769
|
+
const pairs = [];
|
|
770
|
+
const seen = /* @__PURE__ */ new Set();
|
|
771
|
+
const add = (u, v) => {
|
|
772
|
+
const key = u < v ? `${u}-${v}` : `${v}-${u}`;
|
|
773
|
+
if (u === v || seen.has(key)) return;
|
|
774
|
+
seen.add(key);
|
|
775
|
+
pairs.push([u, v]);
|
|
776
|
+
};
|
|
777
|
+
const anyBox = () => randomInt(r, 0, n - 1);
|
|
778
|
+
const inCluster = (c) => {
|
|
779
|
+
const m = members(c);
|
|
780
|
+
return m[randomInt(r, 0, m.length - 1)];
|
|
781
|
+
};
|
|
782
|
+
const otherCluster = (c) => {
|
|
783
|
+
const o = randomInt(r, 0, clusters - 2);
|
|
784
|
+
return o >= c ? o + 1 : o;
|
|
785
|
+
};
|
|
786
|
+
const target = Math.min(Math.round(n * EDGE_DENSITY[full.edgeDensity]), n * (n - 1) / 2);
|
|
787
|
+
const fill = (pick) => {
|
|
788
|
+
for (let tries = 0; pairs.length < target && tries < target * 30; tries++) add(...pick());
|
|
789
|
+
};
|
|
790
|
+
const clustered = () => {
|
|
791
|
+
const u = anyBox();
|
|
792
|
+
return [u, r() < INSIDE ? inCluster(clusterOf[u]) : anyBox()];
|
|
793
|
+
};
|
|
794
|
+
if (n >= 2) switch (full.edgeShape) {
|
|
795
|
+
case "random":
|
|
796
|
+
fill(() => [anyBox(), anyBox()]);
|
|
797
|
+
break;
|
|
798
|
+
case "clustered":
|
|
799
|
+
fill(clustered);
|
|
800
|
+
break;
|
|
801
|
+
case "longRange":
|
|
802
|
+
fill(() => {
|
|
803
|
+
const u = anyBox();
|
|
804
|
+
return [u, clusters > 1 ? inCluster(otherCluster(clusterOf[u])) : anyBox()];
|
|
805
|
+
});
|
|
806
|
+
break;
|
|
807
|
+
case "hubs":
|
|
808
|
+
fill(() => [anyBox(), rank[Math.floor(n * r() ** 3)]]);
|
|
809
|
+
break;
|
|
810
|
+
case "tree":
|
|
811
|
+
for (let i = 1; i < n; i++) add(rank[randomInt(r, 0, i - 1)], rank[i]);
|
|
812
|
+
break;
|
|
813
|
+
case "hubChain": {
|
|
814
|
+
const k = Math.ceil(n / CHAIN);
|
|
815
|
+
const length = Math.ceil(n / k);
|
|
816
|
+
const chains = Array.from({ length: k }, (_, c) => perm.slice(c * length, (c + 1) * length));
|
|
817
|
+
for (const chain of chains) for (let i = 0; i + 1 < chain.length; i++) add(chain[i], chain[i + 1]);
|
|
818
|
+
const skips = Math.max(0, target - pairs.length);
|
|
819
|
+
for (let s = 0; s < skips; s++) {
|
|
820
|
+
const c = k > 1 ? randomInt(r, 0, k - 2) : 0;
|
|
821
|
+
const from = chains[c];
|
|
822
|
+
const to = chains[k > 1 ? c + 1 : 0];
|
|
823
|
+
const i = randomInt(r, 0, from.length - 1);
|
|
824
|
+
const j = i + Math.floor(from.length / 8) + randomInt(r, 0, Math.floor(from.length / 2));
|
|
825
|
+
if (j < to.length) add(from[i], to[j]);
|
|
826
|
+
}
|
|
827
|
+
break;
|
|
828
|
+
}
|
|
829
|
+
case "bundled":
|
|
830
|
+
for (let rounds = 0; pairs.length < target * FAN_SHARE && clusters > 1 && rounds < target; rounds++) {
|
|
831
|
+
const u = anyBox();
|
|
832
|
+
const c = otherCluster(clusterOf[u]);
|
|
833
|
+
const fan = randomInt(r, 4, 15);
|
|
834
|
+
for (let f = 0; f < fan && pairs.length < target; f++) add(u, inCluster(c));
|
|
835
|
+
}
|
|
836
|
+
fill(clustered);
|
|
837
|
+
}
|
|
838
|
+
const rp = stepRandom(seed, "ports");
|
|
839
|
+
const ports = input.boxes.map((b) => [...b.ports ?? []]);
|
|
840
|
+
const portOn = (box, id, side, fixed) => {
|
|
841
|
+
if (!fixed) return {
|
|
842
|
+
id,
|
|
843
|
+
side
|
|
844
|
+
};
|
|
845
|
+
const along = round3(rp() * (side === "top" || side === "bottom" ? box.w : box.h));
|
|
846
|
+
const at = {
|
|
847
|
+
top: [along, 0],
|
|
848
|
+
bottom: [along, box.h],
|
|
849
|
+
left: [0, along],
|
|
850
|
+
right: [box.w, along]
|
|
851
|
+
}[side];
|
|
852
|
+
return {
|
|
853
|
+
id,
|
|
854
|
+
side,
|
|
855
|
+
x: at[0],
|
|
856
|
+
y: at[1]
|
|
857
|
+
};
|
|
858
|
+
};
|
|
859
|
+
const out = /* @__PURE__ */ new Set();
|
|
860
|
+
if (full.ports === "fixed") input.boxes.forEach((box, i) => {
|
|
861
|
+
if (rp() >= FIXED_SHARE) return;
|
|
862
|
+
const side = SIDES[randomInt(rp, 0, 3)];
|
|
863
|
+
ports[i].push(portOn(box, "out", side, true));
|
|
864
|
+
out.add(i);
|
|
865
|
+
});
|
|
866
|
+
const edges = pairs.map(([u, v], k) => {
|
|
867
|
+
const id = `e${k}`;
|
|
868
|
+
const s = input.boxes[u];
|
|
869
|
+
const t = input.boxes[v];
|
|
870
|
+
let ends = {};
|
|
871
|
+
if (full.ports === "sides") {
|
|
872
|
+
ports[u].push(portOn(s, `${id}.s`, SIDES[randomInt(rp, 0, 3)], false));
|
|
873
|
+
ports[v].push(portOn(t, `${id}.t`, SIDES[randomInt(rp, 0, 3)], false));
|
|
874
|
+
ends = {
|
|
875
|
+
sourcePort: `${id}.s`,
|
|
876
|
+
targetPort: `${id}.t`
|
|
877
|
+
};
|
|
878
|
+
} else if (out.has(u)) ends = { sourcePort: "out" };
|
|
879
|
+
return {
|
|
880
|
+
id,
|
|
881
|
+
source: s.id,
|
|
882
|
+
target: t.id,
|
|
883
|
+
...ends,
|
|
884
|
+
data: { collection: collectionOf[v] }
|
|
885
|
+
};
|
|
886
|
+
});
|
|
887
|
+
const boxes = input.boxes.map((box, i) => {
|
|
888
|
+
const c = clusterOf[i];
|
|
889
|
+
const group = full.groups === "none" ? void 0 : `g${c}`;
|
|
890
|
+
const path = full.groups === "nested" ? `G${Math.floor(c / 4)}/g${c}` : group;
|
|
891
|
+
return {
|
|
892
|
+
...box,
|
|
893
|
+
...group === void 0 ? {} : {
|
|
894
|
+
group,
|
|
895
|
+
data: {
|
|
896
|
+
...box.data,
|
|
897
|
+
group: path
|
|
898
|
+
}
|
|
899
|
+
},
|
|
900
|
+
...ports[i].length === 0 ? {} : { ports: ports[i] }
|
|
901
|
+
};
|
|
902
|
+
});
|
|
903
|
+
const stamp = {
|
|
904
|
+
name: "edges",
|
|
905
|
+
version: 1,
|
|
906
|
+
params: { ...full },
|
|
907
|
+
seed
|
|
908
|
+
};
|
|
909
|
+
const { hash: _old, ...rest } = input;
|
|
910
|
+
return {
|
|
911
|
+
...rest,
|
|
912
|
+
boxes,
|
|
913
|
+
edges,
|
|
914
|
+
steps: [...input.steps ?? [], stamp]
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
export { DEFAULT_TOLERANCE, EDGE_DENSITY, EDGE_STEP_VERSION, EPS, JOINT_MEASURES, JOINT_MOVED_MIN, RECORD_EPS, SIDES, applyPack, boundsOf, checkInput, compareMeasure, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, edgeStep, fnv1a32, grow, marginSides, minEffectOf, mulberry32, overlapOf, packHard, placedRect, randomInt, rectInRegion, regionHitsRect, stepRandom, toLayoutRecord, toPackInput, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnSide };
|
|
612
918
|
|
|
613
919
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/geometry.ts","../src/tolerance.ts","../src/input.ts","../src/turn.ts","../src/output.ts","../src/record.ts","../src/rules.ts","../src/measures.ts"],"sourcesContent":["/** A side of a box. The y axis points down, so `top` has the smallest y. */\nexport type Side = \"top\" | \"right\" | \"bottom\" | \"left\";\n\n/** The sides in clockwise order, from the top. */\nexport const SIDES: readonly Side[] = [\"top\", \"right\", \"bottom\", \"left\"];\n\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\n/** A rectangle: its top-left corner and its size. */\nexport interface Rect {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n}\n\n/** A value for each side of a box. */\nexport interface Sides {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\n/**\n * A region. The forms and the rules are those of `docs/FORMAT.md` of `packing`.\n * A ring of a polygon closes without a copy of its first point.\n */\nexport type Region =\n | { readonly kind: \"rect\"; readonly x: number; readonly y: number; readonly w: number; readonly h: number }\n | {\n readonly kind: \"polygon\";\n readonly points: readonly (readonly [number, number])[];\n readonly holes?: readonly (readonly (readonly [number, number])[])[];\n }\n | { readonly kind: \"circle\"; readonly cx: number; readonly cy: number; readonly r: number }\n | { readonly kind: \"ellipse\"; readonly cx: number; readonly cy: number; readonly rx: number; readonly ry: number };\n\n/** A margin: one value for the four sides, or one value for each side. */\nexport type Margin = number | Sides;\n\n/** This function gives the value of each side of a margin. No margin gives 0 on each side. */\nexport function marginSides(margin: Margin | undefined): Sides {\n if (margin === undefined) return { top: 0, right: 0, bottom: 0, left: 0 };\n if (typeof margin === \"number\") return { top: margin, right: margin, bottom: margin, left: margin };\n return margin;\n}\n\n/** This function gives the rectangle made larger by the margin on each side. */\nexport function grow(rect: Rect, margin: Margin | undefined): Rect {\n const m = marginSides(margin);\n return { x: rect.x - m.left, y: rect.y - m.top, w: rect.w + m.left + m.right, h: rect.h + m.top + m.bottom };\n}\n\n/** This function gives the bounding box of a region. */\nexport function boundsOf(region: Region): Rect {\n switch (region.kind) {\n case \"rect\":\n return { x: region.x, y: region.y, w: region.w, h: region.h };\n case \"circle\":\n return { x: region.cx - region.r, y: region.cy - region.r, w: 2 * region.r, h: 2 * region.r };\n case \"ellipse\":\n return { x: region.cx - region.rx, y: region.cy - region.ry, w: 2 * region.rx, h: 2 * region.ry };\n case \"polygon\": {\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (const [x, y] of region.points) {\n x0 = Math.min(x0, x);\n y0 = Math.min(y0, y);\n x1 = Math.max(x1, x);\n y1 = Math.max(y1, y);\n }\n return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };\n }\n }\n}\n\n/** This function gives the region moved by `dx` and `dy`. */\nexport function translate(region: Region, dx: number, dy: number): Region {\n switch (region.kind) {\n case \"rect\":\n return { ...region, x: region.x + dx, y: region.y + dy };\n case \"circle\":\n case \"ellipse\":\n return { ...region, cx: region.cx + dx, cy: region.cy + dy };\n case \"polygon\": {\n const move = (ring: readonly (readonly [number, number])[]): [number, number][] => ring.map(([x, y]) => [x + dx, y + dy]);\n return region.holes === undefined\n ? { kind: \"polygon\", points: move(region.points) }\n : { kind: \"polygon\", points: move(region.points), holes: region.holes.map(move) };\n }\n }\n}\n\n/**\n * This function gives the overlap of the insides of two rectangles on each axis.\n * A value of 0 or less on an axis is no overlap. Two rectangles with a common edge have an overlap of 0.\n */\nexport function overlapOf(a: Rect, b: Rect): { readonly x: number; readonly y: number } {\n return {\n x: Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x),\n y: Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y),\n };\n}\n","/** The epsilon for the float compares in an engine. */\nexport const EPS = 1e-6;\n\n/**\n * The epsilon for the float compares on a written file. A file rounds each number to 3 decimals,\n * so a difference of two values can move by up to 0.001.\n */\nexport const RECORD_EPS = 1e-3;\n\n/**\n * The tolerance of each hard rule, in layout units. A record writes the tolerance that its run used,\n * in its field `tolerance`, next to `hard`.\n */\nexport interface Tolerance {\n /** Two boxes with their margins break `no-overlap` when their insides overlap by more than this on each axis. */\n readonly overlap: number;\n /** A route breaks `no-pass-through` when a part longer than this is inside a box made this much smaller. */\n readonly through: number;\n}\n\n/**\n * The default tolerance of each rule. The packer is exact, so `overlap` is one unit of the rounding.\n * Routes are sampled curves that follow the margin line, so `through` is larger.\n */\nexport const DEFAULT_TOLERANCE: Tolerance = Object.freeze({ overlap: 0.001, through: 0.5 });\n","import type { Margin, Region, Side } from \"./geometry.ts\";\n\n/**\n * A port of a box: a place where edges go into the box.\n * With `x` and `y`, the port is fixed on the border of the box, relative to its top-left corner.\n * Without them, the router places the port on its `side`. Without a side, the router picks the side.\n */\nexport interface Port {\n readonly id: string;\n readonly side?: Side;\n readonly x?: number;\n readonly y?: number;\n}\n\n/** A box of an input. In the packer, its name is item. */\nexport interface LayoutBox {\n readonly id: string;\n readonly w: number;\n readonly h: number;\n /** The packer writes the position. The router reads it. */\n readonly x?: number;\n readonly y?: number;\n /** A locked box keeps `x` and `y`. The packer reads it as an obstacle. */\n readonly locked?: boolean;\n /** The reading order. Without it, the order of the array is the rank. */\n readonly rank?: number;\n readonly parent?: string;\n readonly group?: string;\n /** A region relative to the origin of the box. Without it, the box is the rectangle `w` by `h`. */\n readonly shape?: Region;\n readonly ports?: readonly Port[];\n /** A ring around the box. No other box enters it. Only a route from a port of the box enters it, at a right angle. */\n readonly margin?: Margin;\n /** The packer can turn the box by 90 degrees. The output has the turned box and ports. */\n readonly turnable?: boolean;\n /** The free data of the node. The grouping rule `keys` of `highways` reads `data.group`. */\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/** The packer name of a box. It is the same type. */\nexport type Item = LayoutBox;\n\n/** An edge between two boxes, with optional ports. */\nexport interface LayoutEdge {\n readonly id: string;\n readonly source: string;\n readonly target: string;\n readonly sourcePort?: string;\n readonly targetPort?: string;\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/** The container. `fixed` tells which sides of the size stay. */\nexport interface LayoutContainer {\n readonly w?: number;\n readonly h?: number;\n readonly fixed: \"size\" | \"width\" | \"height\" | \"none\";\n /** The target aspect: the width divided by the height. The default is 1. */\n readonly aspect?: number;\n /** The weight of the aspect error in the objective. 0 gives the least area. The default is 1. */\n readonly aspectWeight?: number;\n /** The shape. Without it, the container is the rectangle from 0, 0 to `w`, `h`. */\n readonly shape?: Region;\n /** The space between the border and the boxes with their margins. */\n readonly inset?: number;\n}\n\n/** An area that boxes and routes avoid. Without `move`, it stays. With `move`, the packer can move it for `cost` times the distance. */\nexport interface Obstacle {\n readonly id: string;\n readonly region: Region;\n readonly move?: { readonly cost: number };\n}\n\n/** The generator of an input. The same name, version, parameters and seed give the same file, byte for byte. */\nexport interface LayoutGenerator {\n readonly name: string;\n readonly version: number;\n readonly params: Readonly<Record<string, unknown>>;\n readonly seed: number;\n}\n\n/** The cell of an input in the taxonomy: one value for each dimension. The dimensions are in `docs/FORMAT.md` of `packing`. */\nexport interface LayoutCell {\n readonly containerSize?: \"fixed\" | \"freeHeight\" | \"freeWidth\" | \"freeAspect\" | \"freeArea\";\n readonly containerShape?: \"rect\" | \"convex\" | \"polygon\" | \"circle\" | \"ellipse\" | \"holes\";\n readonly obstacles?: \"none\" | \"center\" | \"scattered\" | \"wall\" | \"corridors\" | \"touching\" | \"edge\";\n readonly sizes?: \"identical\" | \"uniform\" | \"heavyTail\" | \"bimodal\" | \"extremeAspect\" | \"nearIdentical\";\n readonly count?: \"1\" | \"10\" | \"100\" | \"1k\" | \"10k\";\n readonly mode?: \"offline\" | \"online\" | \"incremental\";\n readonly edgeDensity?: \"sparse\" | \"medium\" | \"dense\";\n readonly edgeShape?: \"random\" | \"clustered\" | \"hubChain\" | \"longRange\" | \"tree\" | \"bundled\";\n readonly groups?: \"none\" | \"flat\" | \"nested\";\n readonly ports?: \"free\" | \"sides\" | \"fixed\";\n}\n\n/** An input of the corpus: the format `layout-input/1`. */\nexport interface LayoutInput {\n readonly schema: \"layout-input/1\";\n readonly id: string;\n readonly set?: string;\n readonly family?: string;\n readonly seed?: number;\n /** The origin: `made-up`, `published:<set>` or `known-best:<construction>`. */\n readonly source?: string;\n /** The first 16 hex characters of the SHA-256 of the canonical file without this field. */\n readonly hash?: string;\n /** The generator of the input. `null` or no value tells that a person made the input. */\n readonly generator?: LayoutGenerator | null;\n readonly cell?: LayoutCell;\n /** The place of the input in a sequence of changes. */\n readonly step?: number;\n /** A router input can have no container. */\n readonly container?: LayoutContainer;\n /** The free space between two boxes with their margins. Routes use it. */\n readonly gap?: number;\n readonly boxes: readonly LayoutBox[];\n readonly edges?: readonly LayoutEdge[];\n readonly obstacles?: readonly Obstacle[];\n /**\n * A variant names its base input and its change.\n * With `packed`, the variant is the packed output of its base input: the router routes the positions of that pack.\n */\n readonly base?: string;\n readonly change?: \"add\" | \"remove\" | \"resize\" | \"reorder\" | \"packed\";\n}\n\n/** The input of a packer: a `layout-input/1` file without the edges. */\nexport interface PackInput {\n readonly container: LayoutContainer;\n readonly items: readonly Item[];\n readonly obstacles?: readonly Obstacle[];\n readonly gap?: number;\n}\n\n/** This function gives the packer input of a file. An input without a container gets `{ fixed: \"none\" }`, so the packer picks the size. */\nexport function toPackInput(input: LayoutInput): PackInput {\n return {\n container: input.container ?? { fixed: \"none\" },\n items: input.boxes,\n ...(input.obstacles === undefined ? {} : { obstacles: input.obstacles }),\n ...(input.gap === undefined ? {} : { gap: input.gap }),\n };\n}\n","import { SIDES, marginSides, type Margin, type Region, type Side } from \"./geometry.ts\";\nimport type { LayoutBox, Port } from \"./input.ts\";\n\n/*\n * The turn: 90 degrees clockwise, with the y axis down. The turned box has `w` and `h` swapped,\n * and its top-left corner stays at the position of the box. A point (px, py) of a box of height h\n * goes to (h - py, px). Thus the top-left corner goes to the top-right corner, and each side moves\n * one step clockwise: top to right, right to bottom, bottom to left, left to top.\n */\n\n/** This function gives the side after a turn of 90 degrees clockwise. */\nexport function turnSide(side: Side): Side {\n return SIDES[(SIDES.indexOf(side) + 1) % 4]!;\n}\n\n/** This function gives a point of a box of height `h` after the turn. */\nexport function turnPoint(x: number, y: number, h: number): [number, number] {\n return [h - y, x];\n}\n\n/** This function gives a port of a box of height `h` after the turn. Each value of the port turns, also a port with only `x` or only `y`. */\nexport function turnPort(port: Port, h: number): Port {\n const { side, x, y, ...rest } = port;\n return {\n ...rest,\n ...(side === undefined ? {} : { side: turnSide(side) }),\n ...(y === undefined ? {} : { x: h - y }),\n ...(x === undefined ? {} : { y: x }),\n };\n}\n\n/** This function gives a margin after the turn: the value of each side moves one side clockwise. */\nexport function turnMargin(margin: Margin): Margin {\n if (typeof margin === \"number\") return margin;\n const m = marginSides(margin);\n return { top: m.left, right: m.top, bottom: m.right, left: m.bottom };\n}\n\n/** This function gives a region relative to the origin of a box of height `h` after the turn. */\nexport function turnRegion(region: Region, h: number): Region {\n switch (region.kind) {\n case \"rect\":\n return { kind: \"rect\", x: h - region.y - region.h, y: region.x, w: region.h, h: region.w };\n case \"circle\":\n return { ...region, cx: h - region.cy, cy: region.cx };\n case \"ellipse\":\n return { kind: \"ellipse\", cx: h - region.cy, cy: region.cx, rx: region.ry, ry: region.rx };\n case \"polygon\": {\n const turn = (ring: readonly (readonly [number, number])[]): [number, number][] => ring.map(([x, y]) => turnPoint(x, y, h));\n return region.holes === undefined\n ? { kind: \"polygon\", points: turn(region.points) }\n : { kind: \"polygon\", points: turn(region.points), holes: region.holes.map(turn) };\n }\n }\n}\n\n/** This function gives a box after the turn: the size, the ports, the margin and the shape turn. The position stays. */\nexport function turnBox(box: LayoutBox): LayoutBox {\n return {\n ...box,\n w: box.h,\n h: box.w,\n ...(box.ports === undefined ? {} : { ports: box.ports.map((p) => turnPort(p, box.h)) }),\n ...(box.margin === undefined ? {} : { margin: turnMargin(box.margin) }),\n ...(box.shape === undefined ? {} : { shape: turnRegion(box.shape, box.h) }),\n };\n}\n","import { boundsOf, translate } from \"./geometry.ts\";\nimport type { LayoutInput } from \"./input.ts\";\nimport { turnBox } from \"./turn.ts\";\n\n/** The position of one item. `turn` is 90 when the packer turned a turnable item. */\nexport interface Placement {\n readonly id: string;\n readonly x: number;\n readonly y: number;\n readonly turn?: 0 | 90;\n}\n\n/** The facts of one stage of a strategy, for the records and the site. */\nexport interface StageTrace {\n readonly id: string;\n readonly ms?: number;\n readonly measures?: Readonly<Record<string, number>>;\n}\n\n/** The output of a packer. It does not change the input. */\nexport interface PackOutput {\n readonly placements: readonly Placement[];\n /** The ids of the items that the packer did not place. */\n readonly overflow: readonly string[];\n /** The size of the container after the pack. For a free size, the size that the search found. */\n readonly size: { readonly w: number; readonly h: number };\n /** The new top-left corner of the bounding box of each obstacle that moved. */\n readonly moved: readonly { readonly id: string; readonly x: number; readonly y: number }[];\n readonly trace?: readonly StageTrace[];\n}\n\n/**\n * This function gives the input with the output of a packer applied. Each placed box gets its position.\n * A turned box gets its turned size, ports, margin and shape. Each moved obstacle moves.\n * The container gets the size of the output. The router reads this result. It does not read `turn`.\n */\nexport function applyPack(input: LayoutInput, output: PackOutput): LayoutInput {\n const at = new Map(output.placements.map((p) => [p.id, p]));\n const moved = new Map(output.moved.map((m) => [m.id, m]));\n const boxes = input.boxes.map((box) => {\n const p = at.get(box.id);\n if (p === undefined) return box;\n const turned = p.turn === 90 ? turnBox(box) : box;\n return { ...turned, x: p.x, y: p.y };\n });\n const obstacles = input.obstacles?.map((o) => {\n const m = moved.get(o.id);\n if (m === undefined) return o;\n const b = boundsOf(o.region);\n return { ...o, region: translate(o.region, m.x - b.x, m.y - b.y) };\n });\n return {\n ...input,\n container: { ...(input.container ?? { fixed: \"none\" }), w: output.size.w, h: output.size.h },\n boxes,\n ...(obstacles === undefined ? {} : { obstacles }),\n };\n}\n","import type { Tolerance } from \"./tolerance.ts\";\nimport type { LayoutInput } from \"./input.ts\";\n\n/** The stage of a record: the packer, the router, or both together. */\nexport type Stage = \"pack\" | \"route\" | \"joint\";\n\n/** One run of one strategy on one input and seed: the format `layout-record/1`. A run writes one line of JSON Lines. */\nexport interface LayoutRecord {\n readonly schema: \"layout-record/1\";\n readonly stage: Stage;\n readonly step: string;\n readonly strategy: string;\n /** The options in full, with the defaults. */\n readonly options: Readonly<Record<string, unknown>>;\n readonly corpus: string;\n /** The id of the input. */\n readonly input: string;\n /** The `hash` of the input file. */\n readonly inputHash: string;\n readonly set: string;\n readonly seed: number;\n readonly nodes: number;\n readonly edges: number;\n /** The value of each measure, by its name: `pack.*`, `route.*` or `joint.*`. */\n readonly measures: Readonly<Record<string, number>>;\n /** The count of the breaks of each hard rule. A good run has 0 for each rule. */\n readonly hard: Readonly<Record<string, number>>;\n /** The tolerance of each hard rule of the run. */\n readonly tolerance?: Readonly<Partial<Tolerance>>;\n /** `true` when two runs with the same seed give the same positions. */\n readonly deterministic: boolean;\n /** The id of the prediction that was written before the run. */\n readonly prediction?: string;\n /** The median of `msRuns`, or the time of the one run. */\n readonly ms: number;\n /** The time of each timed repeat, in milliseconds. */\n readonly msRuns?: readonly number[];\n /**\n * The first 16 hex characters of the SHA-256 of the canonical output of the stage.\n * The packer hashes its placements by the order of the ids. The router hashes its routes by the order of the edge ids.\n */\n readonly outputHash?: string;\n /** The facts of the computer of the run. */\n readonly env?: RunEnv;\n /** The reason when the strategy did not run, for example an input over its `maxNodes`. Then the record has no measures. */\n readonly skipped?: string;\n readonly commit?: string;\n}\n\n/**\n * The values that a strategy supports, for each dimension of a taxonomy.\n * The dimension names are in `docs/FORMAT.md` of `packing` and `docs/LAYOUT-RECORDS.md` of `highways`.\n */\nexport type Supports = Readonly<Record<string, readonly string[]>>;\n\n/** The facts of the computer of a run. */\nexport interface RunEnv {\n readonly node: string;\n readonly os: string;\n readonly arch: string;\n /** The name of the runner, for example `ubuntu-latest` or `local`. */\n readonly runner: string;\n /** The model of the processor. */\n readonly cpu: string;\n /** The count of the logical processors. */\n readonly cpus: number;\n}\n\n/** The facts of a run that the input does not give. */\nexport type RunFacts = Omit<LayoutRecord, \"schema\" | \"input\" | \"inputHash\" | \"set\" | \"nodes\" | \"edges\">;\n\n/** This function gives the record of a run. The input gives its id, its hash, its set and the counts of the nodes and the edges. */\nexport function toLayoutRecord(input: LayoutInput, run: RunFacts): LayoutRecord {\n return {\n schema: \"layout-record/1\",\n ...run,\n input: input.id,\n inputHash: input.hash ?? \"\",\n set: input.set ?? \"\",\n nodes: input.boxes.length,\n edges: input.edges?.length ?? 0,\n };\n}\n","import { boundsOf, grow, overlapOf, type Rect, type Region } from \"./geometry.ts\";\nimport type { LayoutBox, LayoutInput, Obstacle } from \"./input.ts\";\nimport { applyPack, type PackOutput } from \"./output.ts\";\nimport { DEFAULT_TOLERANCE, RECORD_EPS } from \"./tolerance.ts\";\n\n/** This function gives the area of a placed box: its shape or its rectangle, at its position. A box without a position gives `undefined`. */\nexport function placedRect(box: LayoutBox): Rect | undefined {\n if (box.x === undefined || box.y === undefined) return undefined;\n if (box.shape === undefined) return { x: box.x, y: box.y, w: box.w, h: box.h };\n const b = boundsOf(box.shape);\n return { x: box.x + b.x, y: box.y + b.y, w: b.w, h: b.h };\n}\n\n/**\n * This function counts the pairs of placed boxes whose insides, with their margins, overlap by more than `tolerance` on each axis.\n * A box with a shape counts as its bounding box. That area is larger, thus the count is safe.\n */\nexport function countOverlaps(boxes: readonly LayoutBox[], tolerance: number = DEFAULT_TOLERANCE.overlap): number {\n const rects: Rect[] = [];\n for (const box of boxes) {\n const r = placedRect(box);\n if (r !== undefined) rects.push(grow(r, box.margin));\n }\n rects.sort((a, b) => a.x - b.x);\n let count = 0;\n for (let i = 0; i < rects.length; i++) {\n const a = rects[i]!;\n for (let j = i + 1; j < rects.length; j++) {\n const b = rects[j]!;\n if (b.x >= a.x + a.w - tolerance) break;\n const o = overlapOf(a, b);\n if (o.x > tolerance && o.y > tolerance) count++;\n }\n }\n return count;\n}\n\n/**\n * This function counts the placed boxes that go out of the container.\n * Each box with its margin must stay inside the container made smaller by `inset`. Only the fixed sides of the size count. A shaped container counts as its bounding box.\n * An input without a container gives 0.\n */\nexport function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOLERANCE.overlap): number {\n const c = input.container;\n if (c === undefined) return 0;\n const area = c.shape === undefined ? { x: 0, y: 0, w: c.w ?? Infinity, h: c.h ?? Infinity } : boundsOf(c.shape);\n const inset = c.inset ?? 0;\n const fixW = c.fixed === \"size\" || c.fixed === \"width\";\n const fixH = c.fixed === \"size\" || c.fixed === \"height\";\n let count = 0;\n for (const box of input.boxes) {\n const r0 = placedRect(box);\n if (r0 === undefined) continue;\n const r = grow(r0, box.margin);\n const outX = r.x < area.x + inset - tolerance || r.x + r.w > area.x + area.w - inset + tolerance;\n const outY = r.y < area.y + inset - tolerance || r.y + r.h > area.y + area.h - inset + tolerance;\n if ((fixW && outX) || (fixH && outY)) count++;\n }\n return count;\n}\n\n/** This function counts the fixed ports that are not on the border of their box, with the epsilon of a written file. A port without a side does not count. */\nexport function countPortsOffBorder(boxes: readonly LayoutBox[], eps: number = RECORD_EPS): number {\n let count = 0;\n for (const box of boxes) {\n for (const p of box.ports ?? []) {\n if (p.x === undefined || p.y === undefined || p.side === undefined) continue;\n const along = p.side === \"top\" || p.side === \"bottom\" ? p.x : p.y;\n const length = p.side === \"top\" || p.side === \"bottom\" ? box.w : box.h;\n const across = { top: p.y, bottom: p.y - box.h, left: p.x, right: p.x - box.w }[p.side];\n if (Math.abs(across) > eps || along < -eps || along > length + eps) count++;\n }\n }\n return count;\n}\n\n/** The count of the breaks of each hard rule of a pack. */\nexport interface PackHard {\n readonly \"no-overlap\": number;\n readonly \"in-container\": number;\n readonly \"locked-kept\": number;\n readonly complete: number;\n}\n\n/** This function tells if the inside of `region` and the inside of `rect` have a common point. */\nexport function regionHitsRect(region: Region, rect: Rect): boolean {\n if (rect.w <= 0 || rect.h <= 0) return false;\n switch (region.kind) {\n case \"rect\": {\n const o = overlapOf(region, rect);\n return o.x > 0 && o.y > 0;\n }\n case \"circle\":\n return circleHitsRect(region.cx, region.cy, region.r, region.r, rect);\n case \"ellipse\":\n return circleHitsRect(region.cx, region.cy, region.rx, region.ry, rect);\n case \"polygon\": {\n const rings = [region.points, ...(region.holes ?? [])];\n const inside = (x: number, y: number): boolean => x > rect.x && x < rect.x + rect.w && y > rect.y && y < rect.y + rect.h;\n if (region.points.some(([x, y]) => inside(x, y))) return true;\n for (const ring of rings) {\n for (let i = 0; i < ring.length; i++) {\n const a = ring[i]!;\n const b = ring[(i + 1) % ring.length]!;\n const m = clipMid(a[0], a[1], b[0], b[1], rect);\n if (m !== undefined && inside(m[0], m[1])) return true;\n }\n }\n return pointInRings(rect.x + rect.w / 2, rect.y + rect.h / 2, rings);\n }\n }\n}\n\n/** An ellipse with the radii `rx` and `ry` scales to a unit circle. The rectangle scales with it. */\nfunction circleHitsRect(cx: number, cy: number, rx: number, ry: number, rect: Rect): boolean {\n if (rx <= 0 || ry <= 0) return false;\n const x0 = (rect.x - cx) / rx;\n const x1 = (rect.x + rect.w - cx) / rx;\n const y0 = (rect.y - cy) / ry;\n const y1 = (rect.y + rect.h - cy) / ry;\n const dx = Math.max(x0, 0, -x1);\n const dy = Math.max(y0, 0, -y1);\n return dx * dx + dy * dy < 1;\n}\n\n/** This function gives the middle of the part of a segment inside a rectangle, or `undefined` when that part is a point or empty. */\nfunction clipMid(ax: number, ay: number, bx: number, by: number, r: Rect): readonly [number, number] | undefined {\n let t0 = 0;\n let t1 = 1;\n const dx = bx - ax;\n const dy = by - ay;\n const edges: readonly (readonly [number, number])[] = [\n [-dx, ax - r.x],\n [dx, r.x + r.w - ax],\n [-dy, ay - r.y],\n [dy, r.y + r.h - ay],\n ];\n for (const [p, q] of edges) {\n if (p === 0) {\n if (q < 0) return undefined;\n } else if (p < 0) {\n t0 = Math.max(t0, q / p);\n } else {\n t1 = Math.min(t1, q / p);\n }\n }\n if (t1 <= t0) return undefined;\n const t = (t0 + t1) / 2;\n return [ax + t * dx, ay + t * dy];\n}\n\n/** The even-odd rule over the outer ring and the holes. */\nfunction pointInRings(x: number, y: number, rings: readonly (readonly (readonly [number, number])[])[]): boolean {\n let inside = false;\n for (const ring of rings) {\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n const [xi, yi] = ring[i]!;\n const [xj, yj] = ring[j]!;\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;\n }\n }\n return inside;\n}\n\n/**\n * This function counts the pairs of a placed box and an obstacle that overlap by more than `tolerance`.\n * The box counts with its margin. A box with a shape counts as its bounding box.\n */\nexport function countObstacleHits(\n boxes: readonly LayoutBox[],\n obstacles: readonly Obstacle[] | undefined,\n tolerance: number = DEFAULT_TOLERANCE.overlap,\n): number {\n if (obstacles === undefined || obstacles.length === 0) return 0;\n let count = 0;\n for (const box of boxes) {\n const r0 = placedRect(box);\n if (r0 === undefined) continue;\n const r = grow(r0, box.margin);\n const small = { x: r.x + tolerance, y: r.y + tolerance, w: r.w - 2 * tolerance, h: r.h - 2 * tolerance };\n for (const o of obstacles) if (regionHitsRect(o.region, small)) count++;\n }\n return count;\n}\n\n/**\n * This function gives the count of each hard rule of the output of a packer.\n * It applies the output with `applyPack`. Only the placed boxes and the locked boxes count for the overlaps and the container.\n * `no-overlap` counts the pairs of boxes and the pairs of a box and an obstacle.\n * A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`.\n * A locked box without a position in the input is a bad input, not a break. `checkInput` finds it.\n * Another box without a placement that is not in `overflow` breaks `complete`.\n */\nexport function packHard(input: LayoutInput, output: PackOutput, tolerance: number = DEFAULT_TOLERANCE.overlap): PackHard {\n const after = applyPack(input, output);\n const placed = new Set(output.placements.map((p) => p.id));\n const out = new Set(output.overflow);\n const was = new Map(input.boxes.map((b) => [b.id, b]));\n let lockedMoved = 0;\n let incomplete = 0;\n const kept: LayoutBox[] = [];\n for (const box of after.boxes) {\n const old = was.get(box.id);\n if (old?.locked === true) {\n if (old.x === undefined || old.y === undefined) continue;\n const moved = Math.abs(old.x - (box.x ?? old.x)) > RECORD_EPS || Math.abs(old.y - (box.y ?? old.y)) > RECORD_EPS;\n if (!placed.has(box.id) || moved) lockedMoved++;\n kept.push(box);\n } else if (placed.has(box.id)) {\n kept.push(box);\n } else if (!out.has(box.id)) {\n incomplete++;\n }\n }\n return {\n \"no-overlap\": countOverlaps(kept, tolerance) + countObstacleHits(kept, after.obstacles, tolerance),\n \"in-container\": countOutside({ ...after, boxes: kept }, tolerance),\n \"locked-kept\": lockedMoved,\n complete: incomplete,\n };\n}\n\n/**\n * This function gives the problems of an input file. An empty list tells that the file is good.\n * A problem is a bad input, not a break of a hard rule. Thus an engine refuses the input.\n */\nexport function checkInput(input: LayoutInput): readonly string[] {\n const problems: string[] = [];\n const ids = new Set<string>();\n for (const box of input.boxes) {\n if (ids.has(box.id)) problems.push(`box ${box.id}: the id is not unique`);\n ids.add(box.id);\n if (!(box.w > 0 && box.h > 0 && Number.isFinite(box.w) && Number.isFinite(box.h))) problems.push(`box ${box.id}: the size is not positive and finite`);\n if (box.locked === true && (box.x === undefined || box.y === undefined)) problems.push(`box ${box.id}: a locked box has no position`);\n }\n if (countPortsOffBorder(input.boxes) > 0) problems.push(\"a fixed port is not on the border of its box\");\n for (const edge of input.edges ?? []) {\n if (!ids.has(edge.source) || !ids.has(edge.target)) problems.push(`edge ${edge.id}: a box of the edge is not in the input`);\n }\n return problems;\n}\n","import { RECORD_EPS } from \"./tolerance.ts\";\n\n/** The direction of a measure: the side of the better values. */\nexport type Direction = \"lower\" | \"higher\";\n\n/**\n * The facts of one measure: its unit, its direction and its range.\n * `floor` and `tol` are the parameters of the floor rule of the promotion rule (`docs/PROMOTION.md` of `highways`).\n * Each engine exports the specs of its own measures. This package exports the specs of the `joint.*` measures.\n */\nexport interface MeasureSpec<Id extends string = string> {\n readonly id: Id;\n readonly unit: string;\n readonly direction: Direction;\n /** The lowest value. */\n readonly min: number;\n /** The highest value. The value `Infinity` tells that the measure has no upper limit. */\n readonly max: number;\n /** The family of the measure in the measure note of its engine. */\n readonly family?: string;\n /** The best value. Without it, the measure has no floor. */\n readonly floor?: number;\n /** The absolute tolerance at the floor. */\n readonly tol?: number;\n /**\n * The smallest change that counts as better or worse. A number is an absolute change. `{ rel }` is a share of the larger of the two values.\n * `docs/JOINT-MEASURES.md` gives the reason of each joint value.\n */\n readonly minEffect?: number | { readonly rel: number };\n /** The role of the measure in the joint selector. */\n readonly role?: \"guard\" | \"change-guard\" | \"diagnostic\" | \"time\";\n}\n\n/** The id of a joint measure. `docs/JOINT-MEASURES.md` gives the definitions. */\nexport type JointMeasureId =\n | \"joint.fill\"\n | \"joint.aspectError\"\n | \"joint.spill\"\n | \"joint.straight.crossings\"\n | \"joint.straight.length\"\n | \"joint.stability.mean\"\n | \"joint.stability.moved\"\n | \"joint.proxy.rank\"\n | \"joint.ms\";\n\n/** The specs of the joint measures, in the order of `docs/JOINT-MEASURES.md`. */\nexport const JOINT_MEASURES: readonly MeasureSpec<JointMeasureId>[] = Object.freeze([\n { id: \"joint.fill\", minEffect: 0.001, unit: \"0 to 1\", direction: \"higher\", min: 0, max: 1, floor: 1, role: \"guard\" },\n { id: \"joint.aspectError\", minEffect: 0.01, unit: \"natural log\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0.01, role: \"guard\" },\n { id: \"joint.spill\", minEffect: 0.001, unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, floor: 0, tol: 0.001, role: \"guard\" },\n { id: \"joint.straight.crossings\", minEffect: 0, unit: \"count\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0, role: \"guard\" },\n { id: \"joint.straight.length\", minEffect: 0.01, unit: \"S for each edge\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0.01, role: \"guard\" },\n { id: \"joint.stability.mean\", minEffect: 0.005, unit: \"W\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0.005, role: \"change-guard\" },\n { id: \"joint.stability.moved\", minEffect: 0.02, unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, floor: 0, tol: 0.02, role: \"change-guard\" },\n { id: \"joint.proxy.rank\", unit: \"-1 to 1\", direction: \"higher\", min: -1, max: 1, role: \"diagnostic\" },\n { id: \"joint.ms\", unit: \"milliseconds\", direction: \"lower\", min: 0, max: Infinity, role: \"time\" },\n] as const);\n\n/** The threshold of `joint.stability.moved`, in widths `W` of the base. */\nexport const JOINT_MOVED_MIN = 0.01;\n\n/** The result of a compare of a candidate with a baseline on one measure. A tie is not better. */\nexport type Verdict = \"better\" | \"worse\" | \"tie\";\n\n/**\n * This function gives the smallest change of a measure that counts between the values `a` and `b`.\n * The value is `max(RECORD_EPS, minEffect)`, or `max(RECORD_EPS, rel * max(|a|, |b|))` for a relative `minEffect`.\n * The larger value makes the threshold the same after a swap of `a` and `b`.\n */\nexport function minEffectOf(spec: Pick<MeasureSpec, \"minEffect\">, a = 0, b = 0): number {\n const m = spec.minEffect ?? 0;\n const t = typeof m === \"number\" ? m : m.rel * Math.max(Math.abs(a), Math.abs(b));\n return Math.max(RECORD_EPS, Number.isFinite(t) ? t : 0);\n}\n\n/**\n * This function compares the value `candidate` with the value `baseline` of one measure on one input.\n * A change of at most `minEffectOf(spec, candidate, baseline)` is a tie. The test is symmetric: a swap of the two values swaps better and worse.\n * Two equal values are a tie, also two infinite values. A value `NaN` is an error.\n */\nexport function compareMeasure(candidate: number, baseline: number, spec: Pick<MeasureSpec, \"direction\" | \"minEffect\">): Verdict {\n if (Number.isNaN(candidate) || Number.isNaN(baseline)) throw new RangeError(\"compareMeasure: a value is NaN\");\n if (candidate === baseline) return \"tie\";\n const delta = candidate - baseline;\n if (!(Math.abs(delta) > minEffectOf(spec, candidate, baseline))) return \"tie\";\n const better = spec.direction === \"lower\" ? delta < 0 : delta > 0;\n return better ? \"better\" : \"worse\";\n}\n"],"mappings":";;AAIA,MAAa,QAAyB;CAAC;CAAO;CAAS;CAAU;AAAM;;AAyCvE,SAAgB,YAAY,QAAmC;CAC7D,IAAI,WAAW,KAAA,GAAW,OAAO;EAAE,KAAK;EAAG,OAAO;EAAG,QAAQ;EAAG,MAAM;CAAE;CACxE,IAAI,OAAO,WAAW,UAAU,OAAO;EAAE,KAAK;EAAQ,OAAO;EAAQ,QAAQ;EAAQ,MAAM;CAAO;CAClG,OAAO;AACT;;AAGA,SAAgB,KAAK,MAAY,QAAkC;CACjE,MAAM,IAAI,YAAY,MAAM;CAC5B,OAAO;EAAE,GAAG,KAAK,IAAI,EAAE;EAAM,GAAG,KAAK,IAAI,EAAE;EAAK,GAAG,KAAK,IAAI,EAAE,OAAO,EAAE;EAAO,GAAG,KAAK,IAAI,EAAE,MAAM,EAAE;CAAO;AAC7G;;AAGA,SAAgB,SAAS,QAAsB;CAC7C,QAAQ,OAAO,MAAf;EACE,KAAK,QACH,OAAO;GAAE,GAAG,OAAO;GAAG,GAAG,OAAO;GAAG,GAAG,OAAO;GAAG,GAAG,OAAO;EAAE;EAC9D,KAAK,UACH,OAAO;GAAE,GAAG,OAAO,KAAK,OAAO;GAAG,GAAG,OAAO,KAAK,OAAO;GAAG,GAAG,IAAI,OAAO;GAAG,GAAG,IAAI,OAAO;EAAE;EAC9F,KAAK,WACH,OAAO;GAAE,GAAG,OAAO,KAAK,OAAO;GAAI,GAAG,OAAO,KAAK,OAAO;GAAI,GAAG,IAAI,OAAO;GAAI,GAAG,IAAI,OAAO;EAAG;EAClG,KAAK,WAAW;GAC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../src/turn.ts","../src/output.ts","../src/record.ts","../src/rules.ts","../src/measures.ts","../src/random.ts","../src/edges.ts"],"sourcesContent":["/** A side of a box. The y axis points down, so `top` has the smallest y. */\nexport type Side = \"top\" | \"right\" | \"bottom\" | \"left\";\n\n/** The sides in clockwise order, from the top. */\nexport const SIDES: readonly Side[] = [\"top\", \"right\", \"bottom\", \"left\"];\n\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\n/** A rectangle: its top-left corner and its size. */\nexport interface Rect {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n}\n\n/** A value for each side of a box. */\nexport interface Sides {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\n/**\n * A region. The forms and the rules are those of `docs/FORMAT.md` of `packing`.\n * A ring of a polygon closes without a copy of its first point.\n */\nexport type Region =\n | { readonly kind: \"rect\"; readonly x: number; readonly y: number; readonly w: number; readonly h: number }\n | {\n readonly kind: \"polygon\";\n readonly points: readonly (readonly [number, number])[];\n readonly holes?: readonly (readonly (readonly [number, number])[])[];\n }\n | { readonly kind: \"circle\"; readonly cx: number; readonly cy: number; readonly r: number }\n | { readonly kind: \"ellipse\"; readonly cx: number; readonly cy: number; readonly rx: number; readonly ry: number };\n\n/** A margin: one value for the four sides, or one value for each side. */\nexport type Margin = number | Sides;\n\n/** This function gives the value of each side of a margin. No margin gives 0 on each side. */\nexport function marginSides(margin: Margin | undefined): Sides {\n if (margin === undefined) return { top: 0, right: 0, bottom: 0, left: 0 };\n if (typeof margin === \"number\") return { top: margin, right: margin, bottom: margin, left: margin };\n return margin;\n}\n\n/** This function gives the rectangle made larger by the margin on each side. */\nexport function grow(rect: Rect, margin: Margin | undefined): Rect {\n const m = marginSides(margin);\n return { x: rect.x - m.left, y: rect.y - m.top, w: rect.w + m.left + m.right, h: rect.h + m.top + m.bottom };\n}\n\n/** This function gives the bounding box of a region. */\nexport function boundsOf(region: Region): Rect {\n switch (region.kind) {\n case \"rect\":\n return { x: region.x, y: region.y, w: region.w, h: region.h };\n case \"circle\":\n return { x: region.cx - region.r, y: region.cy - region.r, w: 2 * region.r, h: 2 * region.r };\n case \"ellipse\":\n return { x: region.cx - region.rx, y: region.cy - region.ry, w: 2 * region.rx, h: 2 * region.ry };\n case \"polygon\": {\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (const [x, y] of region.points) {\n x0 = Math.min(x0, x);\n y0 = Math.min(y0, y);\n x1 = Math.max(x1, x);\n y1 = Math.max(y1, y);\n }\n return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };\n }\n }\n}\n\n/** This function gives the region moved by `dx` and `dy`. */\nexport function translate(region: Region, dx: number, dy: number): Region {\n switch (region.kind) {\n case \"rect\":\n return { ...region, x: region.x + dx, y: region.y + dy };\n case \"circle\":\n case \"ellipse\":\n return { ...region, cx: region.cx + dx, cy: region.cy + dy };\n case \"polygon\": {\n const move = (ring: readonly (readonly [number, number])[]): [number, number][] => ring.map(([x, y]) => [x + dx, y + dy]);\n return region.holes === undefined\n ? { kind: \"polygon\", points: move(region.points) }\n : { kind: \"polygon\", points: move(region.points), holes: region.holes.map(move) };\n }\n }\n}\n\n/**\n * This function gives the overlap of the insides of two rectangles on each axis.\n * A value of 0 or less on an axis is no overlap. Two rectangles with a common edge have an overlap of 0.\n */\nexport function overlapOf(a: Rect, b: Rect): { readonly x: number; readonly y: number } {\n return {\n x: Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x),\n y: Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y),\n };\n}\n","/** The epsilon for the float compares in an engine. */\nexport const EPS = 1e-6;\n\n/**\n * The epsilon for the float compares on a written file. A file rounds each number to 3 decimals,\n * so a difference of two values can move by up to 0.001.\n */\nexport const RECORD_EPS = 1e-3;\n\n/**\n * The tolerance of each hard rule, in layout units. A record writes the tolerance that its run used,\n * in its field `tolerance`, next to `hard`.\n */\nexport interface Tolerance {\n /** Two boxes with their margins break `no-overlap` when their insides overlap by more than this on each axis. */\n readonly overlap: number;\n /** A route breaks `no-pass-through` when a part longer than this is inside a box made this much smaller. */\n readonly through: number;\n}\n\n/**\n * The default tolerance of each rule. The packer is exact, so `overlap` is one unit of the rounding.\n * Routes are sampled curves that follow the margin line, so `through` is larger.\n */\nexport const DEFAULT_TOLERANCE: Tolerance = Object.freeze({ overlap: 0.001, through: 0.5 });\n","import type { Margin, Region, Side } from \"./geometry.ts\";\n\n/**\n * A port of a box: a place where edges go into the box.\n * With `x` and `y`, the port is fixed on the border of the box, relative to its top-left corner.\n * Without them, the router places the port on its `side`. Without a side, the router picks the side.\n */\nexport interface Port {\n readonly id: string;\n readonly side?: Side;\n readonly x?: number;\n readonly y?: number;\n}\n\n/** A box of an input. In the packer, its name is item. */\nexport interface LayoutBox {\n readonly id: string;\n readonly w: number;\n readonly h: number;\n /** The packer writes the position. The router reads it. */\n readonly x?: number;\n readonly y?: number;\n /** A locked box keeps `x` and `y`. The packer reads it as an obstacle. */\n readonly locked?: boolean;\n /** The reading order. Without it, the order of the array is the rank. */\n readonly rank?: number;\n readonly parent?: string;\n readonly group?: string;\n /** A region relative to the origin of the box. Without it, the box is the rectangle `w` by `h`. */\n readonly shape?: Region;\n readonly ports?: readonly Port[];\n /** A ring around the box. No other box enters it. Only a route from a port of the box enters it, at a right angle. */\n readonly margin?: Margin;\n /** The packer can turn the box by 90 degrees. The output has the turned box and ports. */\n readonly turnable?: boolean;\n /** The free data of the node. The grouping rule `keys` of `highways` reads `data.group`. */\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/** The packer name of a box. It is the same type. */\nexport type Item = LayoutBox;\n\n/** An edge between two boxes, with optional ports. */\nexport interface LayoutEdge {\n readonly id: string;\n readonly source: string;\n readonly target: string;\n readonly sourcePort?: string;\n readonly targetPort?: string;\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/** The container. `fixed` tells which sides of the size stay. */\nexport interface LayoutContainer {\n readonly w?: number;\n readonly h?: number;\n readonly fixed: \"size\" | \"width\" | \"height\" | \"none\";\n /** The target aspect: the width divided by the height. The default is 1. */\n readonly aspect?: number;\n /** The weight of the aspect error in the objective. 0 gives the least area. The default is 1. */\n readonly aspectWeight?: number;\n /** The shape. Without it, the container is the rectangle from 0, 0 to `w`, `h`. */\n readonly shape?: Region;\n /** The space between the border and the boxes with their margins. */\n readonly inset?: number;\n}\n\n/** An area that boxes and routes avoid. Without `move`, it stays. With `move`, the packer can move it for `cost` times the distance. */\nexport interface Obstacle {\n readonly id: string;\n readonly region: Region;\n readonly move?: { readonly cost: number };\n}\n\n/** The generator of an input. The same name, version, parameters and seed give the same file, byte for byte. */\nexport interface LayoutGenerator {\n readonly name: string;\n readonly version: number;\n readonly params: Readonly<Record<string, unknown>>;\n readonly seed: number;\n}\n\n/** The cell of an input in the taxonomy: one value for each dimension. The dimensions are in `docs/FORMAT.md` of `packing`. */\nexport interface LayoutCell {\n readonly containerSize?: \"fixed\" | \"freeHeight\" | \"freeWidth\" | \"freeAspect\" | \"freeArea\";\n readonly containerShape?: \"rect\" | \"convex\" | \"polygon\" | \"circle\" | \"ellipse\" | \"holes\";\n readonly obstacles?: \"none\" | \"center\" | \"scattered\" | \"wall\" | \"corridors\" | \"touching\" | \"edge\";\n readonly sizes?: \"identical\" | \"uniform\" | \"heavyTail\" | \"bimodal\" | \"extremeAspect\" | \"nearIdentical\";\n readonly count?: \"1\" | \"10\" | \"100\" | \"1k\" | \"10k\";\n readonly mode?: \"offline\" | \"online\" | \"incremental\";\n readonly edgeDensity?: \"sparse\" | \"medium\" | \"dense\";\n readonly edgeShape?: \"random\" | \"clustered\" | \"hubChain\" | \"longRange\" | \"tree\" | \"bundled\";\n readonly groups?: \"none\" | \"flat\" | \"nested\";\n readonly ports?: \"free\" | \"sides\" | \"fixed\";\n}\n\n/** An input of the corpus: the format `layout-input/1`. */\nexport interface LayoutInput {\n readonly schema: \"layout-input/1\";\n readonly id: string;\n readonly set?: string;\n readonly family?: string;\n readonly seed?: number;\n /** The origin: `made-up`, `published:<set>` or `known-best:<construction>`. */\n readonly source?: string;\n /** The first 16 hex characters of the SHA-256 of the canonical file without this field. */\n readonly hash?: string;\n /** The generator of the input. `null` or no value tells that a person made the input. */\n readonly generator?: LayoutGenerator | null;\n /** The steps that changed the input after its generator, in their order. `edgeStep` adds one. */\n readonly steps?: readonly LayoutGenerator[];\n readonly cell?: LayoutCell;\n /** The place of the input in a sequence of changes. */\n readonly step?: number;\n /** A router input can have no container. */\n readonly container?: LayoutContainer;\n /** The free space between two boxes with their margins. Routes use it. */\n readonly gap?: number;\n readonly boxes: readonly LayoutBox[];\n readonly edges?: readonly LayoutEdge[];\n readonly obstacles?: readonly Obstacle[];\n /**\n * A variant names its base input and its change.\n * With `packed`, the variant is the packed output of its base input: the router routes the positions of that pack.\n */\n readonly base?: string;\n readonly change?: \"add\" | \"remove\" | \"resize\" | \"reorder\" | \"packed\";\n}\n\n/** The input of a packer: a `layout-input/1` file without the edges. */\nexport interface PackInput {\n readonly container: LayoutContainer;\n readonly items: readonly Item[];\n readonly obstacles?: readonly Obstacle[];\n readonly gap?: number;\n}\n\n/** This function gives the packer input of a file. An input without a container gets `{ fixed: \"none\" }`, so the packer picks the size. */\nexport function toPackInput(input: LayoutInput): PackInput {\n return {\n container: input.container ?? { fixed: \"none\" },\n items: input.boxes,\n ...(input.obstacles === undefined ? {} : { obstacles: input.obstacles }),\n ...(input.gap === undefined ? {} : { gap: input.gap }),\n };\n}\n","import { SIDES, marginSides, type Margin, type Region, type Side } from \"./geometry.ts\";\nimport type { LayoutBox, Port } from \"./input.ts\";\n\n/*\n * The turn: 90 degrees clockwise, with the y axis down. The turned box has `w` and `h` swapped,\n * and its top-left corner stays at the position of the box. A point (px, py) of a box of height h\n * goes to (h - py, px). Thus the top-left corner goes to the top-right corner, and each side moves\n * one step clockwise: top to right, right to bottom, bottom to left, left to top.\n */\n\n/** This function gives the side after a turn of 90 degrees clockwise. */\nexport function turnSide(side: Side): Side {\n return SIDES[(SIDES.indexOf(side) + 1) % 4]!;\n}\n\n/** This function gives a point of a box of height `h` after the turn. */\nexport function turnPoint(x: number, y: number, h: number): [number, number] {\n return [h - y, x];\n}\n\n/** This function gives a port of a box of height `h` after the turn. Each value of the port turns, also a port with only `x` or only `y`. */\nexport function turnPort(port: Port, h: number): Port {\n const { side, x, y, ...rest } = port;\n return {\n ...rest,\n ...(side === undefined ? {} : { side: turnSide(side) }),\n ...(y === undefined ? {} : { x: h - y }),\n ...(x === undefined ? {} : { y: x }),\n };\n}\n\n/** This function gives a margin after the turn: the value of each side moves one side clockwise. */\nexport function turnMargin(margin: Margin): Margin {\n if (typeof margin === \"number\") return margin;\n const m = marginSides(margin);\n return { top: m.left, right: m.top, bottom: m.right, left: m.bottom };\n}\n\n/** This function gives a region relative to the origin of a box of height `h` after the turn. */\nexport function turnRegion(region: Region, h: number): Region {\n switch (region.kind) {\n case \"rect\":\n return { kind: \"rect\", x: h - region.y - region.h, y: region.x, w: region.h, h: region.w };\n case \"circle\":\n return { ...region, cx: h - region.cy, cy: region.cx };\n case \"ellipse\":\n return { kind: \"ellipse\", cx: h - region.cy, cy: region.cx, rx: region.ry, ry: region.rx };\n case \"polygon\": {\n const turn = (ring: readonly (readonly [number, number])[]): [number, number][] => ring.map(([x, y]) => turnPoint(x, y, h));\n return region.holes === undefined\n ? { kind: \"polygon\", points: turn(region.points) }\n : { kind: \"polygon\", points: turn(region.points), holes: region.holes.map(turn) };\n }\n }\n}\n\n/** This function gives a box after the turn: the size, the ports, the margin and the shape turn. The position stays. */\nexport function turnBox(box: LayoutBox): LayoutBox {\n return {\n ...box,\n w: box.h,\n h: box.w,\n ...(box.ports === undefined ? {} : { ports: box.ports.map((p) => turnPort(p, box.h)) }),\n ...(box.margin === undefined ? {} : { margin: turnMargin(box.margin) }),\n ...(box.shape === undefined ? {} : { shape: turnRegion(box.shape, box.h) }),\n };\n}\n","import { boundsOf, translate } from \"./geometry.ts\";\nimport type { LayoutInput } from \"./input.ts\";\nimport { turnBox } from \"./turn.ts\";\n\n/** The position of one item. `turn` is 90 when the packer turned a turnable item. */\nexport interface Placement {\n readonly id: string;\n readonly x: number;\n readonly y: number;\n readonly turn?: 0 | 90;\n}\n\n/** The facts of one stage of a strategy, for the records and the site. */\nexport interface StageTrace {\n readonly id: string;\n readonly ms?: number;\n readonly measures?: Readonly<Record<string, number>>;\n}\n\n/** The output of a packer. It does not change the input. */\nexport interface PackOutput {\n readonly placements: readonly Placement[];\n /** The ids of the items that the packer did not place. */\n readonly overflow: readonly string[];\n /** The size of the container after the pack. For a free size, the size that the search found. */\n readonly size: { readonly w: number; readonly h: number };\n /** The new top-left corner of the bounding box of each obstacle that moved. */\n readonly moved: readonly { readonly id: string; readonly x: number; readonly y: number }[];\n readonly trace?: readonly StageTrace[];\n}\n\n/**\n * This function gives the input with the output of a packer applied. Each placed box gets its position.\n * A turned box gets its turned size, ports, margin and shape. Each moved obstacle moves.\n * The container gets the size of the output. The router reads this result. It does not read `turn`.\n */\nexport function applyPack(input: LayoutInput, output: PackOutput): LayoutInput {\n const at = new Map(output.placements.map((p) => [p.id, p]));\n const moved = new Map(output.moved.map((m) => [m.id, m]));\n const boxes = input.boxes.map((box) => {\n const p = at.get(box.id);\n if (p === undefined) return box;\n const turned = p.turn === 90 ? turnBox(box) : box;\n return { ...turned, x: p.x, y: p.y };\n });\n const obstacles = input.obstacles?.map((o) => {\n const m = moved.get(o.id);\n if (m === undefined) return o;\n const b = boundsOf(o.region);\n return { ...o, region: translate(o.region, m.x - b.x, m.y - b.y) };\n });\n return {\n ...input,\n container: { ...(input.container ?? { fixed: \"none\" }), w: output.size.w, h: output.size.h },\n boxes,\n ...(obstacles === undefined ? {} : { obstacles }),\n };\n}\n","import type { Tolerance } from \"./tolerance.ts\";\nimport type { LayoutInput } from \"./input.ts\";\n\n/** The stage of a record: the packer, the router, or both together. */\nexport type Stage = \"pack\" | \"route\" | \"joint\";\n\n/** One run of one strategy on one input and seed: the format `layout-record/1`. A run writes one line of JSON Lines. */\nexport interface LayoutRecord {\n readonly schema: \"layout-record/1\";\n readonly stage: Stage;\n readonly step: string;\n readonly strategy: string;\n /** The options in full, with the defaults. */\n readonly options: Readonly<Record<string, unknown>>;\n readonly corpus: string;\n /** The id of the input. */\n readonly input: string;\n /** The `hash` of the input file. */\n readonly inputHash: string;\n readonly set: string;\n readonly seed: number;\n readonly nodes: number;\n readonly edges: number;\n /** The value of each measure, by its name: `pack.*`, `route.*` or `joint.*`. */\n readonly measures: Readonly<Record<string, number>>;\n /** The count of the breaks of each hard rule. A good run has 0 for each rule. */\n readonly hard: Readonly<Record<string, number>>;\n /** The tolerance of each hard rule of the run. */\n readonly tolerance?: Readonly<Partial<Tolerance>>;\n /** `true` when two runs with the same seed give the same positions. */\n readonly deterministic: boolean;\n /** The id of the prediction that was written before the run. */\n readonly prediction?: string;\n /** The median of `msRuns`, or the time of the one run. */\n readonly ms: number;\n /** The time of each timed repeat, in milliseconds. */\n readonly msRuns?: readonly number[];\n /**\n * The first 16 hex characters of the SHA-256 of the canonical output of the stage.\n * The packer hashes its placements by the order of the ids. The router hashes its routes by the order of the edge ids.\n */\n readonly outputHash?: string;\n /** The facts of the computer of the run. */\n readonly env?: RunEnv;\n /** The reason when the strategy did not run, for example an input over its `maxNodes`. Then the record has no measures. */\n readonly skipped?: string;\n readonly commit?: string;\n}\n\n/**\n * The values that a strategy supports, for each dimension of a taxonomy.\n * The dimension names are in `docs/FORMAT.md` of `packing` and `docs/LAYOUT-RECORDS.md` of `highways`.\n */\nexport type Supports = Readonly<Record<string, readonly string[]>>;\n\n/** The facts of the computer of a run. */\nexport interface RunEnv {\n readonly node: string;\n readonly os: string;\n readonly arch: string;\n /** The name of the runner, for example `ubuntu-latest` or `local`. */\n readonly runner: string;\n /** The model of the processor. */\n readonly cpu: string;\n /** The count of the logical processors. */\n readonly cpus: number;\n}\n\n/** The facts of a run that the input does not give. */\nexport type RunFacts = Omit<LayoutRecord, \"schema\" | \"input\" | \"inputHash\" | \"set\" | \"nodes\" | \"edges\">;\n\n/** This function gives the record of a run. The input gives its id, its hash, its set and the counts of the nodes and the edges. */\nexport function toLayoutRecord(input: LayoutInput, run: RunFacts): LayoutRecord {\n return {\n schema: \"layout-record/1\",\n ...run,\n input: input.id,\n inputHash: input.hash ?? \"\",\n set: input.set ?? \"\",\n nodes: input.boxes.length,\n edges: input.edges?.length ?? 0,\n };\n}\n","import { boundsOf, grow, overlapOf, type Rect, type Region } from \"./geometry.ts\";\nimport type { LayoutBox, LayoutInput, Obstacle } from \"./input.ts\";\nimport { applyPack, type PackOutput } from \"./output.ts\";\nimport { DEFAULT_TOLERANCE, EPS, RECORD_EPS } from \"./tolerance.ts\";\n\n/** This function gives the area of a placed box: its shape or its rectangle, at its position. A box without a position gives `undefined`. */\nexport function placedRect(box: LayoutBox): Rect | undefined {\n if (box.x === undefined || box.y === undefined) return undefined;\n if (box.shape === undefined) return { x: box.x, y: box.y, w: box.w, h: box.h };\n const b = boundsOf(box.shape);\n return { x: box.x + b.x, y: box.y + b.y, w: b.w, h: b.h };\n}\n\n/**\n * This function counts the pairs of placed boxes whose insides, with their margins, overlap by more than `tolerance` on each axis.\n * A box with a shape counts as its bounding box. That area is larger, thus the count is safe.\n */\nexport function countOverlaps(boxes: readonly LayoutBox[], tolerance: number = DEFAULT_TOLERANCE.overlap): number {\n const rects: Rect[] = [];\n for (const box of boxes) {\n const r = placedRect(box);\n if (r !== undefined) rects.push(grow(r, box.margin));\n }\n rects.sort((a, b) => a.x - b.x);\n let count = 0;\n for (let i = 0; i < rects.length; i++) {\n const a = rects[i]!;\n for (let j = i + 1; j < rects.length; j++) {\n const b = rects[j]!;\n if (b.x >= a.x + a.w - tolerance) break;\n const o = overlapOf(a, b);\n if (o.x > tolerance && o.y > tolerance) count++;\n }\n }\n return count;\n}\n\n/** The options of the container test of `countOutside` and `packHard`. */\nexport interface ContainerTest {\n /**\n * With `true`, a box of a shaped container with the size `fixed` must stay inside the shape, not only inside its bounding box.\n * The default is `false`. The default changes to `true` at the next breaking version.\n */\n readonly exactContainer?: boolean;\n}\n\n/**\n * This function counts the placed boxes that go out of the container.\n * Each box with its margin must stay inside the container made smaller by `inset`. Only the fixed sides of the size count. A shaped container counts as its bounding box.\n *\n * With `exactContainer`, a box of a shaped container with the size `fixed` also counts when `rectInRegion` tells that it is not inside the shape.\n * For that test, the box grows by `inset` and becomes smaller by `tolerance` on each side. A shaped container with a free side keeps the bounding test only.\n * An input without a container gives 0.\n */\nexport function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOLERANCE.overlap, options: ContainerTest = {}): number {\n const c = input.container;\n if (c === undefined) return 0;\n const shape = options.exactContainer === true && c.fixed === \"size\" ? c.shape : undefined;\n const area = c.shape === undefined ? { x: 0, y: 0, w: c.w ?? Infinity, h: c.h ?? Infinity } : boundsOf(c.shape);\n const inset = c.inset ?? 0;\n const fixW = c.fixed === \"size\" || c.fixed === \"width\";\n const fixH = c.fixed === \"size\" || c.fixed === \"height\";\n let count = 0;\n for (const box of input.boxes) {\n const r0 = placedRect(box);\n if (r0 === undefined) continue;\n const r = grow(r0, box.margin);\n const outX = r.x < area.x + inset - tolerance || r.x + r.w > area.x + area.w - inset + tolerance;\n const outY = r.y < area.y + inset - tolerance || r.y + r.h > area.y + area.h - inset + tolerance;\n if ((fixW && outX) || (fixH && outY)) count++;\n else if (shape !== undefined && !rectInRegion(shape, shrink(grow(r, inset), tolerance))) count++;\n }\n return count;\n}\n\n/** This function counts the fixed ports that are not on the border of their box, with the epsilon of a written file. A port without a side does not count. */\nexport function countPortsOffBorder(boxes: readonly LayoutBox[], eps: number = RECORD_EPS): number {\n let count = 0;\n for (const box of boxes) {\n for (const p of box.ports ?? []) {\n if (p.x === undefined || p.y === undefined || p.side === undefined) continue;\n const along = p.side === \"top\" || p.side === \"bottom\" ? p.x : p.y;\n const length = p.side === \"top\" || p.side === \"bottom\" ? box.w : box.h;\n const across = { top: p.y, bottom: p.y - box.h, left: p.x, right: p.x - box.w }[p.side];\n if (Math.abs(across) > eps || along < -eps || along > length + eps) count++;\n }\n }\n return count;\n}\n\n/** The count of the breaks of each hard rule of a pack. */\nexport interface PackHard {\n readonly \"no-overlap\": number;\n readonly \"in-container\": number;\n readonly \"locked-kept\": number;\n readonly complete: number;\n}\n\n/** This function tells if the inside of `region` and the inside of `rect` have a common point. */\nexport function regionHitsRect(region: Region, rect: Rect): boolean {\n if (rect.w <= 0 || rect.h <= 0) return false;\n switch (region.kind) {\n case \"rect\": {\n const o = overlapOf(region, rect);\n return o.x > 0 && o.y > 0;\n }\n case \"circle\":\n return circleHitsRect(region.cx, region.cy, region.r, region.r, rect);\n case \"ellipse\":\n return circleHitsRect(region.cx, region.cy, region.rx, region.ry, rect);\n case \"polygon\": {\n const rings = [region.points, ...(region.holes ?? [])];\n const inside = (x: number, y: number): boolean => x > rect.x && x < rect.x + rect.w && y > rect.y && y < rect.y + rect.h;\n if (region.points.some(([x, y]) => inside(x, y))) return true;\n for (const ring of rings) {\n for (let i = 0; i < ring.length; i++) {\n const a = ring[i]!;\n const b = ring[(i + 1) % ring.length]!;\n const m = clipMid(a[0], a[1], b[0], b[1], rect);\n if (m !== undefined && inside(m[0], m[1])) return true;\n }\n }\n return pointInRings(rect.x + rect.w / 2, rect.y + rect.h / 2, rings);\n }\n }\n}\n\n/**\n * This function tells if all of `rect` is inside `region`. A point on the border counts as inside. No part of `rect` can overlap a hole.\n * The test of a circle, an ellipse or a polygon accepts an error of `EPS` on the border. A polygon can be concave.\n */\nexport function rectInRegion(region: Region, rect: Rect): boolean {\n const x1 = rect.x + rect.w;\n const y1 = rect.y + rect.h;\n const corners: readonly (readonly [number, number])[] = [\n [rect.x, rect.y],\n [x1, rect.y],\n [x1, y1],\n [rect.x, y1],\n ];\n switch (region.kind) {\n case \"rect\":\n return rect.x >= region.x && rect.y >= region.y && x1 <= region.x + region.w && y1 <= region.y + region.h;\n case \"circle\":\n return corners.every(([x, y]) => inEllipse(region.cx, region.cy, region.r, region.r, x, y));\n case \"ellipse\":\n return corners.every(([x, y]) => inEllipse(region.cx, region.cy, region.rx, region.ry, x, y));\n case \"polygon\": {\n const ring = region.points;\n if (ring.length < 3) return false;\n const points = [...corners, [rect.x + rect.w / 2, rect.y + rect.h / 2] as const];\n if (!points.every(([x, y]) => onRing(x, y, ring) || pointInRings(x, y, [ring]))) return false;\n const deep = (x: number, y: number): boolean => x > rect.x + EPS && x < x1 - EPS && y > rect.y + EPS && y < y1 - EPS;\n for (let i = 0; i < ring.length; i++) {\n const a = ring[i]!;\n const b = ring[(i + 1) % ring.length]!;\n const m = clipMid(a[0], a[1], b[0], b[1], rect);\n if (m !== undefined && deep(m[0], m[1])) return false;\n }\n return (region.holes ?? []).every((hole) => !regionHitsRect({ kind: \"polygon\", points: hole }, rect));\n }\n }\n}\n\n/** This function gives the rectangle made smaller by `d` on each side. A side does not become smaller than 0. */\nfunction shrink(r: Rect, d: number): Rect {\n const dx = Math.min(d, r.w / 2);\n const dy = Math.min(d, r.h / 2);\n return { x: r.x + dx, y: r.y + dy, w: r.w - 2 * dx, h: r.h - 2 * dy };\n}\n\n/** This function tells if a point is inside an ellipse or on its border, with an error of `EPS`. */\nfunction inEllipse(cx: number, cy: number, rx: number, ry: number, x: number, y: number): boolean {\n if (rx <= 0 || ry <= 0) return false;\n const u = (x - cx) / rx;\n const v = (y - cy) / ry;\n return u * u + v * v <= 1 + EPS;\n}\n\n/** This function tells if a point is on a ring of a polygon, with an error of `EPS`. */\nfunction onRing(x: number, y: number, ring: readonly (readonly [number, number])[]): boolean {\n for (let i = 0; i < ring.length; i++) {\n const [ax, ay] = ring[i]!;\n const [bx, by] = ring[(i + 1) % ring.length]!;\n const dx = bx - ax;\n const dy = by - ay;\n const len2 = dx * dx + dy * dy;\n const t = len2 === 0 ? 0 : Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / len2));\n if (Math.hypot(x - (ax + t * dx), y - (ay + t * dy)) <= EPS) return true;\n }\n return false;\n}\n\n/** An ellipse with the radii `rx` and `ry` scales to a unit circle. The rectangle scales with it. */\nfunction circleHitsRect(cx: number, cy: number, rx: number, ry: number, rect: Rect): boolean {\n if (rx <= 0 || ry <= 0) return false;\n const x0 = (rect.x - cx) / rx;\n const x1 = (rect.x + rect.w - cx) / rx;\n const y0 = (rect.y - cy) / ry;\n const y1 = (rect.y + rect.h - cy) / ry;\n const dx = Math.max(x0, 0, -x1);\n const dy = Math.max(y0, 0, -y1);\n return dx * dx + dy * dy < 1;\n}\n\n/** This function gives the middle of the part of a segment inside a rectangle, or `undefined` when that part is a point or empty. */\nfunction clipMid(ax: number, ay: number, bx: number, by: number, r: Rect): readonly [number, number] | undefined {\n let t0 = 0;\n let t1 = 1;\n const dx = bx - ax;\n const dy = by - ay;\n const edges: readonly (readonly [number, number])[] = [\n [-dx, ax - r.x],\n [dx, r.x + r.w - ax],\n [-dy, ay - r.y],\n [dy, r.y + r.h - ay],\n ];\n for (const [p, q] of edges) {\n if (p === 0) {\n if (q < 0) return undefined;\n } else if (p < 0) {\n t0 = Math.max(t0, q / p);\n } else {\n t1 = Math.min(t1, q / p);\n }\n }\n if (t1 <= t0) return undefined;\n const t = (t0 + t1) / 2;\n return [ax + t * dx, ay + t * dy];\n}\n\n/** The even-odd rule over the outer ring and the holes. */\nfunction pointInRings(x: number, y: number, rings: readonly (readonly (readonly [number, number])[])[]): boolean {\n let inside = false;\n for (const ring of rings) {\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n const [xi, yi] = ring[i]!;\n const [xj, yj] = ring[j]!;\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;\n }\n }\n return inside;\n}\n\n/**\n * This function counts the pairs of a placed box and an obstacle that overlap by more than `tolerance`.\n * The box counts with its margin. A box with a shape counts as its bounding box.\n */\nexport function countObstacleHits(\n boxes: readonly LayoutBox[],\n obstacles: readonly Obstacle[] | undefined,\n tolerance: number = DEFAULT_TOLERANCE.overlap,\n): number {\n if (obstacles === undefined || obstacles.length === 0) return 0;\n let count = 0;\n for (const box of boxes) {\n const r0 = placedRect(box);\n if (r0 === undefined) continue;\n const r = grow(r0, box.margin);\n const small = { x: r.x + tolerance, y: r.y + tolerance, w: r.w - 2 * tolerance, h: r.h - 2 * tolerance };\n for (const o of obstacles) if (regionHitsRect(o.region, small)) count++;\n }\n return count;\n}\n\n/**\n * This function gives the count of each hard rule of the output of a packer.\n * It applies the output with `applyPack`. Only the placed boxes and the locked boxes count for the overlaps and the container.\n * `no-overlap` counts the pairs of boxes and the pairs of a box and an obstacle.\n * A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`.\n * A locked box without a position in the input is a bad input, not a break. `checkInput` finds it.\n * Another box without a placement that is not in `overflow` breaks `complete`.\n *\n * `options` goes to `countOutside` for `in-container`.\n */\nexport function packHard(input: LayoutInput, output: PackOutput, tolerance: number = DEFAULT_TOLERANCE.overlap, options: ContainerTest = {}): PackHard {\n const after = applyPack(input, output);\n const placed = new Set(output.placements.map((p) => p.id));\n const out = new Set(output.overflow);\n const was = new Map(input.boxes.map((b) => [b.id, b]));\n let lockedMoved = 0;\n let incomplete = 0;\n const kept: LayoutBox[] = [];\n for (const box of after.boxes) {\n const old = was.get(box.id);\n if (old?.locked === true) {\n if (old.x === undefined || old.y === undefined) continue;\n const moved = Math.abs(old.x - (box.x ?? old.x)) > RECORD_EPS || Math.abs(old.y - (box.y ?? old.y)) > RECORD_EPS;\n if (!placed.has(box.id) || moved) lockedMoved++;\n kept.push(box);\n } else if (placed.has(box.id)) {\n kept.push(box);\n } else if (!out.has(box.id)) {\n incomplete++;\n }\n }\n return {\n \"no-overlap\": countOverlaps(kept, tolerance) + countObstacleHits(kept, after.obstacles, tolerance),\n \"in-container\": countOutside({ ...after, boxes: kept }, tolerance, options),\n \"locked-kept\": lockedMoved,\n complete: incomplete,\n };\n}\n\n/**\n * This function gives the problems of an input file. An empty list tells that the file is good.\n * A problem is a bad input, not a break of a hard rule. Thus an engine refuses the input.\n */\nexport function checkInput(input: LayoutInput): readonly string[] {\n const problems: string[] = [];\n const ids = new Set<string>();\n for (const box of input.boxes) {\n if (ids.has(box.id)) problems.push(`box ${box.id}: the id is not unique`);\n ids.add(box.id);\n if (!(box.w > 0 && box.h > 0 && Number.isFinite(box.w) && Number.isFinite(box.h))) problems.push(`box ${box.id}: the size is not positive and finite`);\n if (box.locked === true && (box.x === undefined || box.y === undefined)) problems.push(`box ${box.id}: a locked box has no position`);\n }\n if (countPortsOffBorder(input.boxes) > 0) problems.push(\"a fixed port is not on the border of its box\");\n for (const edge of input.edges ?? []) {\n if (!ids.has(edge.source) || !ids.has(edge.target)) problems.push(`edge ${edge.id}: a box of the edge is not in the input`);\n }\n return problems;\n}\n","import { RECORD_EPS } from \"./tolerance.ts\";\n\n/** The direction of a measure: the side of the better values. */\nexport type Direction = \"lower\" | \"higher\";\n\n/**\n * The facts of one measure: its unit, its direction and its range.\n * `floor` and `tol` are the parameters of the floor rule of the promotion rule (`docs/PROMOTION.md` of `highways`).\n * Each engine exports the specs of its own measures. This package exports the specs of the `joint.*` measures.\n */\nexport interface MeasureSpec<Id extends string = string> {\n readonly id: Id;\n readonly unit: string;\n readonly direction: Direction;\n /** The lowest value. */\n readonly min: number;\n /** The highest value. The value `Infinity` tells that the measure has no upper limit. */\n readonly max: number;\n /** The family of the measure in the measure note of its engine. */\n readonly family?: string;\n /** The best value. Without it, the measure has no floor. */\n readonly floor?: number;\n /** The absolute tolerance at the floor. */\n readonly tol?: number;\n /**\n * The smallest change that counts as better or worse. A number is an absolute change. `{ rel }` is a share of the larger of the two values.\n * `docs/JOINT-MEASURES.md` gives the reason of each joint value.\n */\n readonly minEffect?: number | { readonly rel: number };\n /** The role of the measure in the joint selector. */\n readonly role?: \"guard\" | \"change-guard\" | \"diagnostic\" | \"time\";\n}\n\n/** The id of a joint measure. `docs/JOINT-MEASURES.md` gives the definitions. */\nexport type JointMeasureId =\n | \"joint.fill\"\n | \"joint.aspectError\"\n | \"joint.spill\"\n | \"joint.straight.crossings\"\n | \"joint.straight.length\"\n | \"joint.stability.mean\"\n | \"joint.stability.moved\"\n | \"joint.proxy.rank\"\n | \"joint.ms\";\n\n/** The specs of the joint measures, in the order of `docs/JOINT-MEASURES.md`. */\nexport const JOINT_MEASURES: readonly MeasureSpec<JointMeasureId>[] = Object.freeze([\n { id: \"joint.fill\", minEffect: 0.001, unit: \"0 to 1\", direction: \"higher\", min: 0, max: 1, floor: 1, role: \"guard\" },\n { id: \"joint.aspectError\", minEffect: 0.01, unit: \"natural log\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0.01, role: \"guard\" },\n { id: \"joint.spill\", minEffect: 0.001, unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, floor: 0, tol: 0.001, role: \"guard\" },\n { id: \"joint.straight.crossings\", minEffect: 0, unit: \"count\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0, role: \"guard\" },\n { id: \"joint.straight.length\", minEffect: 0.01, unit: \"S for each edge\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0.01, role: \"guard\" },\n { id: \"joint.stability.mean\", minEffect: 0.005, unit: \"W\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0.005, role: \"change-guard\" },\n { id: \"joint.stability.moved\", minEffect: 0.02, unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, floor: 0, tol: 0.02, role: \"change-guard\" },\n { id: \"joint.proxy.rank\", unit: \"-1 to 1\", direction: \"higher\", min: -1, max: 1, role: \"diagnostic\" },\n { id: \"joint.ms\", unit: \"milliseconds\", direction: \"lower\", min: 0, max: Infinity, role: \"time\" },\n] as const);\n\n/** The threshold of `joint.stability.moved`, in widths `W` of the base. */\nexport const JOINT_MOVED_MIN = 0.01;\n\n/** The result of a compare of a candidate with a baseline on one measure. A tie is not better. */\nexport type Verdict = \"better\" | \"worse\" | \"tie\";\n\n/**\n * This function gives the smallest change of a measure that counts between the values `a` and `b`.\n * The value is `max(RECORD_EPS, minEffect)`, or `max(RECORD_EPS, rel * max(|a|, |b|))` for a relative `minEffect`.\n * The larger value makes the threshold the same after a swap of `a` and `b`.\n */\nexport function minEffectOf(spec: Pick<MeasureSpec, \"minEffect\">, a = 0, b = 0): number {\n const m = spec.minEffect ?? 0;\n const t = typeof m === \"number\" ? m : m.rel * Math.max(Math.abs(a), Math.abs(b));\n return Math.max(RECORD_EPS, Number.isFinite(t) ? t : 0);\n}\n\n/**\n * This function compares the value `candidate` with the value `baseline` of one measure on one input.\n * A change of at most `minEffectOf(spec, candidate, baseline)` is a tie. The test is symmetric: a swap of the two values swaps better and worse.\n * Two equal values are a tie, also two infinite values. A value `NaN` is an error.\n */\nexport function compareMeasure(candidate: number, baseline: number, spec: Pick<MeasureSpec, \"direction\" | \"minEffect\">): Verdict {\n if (Number.isNaN(candidate) || Number.isNaN(baseline)) throw new RangeError(\"compareMeasure: a value is NaN\");\n if (candidate === baseline) return \"tie\";\n const delta = candidate - baseline;\n if (!(Math.abs(delta) > minEffectOf(spec, candidate, baseline))) return \"tie\";\n const better = spec.direction === \"lower\" ? delta < 0 : delta > 0;\n return better ? \"better\" : \"worse\";\n}\n","/** This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`. */\nexport function mulberry32(seed: number): () => number {\n let s = seed >>> 0;\n return () => {\n s = (s + 0x6d2b79f5) | 0;\n let t = Math.imul(s ^ (s >>> 15), 1 | s);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n\n/** This function gives the FNV-1a hash of 32 bits of the UTF-8 bytes of a string. */\nexport function fnv1a32(text: string): number {\n let h = 0x811c9dc5;\n for (const b of utf8(text)) h = Math.imul(h ^ b, 0x01000193) >>> 0;\n return h;\n}\n\n/** The UTF-8 bytes of a string. The package has no runtime dependencies, thus it does not use `TextEncoder`. */\nfunction utf8(text: string): number[] {\n const bytes: number[] = [];\n for (const ch of text) {\n const c = ch.codePointAt(0)!;\n if (c < 0x80) bytes.push(c);\n else if (c < 0x800) bytes.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n else if (c < 0x10000) bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n else bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n }\n return bytes;\n}\n\n/** This function gives the generator of one step of a seeded generator: `mulberry32(fnv1a32(\"<seed>:<step>\"))`. */\nexport function stepRandom(seed: number, step: string): () => number {\n return mulberry32(fnv1a32(`${seed}:${step}`));\n}\n\n/** This function gives a whole number from `lo` to `hi`, both included. */\nexport function randomInt(r: () => number, lo: number, hi: number): number {\n return lo + Math.floor(r() * (hi - lo + 1));\n}\n","import { SIDES, type Side } from \"./geometry.ts\";\nimport type { LayoutBox, LayoutEdge, LayoutGenerator, LayoutInput, Port } from \"./input.ts\";\nimport { randomInt, stepRandom } from \"./random.ts\";\n\n/**\n * The shape of the edges of `edgeStep`. The values are the cells of `edgeShape`, and `hubs`.\n * `hubs` waits for the next breaking change to become a value of `LayoutCell.edgeShape`.\n */\nexport type EdgeShape = \"random\" | \"clustered\" | \"hubChain\" | \"hubs\" | \"longRange\" | \"tree\" | \"bundled\";\n\n/** The parameters of `edgeStep`. */\nexport interface EdgeStepParams {\n readonly edgeDensity: \"sparse\" | \"medium\" | \"dense\";\n readonly edgeShape: EdgeShape;\n /** The default is `none`. */\n readonly groups?: \"none\" | \"flat\" | \"nested\";\n /** The default is `free`. */\n readonly ports?: \"free\" | \"sides\" | \"fixed\";\n /** The order of the hubs of `hubs` and `tree`: the largest box first, or a random order. The default is `area`. */\n readonly hubBy?: \"area\" | \"random\";\n}\n\n/** The mean count of the edges of each box for each value of `edgeDensity`. */\nexport const EDGE_DENSITY: Readonly<Record<EdgeStepParams[\"edgeDensity\"], number>> = Object.freeze({ sparse: 0.5, medium: 1.5, dense: 4 });\n\n/** The version of `edgeStep`. A change of its output gives a new version. */\nexport const EDGE_STEP_VERSION = 1;\n\nconst CLUSTER = 8;\nconst CHAIN = 32;\nconst INSIDE = 0.85;\nconst FAN_SHARE = 0.6;\nconst FIXED_SHARE = 0.2;\nconst COLLECTIONS = [\"users\", \"orders\", \"items\", \"events\"] as const;\n\nconst round3 = (x: number): number => Math.round(x * 1000) / 1000;\n\n/**\n * This function gives the input with edges, groups and ports from its topology alone: a joint input has no positions before the pack.\n * The random numbers come from the steps `edges` and `ports` of `seed`. The function appends its stamp to `steps`, and removes the old `hash`.\n * The rules of each shape are in `docs/JOINT-CORPUS.md`.\n */\nexport function edgeStep(input: LayoutInput, params: EdgeStepParams, seed: number = input.seed ?? 0): LayoutInput {\n if ((input.edges?.length ?? 0) > 0) throw new RangeError(\"edgeStep: the input has edges already\");\n const full: Required<EdgeStepParams> = { groups: \"none\", ports: \"free\", hubBy: \"area\", ...params };\n const n = input.boxes.length;\n const r = stepRandom(seed, \"edges\");\n\n const perm = input.boxes.map((_, i) => i);\n for (let i = n - 1; i > 0; i--) {\n const j = randomInt(r, 0, i);\n [perm[i], perm[j]] = [perm[j]!, perm[i]!];\n }\n const clusterOf: number[] = new Array<number>(n);\n perm.forEach((box, p) => (clusterOf[box] = Math.floor(p / CLUSTER)));\n const clusters = Math.ceil(n / CLUSTER);\n const members = (c: number): readonly number[] => perm.slice(c * CLUSTER, (c + 1) * CLUSTER);\n const collectionOf =\n full.edgeShape === \"bundled\"\n ? clusterOf.map((c) => `${COLLECTIONS[c % COLLECTIONS.length]!}-${c}`)\n : input.boxes.map(() => COLLECTIONS[randomInt(r, 0, COLLECTIONS.length - 1)]!);\n const area = (i: number): number => input.boxes[i]!.w * input.boxes[i]!.h;\n const rank = full.hubBy === \"area\" ? input.boxes.map((_, i) => i).sort((a, b) => area(b) - area(a) || a - b) : perm;\n\n const pairs: [number, number][] = [];\n const seen = new Set<string>();\n const add = (u: number, v: number): void => {\n const key = u < v ? `${u}-${v}` : `${v}-${u}`;\n if (u === v || seen.has(key)) return;\n seen.add(key);\n pairs.push([u, v]);\n };\n const anyBox = (): number => randomInt(r, 0, n - 1);\n const inCluster = (c: number): number => {\n const m = members(c);\n return m[randomInt(r, 0, m.length - 1)]!;\n };\n const otherCluster = (c: number): number => {\n const o = randomInt(r, 0, clusters - 2);\n return o >= c ? o + 1 : o;\n };\n const target = Math.min(Math.round(n * EDGE_DENSITY[full.edgeDensity]), (n * (n - 1)) / 2);\n const fill = (pick: () => [number, number]): void => {\n for (let tries = 0; pairs.length < target && tries < target * 30; tries++) add(...pick());\n };\n const clustered = (): [number, number] => {\n const u = anyBox();\n return [u, r() < INSIDE ? inCluster(clusterOf[u]!) : anyBox()];\n };\n\n if (n >= 2) {\n switch (full.edgeShape) {\n case \"random\":\n fill(() => [anyBox(), anyBox()]);\n break;\n case \"clustered\":\n fill(clustered);\n break;\n case \"longRange\":\n fill(() => {\n const u = anyBox();\n return [u, clusters > 1 ? inCluster(otherCluster(clusterOf[u]!)) : anyBox()];\n });\n break;\n case \"hubs\":\n fill(() => [anyBox(), rank[Math.floor(n * r() ** 3)]!]);\n break;\n case \"tree\":\n for (let i = 1; i < n; i++) add(rank[randomInt(r, 0, i - 1)]!, rank[i]!);\n break;\n case \"hubChain\": {\n const k = Math.ceil(n / CHAIN);\n const length = Math.ceil(n / k);\n const chains = Array.from({ length: k }, (_, c) => perm.slice(c * length, (c + 1) * length));\n for (const chain of chains) for (let i = 0; i + 1 < chain.length; i++) add(chain[i]!, chain[i + 1]!);\n const skips = Math.max(0, target - pairs.length);\n for (let s = 0; s < skips; s++) {\n const c = k > 1 ? randomInt(r, 0, k - 2) : 0;\n const from = chains[c]!;\n const to = chains[k > 1 ? c + 1 : 0]!;\n const i = randomInt(r, 0, from.length - 1);\n const j = i + Math.floor(from.length / 8) + randomInt(r, 0, Math.floor(from.length / 2));\n if (j < to.length) add(from[i]!, to[j]!);\n }\n break;\n }\n case \"bundled\":\n for (let rounds = 0; pairs.length < target * FAN_SHARE && clusters > 1 && rounds < target; rounds++) {\n const u = anyBox();\n const c = otherCluster(clusterOf[u]!);\n const fan = randomInt(r, 4, 15);\n for (let f = 0; f < fan && pairs.length < target; f++) add(u, inCluster(c));\n }\n fill(clustered);\n break;\n }\n }\n\n const rp = stepRandom(seed, \"ports\");\n const ports: Port[][] = input.boxes.map((b) => [...(b.ports ?? [])]);\n const portOn = (box: LayoutBox, id: string, side: Side, fixed: boolean): Port => {\n if (!fixed) return { id, side };\n const along = round3(rp() * (side === \"top\" || side === \"bottom\" ? box.w : box.h));\n const at = { top: [along, 0], bottom: [along, box.h], left: [0, along], right: [box.w, along] }[side];\n return { id, side, x: at[0]!, y: at[1]! };\n };\n const out = new Set<number>();\n if (full.ports === \"fixed\") {\n input.boxes.forEach((box, i) => {\n if (rp() >= FIXED_SHARE) return;\n const side = SIDES[randomInt(rp, 0, 3)]!;\n ports[i]!.push(portOn(box, \"out\", side, true));\n out.add(i);\n });\n }\n const edges: LayoutEdge[] = pairs.map(([u, v], k) => {\n const id = `e${k}`;\n const s = input.boxes[u]!;\n const t = input.boxes[v]!;\n let ends: { sourcePort?: string; targetPort?: string } = {};\n if (full.ports === \"sides\") {\n ports[u]!.push(portOn(s, `${id}.s`, SIDES[randomInt(rp, 0, 3)]!, false));\n ports[v]!.push(portOn(t, `${id}.t`, SIDES[randomInt(rp, 0, 3)]!, false));\n ends = { sourcePort: `${id}.s`, targetPort: `${id}.t` };\n } else if (out.has(u)) {\n ends = { sourcePort: \"out\" };\n }\n return { id, source: s.id, target: t.id, ...ends, data: { collection: collectionOf[v]! } };\n });\n\n const boxes = input.boxes.map((box, i): LayoutBox => {\n const c = clusterOf[i]!;\n const group = full.groups === \"none\" ? undefined : `g${c}`;\n const path = full.groups === \"nested\" ? `G${Math.floor(c / 4)}/g${c}` : group;\n return {\n ...box,\n ...(group === undefined ? {} : { group, data: { ...box.data, group: path } }),\n ...(ports[i]!.length === 0 ? {} : { ports: ports[i]! }),\n };\n });\n const stamp: LayoutGenerator = { name: \"edges\", version: EDGE_STEP_VERSION, params: { ...full }, seed };\n const { hash: _old, ...rest } = input;\n return { ...rest, boxes, edges, steps: [...(input.steps ?? []), stamp] };\n}\n"],"mappings":";;AAIA,MAAa,QAAyB;CAAC;CAAO;CAAS;CAAU;AAAM;;AAyCvE,SAAgB,YAAY,QAAmC;CAC7D,IAAI,WAAW,KAAA,GAAW,OAAO;EAAE,KAAK;EAAG,OAAO;EAAG,QAAQ;EAAG,MAAM;CAAE;CACxE,IAAI,OAAO,WAAW,UAAU,OAAO;EAAE,KAAK;EAAQ,OAAO;EAAQ,QAAQ;EAAQ,MAAM;CAAO;CAClG,OAAO;AACT;;AAGA,SAAgB,KAAK,MAAY,QAAkC;CACjE,MAAM,IAAI,YAAY,MAAM;CAC5B,OAAO;EAAE,GAAG,KAAK,IAAI,EAAE;EAAM,GAAG,KAAK,IAAI,EAAE;EAAK,GAAG,KAAK,IAAI,EAAE,OAAO,EAAE;EAAO,GAAG,KAAK,IAAI,EAAE,MAAM,EAAE;CAAO;AAC7G;;AAGA,SAAgB,SAAS,QAAsB;CAC7C,QAAQ,OAAO,MAAf;EACE,KAAK,QACH,OAAO;GAAE,GAAG,OAAO;GAAG,GAAG,OAAO;GAAG,GAAG,OAAO;GAAG,GAAG,OAAO;EAAE;EAC9D,KAAK,UACH,OAAO;GAAE,GAAG,OAAO,KAAK,OAAO;GAAG,GAAG,OAAO,KAAK,OAAO;GAAG,GAAG,IAAI,OAAO;GAAG,GAAG,IAAI,OAAO;EAAE;EAC9F,KAAK,WACH,OAAO;GAAE,GAAG,OAAO,KAAK,OAAO;GAAI,GAAG,OAAO,KAAK,OAAO;GAAI,GAAG,IAAI,OAAO;GAAI,GAAG,IAAI,OAAO;EAAG;EAClG,KAAK,WAAW;GACd,IAAI,KAAK;GACT,IAAI,KAAK;GACT,IAAI,KAAK;GACT,IAAI,KAAK;GACT,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ;IAClC,KAAK,KA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": "@mark1russell7/layout-contract",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.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",
|
package/src/edges.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { SIDES, type Side } from "./geometry.ts";
|
|
2
|
+
import type { LayoutBox, LayoutEdge, LayoutGenerator, LayoutInput, Port } from "./input.ts";
|
|
3
|
+
import { randomInt, stepRandom } from "./random.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The shape of the edges of `edgeStep`. The values are the cells of `edgeShape`, and `hubs`.
|
|
7
|
+
* `hubs` waits for the next breaking change to become a value of `LayoutCell.edgeShape`.
|
|
8
|
+
*/
|
|
9
|
+
export type EdgeShape = "random" | "clustered" | "hubChain" | "hubs" | "longRange" | "tree" | "bundled";
|
|
10
|
+
|
|
11
|
+
/** The parameters of `edgeStep`. */
|
|
12
|
+
export interface EdgeStepParams {
|
|
13
|
+
readonly edgeDensity: "sparse" | "medium" | "dense";
|
|
14
|
+
readonly edgeShape: EdgeShape;
|
|
15
|
+
/** The default is `none`. */
|
|
16
|
+
readonly groups?: "none" | "flat" | "nested";
|
|
17
|
+
/** The default is `free`. */
|
|
18
|
+
readonly ports?: "free" | "sides" | "fixed";
|
|
19
|
+
/** The order of the hubs of `hubs` and `tree`: the largest box first, or a random order. The default is `area`. */
|
|
20
|
+
readonly hubBy?: "area" | "random";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The mean count of the edges of each box for each value of `edgeDensity`. */
|
|
24
|
+
export const EDGE_DENSITY: Readonly<Record<EdgeStepParams["edgeDensity"], number>> = Object.freeze({ sparse: 0.5, medium: 1.5, dense: 4 });
|
|
25
|
+
|
|
26
|
+
/** The version of `edgeStep`. A change of its output gives a new version. */
|
|
27
|
+
export const EDGE_STEP_VERSION = 1;
|
|
28
|
+
|
|
29
|
+
const CLUSTER = 8;
|
|
30
|
+
const CHAIN = 32;
|
|
31
|
+
const INSIDE = 0.85;
|
|
32
|
+
const FAN_SHARE = 0.6;
|
|
33
|
+
const FIXED_SHARE = 0.2;
|
|
34
|
+
const COLLECTIONS = ["users", "orders", "items", "events"] as const;
|
|
35
|
+
|
|
36
|
+
const round3 = (x: number): number => Math.round(x * 1000) / 1000;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* This function gives the input with edges, groups and ports from its topology alone: a joint input has no positions before the pack.
|
|
40
|
+
* The random numbers come from the steps `edges` and `ports` of `seed`. The function appends its stamp to `steps`, and removes the old `hash`.
|
|
41
|
+
* The rules of each shape are in `docs/JOINT-CORPUS.md`.
|
|
42
|
+
*/
|
|
43
|
+
export function edgeStep(input: LayoutInput, params: EdgeStepParams, seed: number = input.seed ?? 0): LayoutInput {
|
|
44
|
+
if ((input.edges?.length ?? 0) > 0) throw new RangeError("edgeStep: the input has edges already");
|
|
45
|
+
const full: Required<EdgeStepParams> = { groups: "none", ports: "free", hubBy: "area", ...params };
|
|
46
|
+
const n = input.boxes.length;
|
|
47
|
+
const r = stepRandom(seed, "edges");
|
|
48
|
+
|
|
49
|
+
const perm = input.boxes.map((_, i) => i);
|
|
50
|
+
for (let i = n - 1; i > 0; i--) {
|
|
51
|
+
const j = randomInt(r, 0, i);
|
|
52
|
+
[perm[i], perm[j]] = [perm[j]!, perm[i]!];
|
|
53
|
+
}
|
|
54
|
+
const clusterOf: number[] = new Array<number>(n);
|
|
55
|
+
perm.forEach((box, p) => (clusterOf[box] = Math.floor(p / CLUSTER)));
|
|
56
|
+
const clusters = Math.ceil(n / CLUSTER);
|
|
57
|
+
const members = (c: number): readonly number[] => perm.slice(c * CLUSTER, (c + 1) * CLUSTER);
|
|
58
|
+
const collectionOf =
|
|
59
|
+
full.edgeShape === "bundled"
|
|
60
|
+
? clusterOf.map((c) => `${COLLECTIONS[c % COLLECTIONS.length]!}-${c}`)
|
|
61
|
+
: input.boxes.map(() => COLLECTIONS[randomInt(r, 0, COLLECTIONS.length - 1)]!);
|
|
62
|
+
const area = (i: number): number => input.boxes[i]!.w * input.boxes[i]!.h;
|
|
63
|
+
const rank = full.hubBy === "area" ? input.boxes.map((_, i) => i).sort((a, b) => area(b) - area(a) || a - b) : perm;
|
|
64
|
+
|
|
65
|
+
const pairs: [number, number][] = [];
|
|
66
|
+
const seen = new Set<string>();
|
|
67
|
+
const add = (u: number, v: number): void => {
|
|
68
|
+
const key = u < v ? `${u}-${v}` : `${v}-${u}`;
|
|
69
|
+
if (u === v || seen.has(key)) return;
|
|
70
|
+
seen.add(key);
|
|
71
|
+
pairs.push([u, v]);
|
|
72
|
+
};
|
|
73
|
+
const anyBox = (): number => randomInt(r, 0, n - 1);
|
|
74
|
+
const inCluster = (c: number): number => {
|
|
75
|
+
const m = members(c);
|
|
76
|
+
return m[randomInt(r, 0, m.length - 1)]!;
|
|
77
|
+
};
|
|
78
|
+
const otherCluster = (c: number): number => {
|
|
79
|
+
const o = randomInt(r, 0, clusters - 2);
|
|
80
|
+
return o >= c ? o + 1 : o;
|
|
81
|
+
};
|
|
82
|
+
const target = Math.min(Math.round(n * EDGE_DENSITY[full.edgeDensity]), (n * (n - 1)) / 2);
|
|
83
|
+
const fill = (pick: () => [number, number]): void => {
|
|
84
|
+
for (let tries = 0; pairs.length < target && tries < target * 30; tries++) add(...pick());
|
|
85
|
+
};
|
|
86
|
+
const clustered = (): [number, number] => {
|
|
87
|
+
const u = anyBox();
|
|
88
|
+
return [u, r() < INSIDE ? inCluster(clusterOf[u]!) : anyBox()];
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
if (n >= 2) {
|
|
92
|
+
switch (full.edgeShape) {
|
|
93
|
+
case "random":
|
|
94
|
+
fill(() => [anyBox(), anyBox()]);
|
|
95
|
+
break;
|
|
96
|
+
case "clustered":
|
|
97
|
+
fill(clustered);
|
|
98
|
+
break;
|
|
99
|
+
case "longRange":
|
|
100
|
+
fill(() => {
|
|
101
|
+
const u = anyBox();
|
|
102
|
+
return [u, clusters > 1 ? inCluster(otherCluster(clusterOf[u]!)) : anyBox()];
|
|
103
|
+
});
|
|
104
|
+
break;
|
|
105
|
+
case "hubs":
|
|
106
|
+
fill(() => [anyBox(), rank[Math.floor(n * r() ** 3)]!]);
|
|
107
|
+
break;
|
|
108
|
+
case "tree":
|
|
109
|
+
for (let i = 1; i < n; i++) add(rank[randomInt(r, 0, i - 1)]!, rank[i]!);
|
|
110
|
+
break;
|
|
111
|
+
case "hubChain": {
|
|
112
|
+
const k = Math.ceil(n / CHAIN);
|
|
113
|
+
const length = Math.ceil(n / k);
|
|
114
|
+
const chains = Array.from({ length: k }, (_, c) => perm.slice(c * length, (c + 1) * length));
|
|
115
|
+
for (const chain of chains) for (let i = 0; i + 1 < chain.length; i++) add(chain[i]!, chain[i + 1]!);
|
|
116
|
+
const skips = Math.max(0, target - pairs.length);
|
|
117
|
+
for (let s = 0; s < skips; s++) {
|
|
118
|
+
const c = k > 1 ? randomInt(r, 0, k - 2) : 0;
|
|
119
|
+
const from = chains[c]!;
|
|
120
|
+
const to = chains[k > 1 ? c + 1 : 0]!;
|
|
121
|
+
const i = randomInt(r, 0, from.length - 1);
|
|
122
|
+
const j = i + Math.floor(from.length / 8) + randomInt(r, 0, Math.floor(from.length / 2));
|
|
123
|
+
if (j < to.length) add(from[i]!, to[j]!);
|
|
124
|
+
}
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
case "bundled":
|
|
128
|
+
for (let rounds = 0; pairs.length < target * FAN_SHARE && clusters > 1 && rounds < target; rounds++) {
|
|
129
|
+
const u = anyBox();
|
|
130
|
+
const c = otherCluster(clusterOf[u]!);
|
|
131
|
+
const fan = randomInt(r, 4, 15);
|
|
132
|
+
for (let f = 0; f < fan && pairs.length < target; f++) add(u, inCluster(c));
|
|
133
|
+
}
|
|
134
|
+
fill(clustered);
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const rp = stepRandom(seed, "ports");
|
|
140
|
+
const ports: Port[][] = input.boxes.map((b) => [...(b.ports ?? [])]);
|
|
141
|
+
const portOn = (box: LayoutBox, id: string, side: Side, fixed: boolean): Port => {
|
|
142
|
+
if (!fixed) return { id, side };
|
|
143
|
+
const along = round3(rp() * (side === "top" || side === "bottom" ? box.w : box.h));
|
|
144
|
+
const at = { top: [along, 0], bottom: [along, box.h], left: [0, along], right: [box.w, along] }[side];
|
|
145
|
+
return { id, side, x: at[0]!, y: at[1]! };
|
|
146
|
+
};
|
|
147
|
+
const out = new Set<number>();
|
|
148
|
+
if (full.ports === "fixed") {
|
|
149
|
+
input.boxes.forEach((box, i) => {
|
|
150
|
+
if (rp() >= FIXED_SHARE) return;
|
|
151
|
+
const side = SIDES[randomInt(rp, 0, 3)]!;
|
|
152
|
+
ports[i]!.push(portOn(box, "out", side, true));
|
|
153
|
+
out.add(i);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
const edges: LayoutEdge[] = pairs.map(([u, v], k) => {
|
|
157
|
+
const id = `e${k}`;
|
|
158
|
+
const s = input.boxes[u]!;
|
|
159
|
+
const t = input.boxes[v]!;
|
|
160
|
+
let ends: { sourcePort?: string; targetPort?: string } = {};
|
|
161
|
+
if (full.ports === "sides") {
|
|
162
|
+
ports[u]!.push(portOn(s, `${id}.s`, SIDES[randomInt(rp, 0, 3)]!, false));
|
|
163
|
+
ports[v]!.push(portOn(t, `${id}.t`, SIDES[randomInt(rp, 0, 3)]!, false));
|
|
164
|
+
ends = { sourcePort: `${id}.s`, targetPort: `${id}.t` };
|
|
165
|
+
} else if (out.has(u)) {
|
|
166
|
+
ends = { sourcePort: "out" };
|
|
167
|
+
}
|
|
168
|
+
return { id, source: s.id, target: t.id, ...ends, data: { collection: collectionOf[v]! } };
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const boxes = input.boxes.map((box, i): LayoutBox => {
|
|
172
|
+
const c = clusterOf[i]!;
|
|
173
|
+
const group = full.groups === "none" ? undefined : `g${c}`;
|
|
174
|
+
const path = full.groups === "nested" ? `G${Math.floor(c / 4)}/g${c}` : group;
|
|
175
|
+
return {
|
|
176
|
+
...box,
|
|
177
|
+
...(group === undefined ? {} : { group, data: { ...box.data, group: path } }),
|
|
178
|
+
...(ports[i]!.length === 0 ? {} : { ports: ports[i]! }),
|
|
179
|
+
};
|
|
180
|
+
});
|
|
181
|
+
const stamp: LayoutGenerator = { name: "edges", version: EDGE_STEP_VERSION, params: { ...full }, seed };
|
|
182
|
+
const { hash: _old, ...rest } = input;
|
|
183
|
+
return { ...rest, boxes, edges, steps: [...(input.steps ?? []), stamp] };
|
|
184
|
+
}
|
package/src/index.ts
CHANGED
package/src/input.ts
CHANGED
|
@@ -107,6 +107,8 @@ export interface LayoutInput {
|
|
|
107
107
|
readonly hash?: string;
|
|
108
108
|
/** The generator of the input. `null` or no value tells that a person made the input. */
|
|
109
109
|
readonly generator?: LayoutGenerator | null;
|
|
110
|
+
/** The steps that changed the input after its generator, in their order. `edgeStep` adds one. */
|
|
111
|
+
readonly steps?: readonly LayoutGenerator[];
|
|
110
112
|
readonly cell?: LayoutCell;
|
|
111
113
|
/** The place of the input in a sequence of changes. */
|
|
112
114
|
readonly step?: number;
|
package/src/random.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`. */
|
|
2
|
+
export function mulberry32(seed: number): () => number {
|
|
3
|
+
let s = seed >>> 0;
|
|
4
|
+
return () => {
|
|
5
|
+
s = (s + 0x6d2b79f5) | 0;
|
|
6
|
+
let t = Math.imul(s ^ (s >>> 15), 1 | s);
|
|
7
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
8
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** This function gives the FNV-1a hash of 32 bits of the UTF-8 bytes of a string. */
|
|
13
|
+
export function fnv1a32(text: string): number {
|
|
14
|
+
let h = 0x811c9dc5;
|
|
15
|
+
for (const b of utf8(text)) h = Math.imul(h ^ b, 0x01000193) >>> 0;
|
|
16
|
+
return h;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The UTF-8 bytes of a string. The package has no runtime dependencies, thus it does not use `TextEncoder`. */
|
|
20
|
+
function utf8(text: string): number[] {
|
|
21
|
+
const bytes: number[] = [];
|
|
22
|
+
for (const ch of text) {
|
|
23
|
+
const c = ch.codePointAt(0)!;
|
|
24
|
+
if (c < 0x80) bytes.push(c);
|
|
25
|
+
else if (c < 0x800) bytes.push(0xc0 | (c >> 6), 0x80 | (c & 63));
|
|
26
|
+
else if (c < 0x10000) bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
27
|
+
else bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
28
|
+
}
|
|
29
|
+
return bytes;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** This function gives the generator of one step of a seeded generator: `mulberry32(fnv1a32("<seed>:<step>"))`. */
|
|
33
|
+
export function stepRandom(seed: number, step: string): () => number {
|
|
34
|
+
return mulberry32(fnv1a32(`${seed}:${step}`));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** This function gives a whole number from `lo` to `hi`, both included. */
|
|
38
|
+
export function randomInt(r: () => number, lo: number, hi: number): number {
|
|
39
|
+
return lo + Math.floor(r() * (hi - lo + 1));
|
|
40
|
+
}
|
package/src/rules.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { boundsOf, grow, overlapOf, type Rect, type Region } from "./geometry.ts";
|
|
2
2
|
import type { LayoutBox, LayoutInput, Obstacle } from "./input.ts";
|
|
3
3
|
import { applyPack, type PackOutput } from "./output.ts";
|
|
4
|
-
import { DEFAULT_TOLERANCE, RECORD_EPS } from "./tolerance.ts";
|
|
4
|
+
import { DEFAULT_TOLERANCE, EPS, RECORD_EPS } from "./tolerance.ts";
|
|
5
5
|
|
|
6
6
|
/** This function gives the area of a placed box: its shape or its rectangle, at its position. A box without a position gives `undefined`. */
|
|
7
7
|
export function placedRect(box: LayoutBox): Rect | undefined {
|
|
@@ -35,14 +35,27 @@ export function countOverlaps(boxes: readonly LayoutBox[], tolerance: number = D
|
|
|
35
35
|
return count;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/** The options of the container test of `countOutside` and `packHard`. */
|
|
39
|
+
export interface ContainerTest {
|
|
40
|
+
/**
|
|
41
|
+
* With `true`, a box of a shaped container with the size `fixed` must stay inside the shape, not only inside its bounding box.
|
|
42
|
+
* The default is `false`. The default changes to `true` at the next breaking version.
|
|
43
|
+
*/
|
|
44
|
+
readonly exactContainer?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
38
47
|
/**
|
|
39
48
|
* This function counts the placed boxes that go out of the container.
|
|
40
49
|
* Each box with its margin must stay inside the container made smaller by `inset`. Only the fixed sides of the size count. A shaped container counts as its bounding box.
|
|
50
|
+
*
|
|
51
|
+
* With `exactContainer`, a box of a shaped container with the size `fixed` also counts when `rectInRegion` tells that it is not inside the shape.
|
|
52
|
+
* For that test, the box grows by `inset` and becomes smaller by `tolerance` on each side. A shaped container with a free side keeps the bounding test only.
|
|
41
53
|
* An input without a container gives 0.
|
|
42
54
|
*/
|
|
43
|
-
export function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOLERANCE.overlap): number {
|
|
55
|
+
export function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOLERANCE.overlap, options: ContainerTest = {}): number {
|
|
44
56
|
const c = input.container;
|
|
45
57
|
if (c === undefined) return 0;
|
|
58
|
+
const shape = options.exactContainer === true && c.fixed === "size" ? c.shape : undefined;
|
|
46
59
|
const area = c.shape === undefined ? { x: 0, y: 0, w: c.w ?? Infinity, h: c.h ?? Infinity } : boundsOf(c.shape);
|
|
47
60
|
const inset = c.inset ?? 0;
|
|
48
61
|
const fixW = c.fixed === "size" || c.fixed === "width";
|
|
@@ -55,6 +68,7 @@ export function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOL
|
|
|
55
68
|
const outX = r.x < area.x + inset - tolerance || r.x + r.w > area.x + area.w - inset + tolerance;
|
|
56
69
|
const outY = r.y < area.y + inset - tolerance || r.y + r.h > area.y + area.h - inset + tolerance;
|
|
57
70
|
if ((fixW && outX) || (fixH && outY)) count++;
|
|
71
|
+
else if (shape !== undefined && !rectInRegion(shape, shrink(grow(r, inset), tolerance))) count++;
|
|
58
72
|
}
|
|
59
73
|
return count;
|
|
60
74
|
}
|
|
@@ -111,6 +125,72 @@ export function regionHitsRect(region: Region, rect: Rect): boolean {
|
|
|
111
125
|
}
|
|
112
126
|
}
|
|
113
127
|
|
|
128
|
+
/**
|
|
129
|
+
* This function tells if all of `rect` is inside `region`. A point on the border counts as inside. No part of `rect` can overlap a hole.
|
|
130
|
+
* The test of a circle, an ellipse or a polygon accepts an error of `EPS` on the border. A polygon can be concave.
|
|
131
|
+
*/
|
|
132
|
+
export function rectInRegion(region: Region, rect: Rect): boolean {
|
|
133
|
+
const x1 = rect.x + rect.w;
|
|
134
|
+
const y1 = rect.y + rect.h;
|
|
135
|
+
const corners: readonly (readonly [number, number])[] = [
|
|
136
|
+
[rect.x, rect.y],
|
|
137
|
+
[x1, rect.y],
|
|
138
|
+
[x1, y1],
|
|
139
|
+
[rect.x, y1],
|
|
140
|
+
];
|
|
141
|
+
switch (region.kind) {
|
|
142
|
+
case "rect":
|
|
143
|
+
return rect.x >= region.x && rect.y >= region.y && x1 <= region.x + region.w && y1 <= region.y + region.h;
|
|
144
|
+
case "circle":
|
|
145
|
+
return corners.every(([x, y]) => inEllipse(region.cx, region.cy, region.r, region.r, x, y));
|
|
146
|
+
case "ellipse":
|
|
147
|
+
return corners.every(([x, y]) => inEllipse(region.cx, region.cy, region.rx, region.ry, x, y));
|
|
148
|
+
case "polygon": {
|
|
149
|
+
const ring = region.points;
|
|
150
|
+
if (ring.length < 3) return false;
|
|
151
|
+
const points = [...corners, [rect.x + rect.w / 2, rect.y + rect.h / 2] as const];
|
|
152
|
+
if (!points.every(([x, y]) => onRing(x, y, ring) || pointInRings(x, y, [ring]))) return false;
|
|
153
|
+
const deep = (x: number, y: number): boolean => x > rect.x + EPS && x < x1 - EPS && y > rect.y + EPS && y < y1 - EPS;
|
|
154
|
+
for (let i = 0; i < ring.length; i++) {
|
|
155
|
+
const a = ring[i]!;
|
|
156
|
+
const b = ring[(i + 1) % ring.length]!;
|
|
157
|
+
const m = clipMid(a[0], a[1], b[0], b[1], rect);
|
|
158
|
+
if (m !== undefined && deep(m[0], m[1])) return false;
|
|
159
|
+
}
|
|
160
|
+
return (region.holes ?? []).every((hole) => !regionHitsRect({ kind: "polygon", points: hole }, rect));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** This function gives the rectangle made smaller by `d` on each side. A side does not become smaller than 0. */
|
|
166
|
+
function shrink(r: Rect, d: number): Rect {
|
|
167
|
+
const dx = Math.min(d, r.w / 2);
|
|
168
|
+
const dy = Math.min(d, r.h / 2);
|
|
169
|
+
return { x: r.x + dx, y: r.y + dy, w: r.w - 2 * dx, h: r.h - 2 * dy };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** This function tells if a point is inside an ellipse or on its border, with an error of `EPS`. */
|
|
173
|
+
function inEllipse(cx: number, cy: number, rx: number, ry: number, x: number, y: number): boolean {
|
|
174
|
+
if (rx <= 0 || ry <= 0) return false;
|
|
175
|
+
const u = (x - cx) / rx;
|
|
176
|
+
const v = (y - cy) / ry;
|
|
177
|
+
return u * u + v * v <= 1 + EPS;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** This function tells if a point is on a ring of a polygon, with an error of `EPS`. */
|
|
181
|
+
function onRing(x: number, y: number, ring: readonly (readonly [number, number])[]): boolean {
|
|
182
|
+
for (let i = 0; i < ring.length; i++) {
|
|
183
|
+
const [ax, ay] = ring[i]!;
|
|
184
|
+
const [bx, by] = ring[(i + 1) % ring.length]!;
|
|
185
|
+
const dx = bx - ax;
|
|
186
|
+
const dy = by - ay;
|
|
187
|
+
const len2 = dx * dx + dy * dy;
|
|
188
|
+
const t = len2 === 0 ? 0 : Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / len2));
|
|
189
|
+
if (Math.hypot(x - (ax + t * dx), y - (ay + t * dy)) <= EPS) return true;
|
|
190
|
+
}
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
|
|
114
194
|
/** An ellipse with the radii `rx` and `ry` scales to a unit circle. The rectangle scales with it. */
|
|
115
195
|
function circleHitsRect(cx: number, cy: number, rx: number, ry: number, rect: Rect): boolean {
|
|
116
196
|
if (rx <= 0 || ry <= 0) return false;
|
|
@@ -190,8 +270,10 @@ export function countObstacleHits(
|
|
|
190
270
|
* A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`.
|
|
191
271
|
* A locked box without a position in the input is a bad input, not a break. `checkInput` finds it.
|
|
192
272
|
* Another box without a placement that is not in `overflow` breaks `complete`.
|
|
273
|
+
*
|
|
274
|
+
* `options` goes to `countOutside` for `in-container`.
|
|
193
275
|
*/
|
|
194
|
-
export function packHard(input: LayoutInput, output: PackOutput, tolerance: number = DEFAULT_TOLERANCE.overlap): PackHard {
|
|
276
|
+
export function packHard(input: LayoutInput, output: PackOutput, tolerance: number = DEFAULT_TOLERANCE.overlap, options: ContainerTest = {}): PackHard {
|
|
195
277
|
const after = applyPack(input, output);
|
|
196
278
|
const placed = new Set(output.placements.map((p) => p.id));
|
|
197
279
|
const out = new Set(output.overflow);
|
|
@@ -214,7 +296,7 @@ export function packHard(input: LayoutInput, output: PackOutput, tolerance: numb
|
|
|
214
296
|
}
|
|
215
297
|
return {
|
|
216
298
|
"no-overlap": countOverlaps(kept, tolerance) + countObstacleHits(kept, after.obstacles, tolerance),
|
|
217
|
-
"in-container": countOutside({ ...after, boxes: kept }, tolerance),
|
|
299
|
+
"in-container": countOutside({ ...after, boxes: kept }, tolerance, options),
|
|
218
300
|
"locked-kept": lockedMoved,
|
|
219
301
|
complete: incomplete,
|
|
220
302
|
};
|