@mark1russell7/layout-contract 0.9.9 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ import type { Direction } from "./measures.ts";
2
+
3
+ /** The schema of a measure survey. */
4
+ export const MEASURE_SURVEY_SCHEMA = "measure-survey/1";
5
+
6
+ /** One measure of a source, as the source declares it. A source without a range has no `min` and no `max`. */
7
+ export interface SurveyMeasure {
8
+ readonly id: string;
9
+ readonly unit: string;
10
+ readonly direction: Direction;
11
+ readonly family?: string;
12
+ readonly min?: number;
13
+ /** The highest value. JSON has no `Infinity`, so `null` tells that the measure has no upper limit. */
14
+ readonly max?: number | null;
15
+ }
16
+
17
+ /** The measures of one package at one version. */
18
+ export interface SurveySource {
19
+ readonly package: string;
20
+ readonly version: string;
21
+ readonly measures: readonly SurveyMeasure[];
22
+ }
23
+
24
+ /** A list of the measures of each package, kept as data in `docs/measure-survey.json`. */
25
+ export interface MeasureSurvey {
26
+ readonly schema: typeof MEASURE_SURVEY_SCHEMA;
27
+ /** The day of the survey, as `YYYY-MM-DD`. */
28
+ readonly date: string;
29
+ readonly sources: readonly SurveySource[];
30
+ }
31
+
32
+ /**
33
+ * Two measures of two sources with one name after the stage, for example `pack.fill` and `joint.fill`, and another unit or direction.
34
+ * The name after the stage is the id without its first part.
35
+ */
36
+ export interface TwinConflict {
37
+ readonly name: string;
38
+ readonly field: "unit" | "direction";
39
+ /** The id and the value of each measure of the twins. */
40
+ readonly values: readonly { readonly id: string; readonly source: string; readonly value: string }[];
41
+ }
42
+
43
+ /** The facts of a survey that feed the idea queue. */
44
+ export interface SurveyFindings {
45
+ /** The count of the distinct ids over all sources. */
46
+ readonly ids: number;
47
+ /** The count of the measures of each source. */
48
+ readonly bySource: Readonly<Record<string, number>>;
49
+ /** The ids that two sources declare, with another unit or direction. */
50
+ readonly conflicts: readonly { readonly id: string; readonly field: "unit" | "direction"; readonly sources: readonly string[] }[];
51
+ /** The twins of two sources with another unit or another direction. */
52
+ readonly twins: readonly TwinConflict[];
53
+ /** The ids without a range. An objective cannot normalize them with the rule `range` or `scale`. */
54
+ readonly noRange: readonly string[];
55
+ /** The distinct units, with the count of the measures of each. */
56
+ readonly units: Readonly<Record<string, number>>;
57
+ }
58
+
59
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
60
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
61
+
62
+ /** This function gives the faults of a survey, as plain text. An empty list tells that the survey is good. */
63
+ export function checkSurvey(v: unknown): string[] {
64
+ const out: string[] = [];
65
+ if (!isObj(v)) return ["the survey is not an object"];
66
+ if (v["schema"] !== MEASURE_SURVEY_SCHEMA) out.push(`the schema is not ${MEASURE_SURVEY_SCHEMA}`);
67
+ if (typeof v["date"] !== "string" || !DATE.test(v["date"])) out.push("the date is not YYYY-MM-DD");
68
+ const sources = v["sources"];
69
+ if (!Array.isArray(sources) || sources.length === 0) return [...out, "the survey has no sources"];
70
+ const names = new Set<string>();
71
+ for (const [i, s] of sources.entries()) {
72
+ const at = `sources[${i}]`;
73
+ if (!isObj(s)) {
74
+ out.push(`${at} is not an object`);
75
+ continue;
76
+ }
77
+ if (typeof s["package"] !== "string" || s["package"].length === 0) out.push(`${at}.package is empty`);
78
+ else if (names.has(s["package"])) out.push(`${at}.package ${s["package"]} is not unique`);
79
+ else names.add(s["package"]);
80
+ if (typeof s["version"] !== "string" || s["version"].length === 0) out.push(`${at}.version is empty`);
81
+ const measures = s["measures"];
82
+ if (!Array.isArray(measures)) {
83
+ out.push(`${at}.measures is not a list`);
84
+ continue;
85
+ }
86
+ const ids = new Set<string>();
87
+ for (const [j, m] of measures.entries()) {
88
+ const mat = `${at}.measures[${j}]`;
89
+ if (!isObj(m)) {
90
+ out.push(`${mat} is not an object`);
91
+ continue;
92
+ }
93
+ if (typeof m["id"] !== "string" || m["id"].length === 0) out.push(`${mat}.id is empty`);
94
+ else if (ids.has(m["id"])) out.push(`${mat}.id ${m["id"]} is not unique in its source`);
95
+ else ids.add(m["id"]);
96
+ if (typeof m["unit"] !== "string" || m["unit"].length === 0) out.push(`${mat}.unit is empty`);
97
+ if (m["direction"] !== "lower" && m["direction"] !== "higher") out.push(`${mat}.direction is not lower or higher`);
98
+ const min = m["min"];
99
+ const max = m["max"];
100
+ if ((min === undefined) !== (max === undefined)) out.push(`${mat} has min or max, not both`);
101
+ if (min !== undefined && (typeof min !== "number" || !Number.isFinite(min))) out.push(`${mat}.min is not a finite number`);
102
+ if (max !== undefined && max !== null && (typeof max !== "number" || !Number.isFinite(max) || !(typeof min === "number" && max > min))) out.push(`${mat}.max is not a number above min, or null`);
103
+ }
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /** This function gives the name of an id after its stage: the id without its first part. An id without a dot is its own name. */
109
+ export function nameAfterStage(id: string): string {
110
+ const dot = id.indexOf(".");
111
+ return dot < 0 ? id : id.slice(dot + 1);
112
+ }
113
+
114
+ /** This function gives the findings of a good survey. `checkSurvey` examines the survey first. */
115
+ export function surveyFindings(survey: MeasureSurvey): SurveyFindings {
116
+ const bySource: Record<string, number> = {};
117
+ const byId = new Map<string, { source: string; m: SurveyMeasure }[]>();
118
+ const units: Record<string, number> = {};
119
+ const noRange = new Set<string>();
120
+ for (const s of survey.sources) {
121
+ bySource[s.package] = s.measures.length;
122
+ for (const m of s.measures) {
123
+ const list = byId.get(m.id) ?? [];
124
+ list.push({ source: s.package, m });
125
+ byId.set(m.id, list);
126
+ units[m.unit] = (units[m.unit] ?? 0) + 1;
127
+ if (m.min === undefined) noRange.add(m.id);
128
+ }
129
+ }
130
+ const conflicts: { id: string; field: "unit" | "direction"; sources: string[] }[] = [];
131
+ for (const [id, list] of byId)
132
+ for (const field of ["unit", "direction"] as const)
133
+ if (new Set(list.map((e) => e.m[field])).size > 1) conflicts.push({ id, field, sources: list.map((e) => e.source) });
134
+
135
+ const byName = new Map<string, { id: string; source: string; m: SurveyMeasure }[]>();
136
+ for (const [id, list] of byId) {
137
+ const name = nameAfterStage(id);
138
+ const group = byName.get(name) ?? [];
139
+ for (const e of list) group.push({ id, ...e });
140
+ byName.set(name, group);
141
+ }
142
+ const twins: TwinConflict[] = [];
143
+ for (const [name, group] of [...byName].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
144
+ if (new Set(group.map((e) => e.source)).size < 2) continue;
145
+ for (const field of ["unit", "direction"] as const)
146
+ if (new Set(group.map((e) => e.m[field])).size > 1) twins.push({ name, field, values: group.map((e) => ({ id: e.id, source: e.source, value: e.m[field] })) });
147
+ }
148
+ return { ids: byId.size, bySource, conflicts, twins, noRange: [...noRange].sort(), units };
149
+ }
package/src/measures.ts CHANGED
@@ -62,14 +62,14 @@ const AREA: readonly ShapeKind[] = ["rect"];
62
62
  * `joint.fill` and `joint.straight.length` read the area of each box, so they support only `rect`. `docs/SHAPES.md` tells the reasons.
63
63
  */
64
64
  export const JOINT_MEASURES: readonly MeasureSpec<JointMeasureId>[] = /* @__PURE__ */ Object.freeze([
65
- { id: "joint.fill", minEffect: 0.001, unit: "0 to 1", direction: "higher", min: 0, max: 1, floor: 1, role: "guard", shapes: AREA },
65
+ { id: "joint.fill", minEffect: 0.001, unit: "share", direction: "higher", min: 0, max: 1, floor: 1, role: "guard", shapes: AREA },
66
66
  { id: "joint.aspectError", minEffect: 0.01, unit: "natural log", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.01, role: "guard", shapes: BOUNDS_ONLY },
67
- { id: "joint.spill", minEffect: 0.001, unit: "0 to 1", direction: "lower", min: 0, max: 1, floor: 0, tol: 0.001, role: "guard", shapes: BOUNDS_ONLY },
67
+ { id: "joint.spill", minEffect: 0.001, unit: "share", direction: "lower", min: 0, max: 1, floor: 0, tol: 0.001, role: "guard", shapes: BOUNDS_ONLY },
68
68
  { id: "joint.straight.crossings", minEffect: 0, unit: "count", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0, role: "guard", shapes: BOUNDS_ONLY },
69
69
  { 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", shapes: AREA },
70
70
  { id: "joint.stability.mean", minEffect: 0.005, unit: "W", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, role: "change-guard", shapes: BOUNDS_ONLY },
71
- { 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", shapes: BOUNDS_ONLY },
72
- { id: "joint.proxy.rank", unit: "-1 to 1", direction: "higher", min: -1, max: 1, role: "diagnostic", shapes: BOUNDS_ONLY },
71
+ { id: "joint.stability.moved", minEffect: 0.02, unit: "share", direction: "lower", min: 0, max: 1, floor: 0, tol: 0.02, role: "change-guard", shapes: BOUNDS_ONLY },
72
+ { id: "joint.proxy.rank", unit: "no unit", direction: "higher", min: -1, max: 1, role: "diagnostic", shapes: BOUNDS_ONLY },
73
73
  { id: "joint.route.length", unit: "layout units for each route", direction: "lower", min: 0, max: Infinity, role: "diagnostic", shapes: BOUNDS_ONLY },
74
74
  { id: "joint.ms", unit: "milliseconds", direction: "lower", min: 0, max: Infinity, role: "time", shapes: BOUNDS_ONLY },
75
75
  ] as const);
package/src/output.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { boundsOf, translate } from "./geometry.ts";
2
- import type { LayoutInput } from "./input.ts";
1
+ import { boundsOf, translate, type Region } from "./geometry.ts";
2
+ import type { LayoutBox, LayoutInput } from "./input.ts";
3
3
  import { resizeBox } from "./resize.ts";
4
4
  import { turnBox } from "./turn.ts";
5
5
 
@@ -14,6 +14,11 @@ export interface Placement {
14
14
  readonly turn?: 0 | 90;
15
15
  readonly w?: number;
16
16
  readonly h?: number;
17
+ /**
18
+ * The shape of the placed box, relative to its origin, as `LayoutBox.shape`. Only a box with `resize.reshape` can get it (`size-kept`).
19
+ * The shape stays inside the box: `w` by `h` of the placement, or of the box without them.
20
+ */
21
+ readonly shape?: Region;
17
22
  }
18
23
 
19
24
  /** The facts of one stage of a strategy, for the records and the site. */
@@ -35,12 +40,19 @@ export interface PackOutput {
35
40
  readonly trace?: readonly StageTrace[];
36
41
  }
37
42
 
43
+ /** This function gives a box with the shape `shape` and without its `shapeKind`. */
44
+ function reshaped(box: LayoutBox, shape: Region): LayoutBox {
45
+ const { shapeKind: _kind, ...rest } = box;
46
+ return { ...rest, shape };
47
+ }
48
+
38
49
  /**
39
50
  * This function gives the input with the output of a packer applied. Each placed box gets its position.
40
51
  * A turned box gets its turned size, ports, margin and shape. Each moved obstacle moves.
41
52
  * The container gets the size of the output. The router reads this result. It does not read `turn`.
42
53
  *
43
54
  * A placement with `w` or `h` gives the box that size after the turn (`resizeBox`).
55
+ * A placement with `shape` gives the box that shape. The box loses its `shapeKind`, so `shapeKindOf` reads the kind of the new shape.
44
56
  */
45
57
  export function applyPack(input: LayoutInput, output: PackOutput): LayoutInput {
46
58
  const at = new Map(output.placements.map((p) => [p.id, p]));
@@ -50,7 +62,7 @@ export function applyPack(input: LayoutInput, output: PackOutput): LayoutInput {
50
62
  if (p === undefined) return box;
51
63
  const turned = p.turn === 90 ? turnBox(box) : box;
52
64
  const sized = p.w === undefined && p.h === undefined ? turned : resizeBox(turned, p.w ?? turned.w, p.h ?? turned.h);
53
- return { ...sized, x: p.x, y: p.y };
65
+ return { ...(p.shape === undefined ? sized : reshaped(sized, p.shape)), x: p.x, y: p.y };
54
66
  });
55
67
  const obstacles = input.obstacles?.map((o) => {
56
68
  const m = moved.get(o.id);
package/src/resize.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  // The resize of a box (`LayoutBox.resize`): the sizes that a packer can give a box, and the box at a new size.
2
+ import { boundsOf, type Region } from "./geometry.ts";
2
3
  import type { LayoutBox, Port } from "./input.ts";
3
4
  import { shapeKindOf } from "./shapes.ts";
4
5
  import { RECORD_EPS } from "./tolerance.ts";
@@ -44,6 +45,16 @@ export function sizeFits(box: LayoutBox, w: number, h: number): boolean {
44
45
  return b.aspect === "free" || Math.abs(w * box.h - h * box.w) <= RECORD_EPS * (box.w + box.h);
45
46
  }
46
47
 
48
+ /**
49
+ * This function tells if a placement can give a box the shape `shape` at the size `w` by `h`.
50
+ * The box needs `resize.reshape`, and the bounding box of the shape stays inside the rectangle from 0, 0 to `w`, `h`, with the tolerance `RECORD_EPS`.
51
+ */
52
+ export function shapeFits(box: LayoutBox, shape: Region, w: number, h: number): boolean {
53
+ if (box.resize?.reshape !== true) return false;
54
+ const b = boundsOf(shape);
55
+ return b.x >= -RECORD_EPS && b.y >= -RECORD_EPS && b.x + b.w <= w + RECORD_EPS && b.y + b.h <= h + RECORD_EPS;
56
+ }
57
+
47
58
  /** This function gives a port of a box of the size `w` by `h` after a resize to `toW` by `toH`. A port with `along` keeps its value. */
48
59
  function resizePort(port: Port, w: number, h: number, toW: number, toH: number): Port {
49
60
  return {
@@ -71,7 +82,7 @@ export function resizeBox(box: LayoutBox, w: number, h: number): LayoutBox {
71
82
  /**
72
83
  * This function gives the problems of the `resize` of a box. A box without `resize` has no problem.
73
84
  * Only a `rect` box without a shape can have a resize. Each bound is a positive finite number.
74
- * The size of the box is in its bounds, and `aspect` is `keep` or `free`.
85
+ * The size of the box is in its bounds, `aspect` is `keep` or `free`, and `reshape` is `true` or `false`.
75
86
  */
76
87
  export function resizeProblems(box: LayoutBox): string[] {
77
88
  const r = box.resize;
@@ -85,6 +96,7 @@ export function resizeProblems(box: LayoutBox): string[] {
85
96
  if (v !== undefined && !(typeof v === "number" && v > 0 && Number.isFinite(v))) problems.push(`${at}: the resize bound ${k} ${String(v)} is not positive and finite`);
86
97
  }
87
98
  if (r.aspect !== undefined && r.aspect !== "keep" && r.aspect !== "free") problems.push(`${at}: the resize aspect ${String(r.aspect)} is not keep or free`);
99
+ if (r.reshape !== undefined && typeof r.reshape !== "boolean") problems.push(`${at}: the resize reshape ${String(r.reshape)} is not true or false`);
88
100
  const b = sizeBoundsOf(box);
89
101
  if (!(b.minW <= box.w && box.w <= b.maxW)) problems.push(`${at}: the width ${box.w} is not in the resize bounds ${b.minW} to ${b.maxW}`);
90
102
  if (!(b.minH <= box.h && box.h <= b.maxH)) problems.push(`${at}: the height ${box.h} is not in the resize bounds ${b.minH} to ${b.maxH}`);
package/src/rules.ts CHANGED
@@ -1,7 +1,21 @@
1
- import { boundsOf, grow, marginSides, overlapOf, pointInRings, type Margin, type Point, type Rect, type Region } from "./geometry.ts";
1
+ import {
2
+ boundsOf,
3
+ convexCorners,
4
+ convexOverlap,
5
+ cornersInConvex,
6
+ grow,
7
+ marginSides,
8
+ overlapOf,
9
+ pointInRings,
10
+ type Margin,
11
+ type Point,
12
+ type Rect,
13
+ type Region,
14
+ type Ring,
15
+ } from "./geometry.ts";
2
16
  import type { LayoutBox, LayoutContainer, LayoutInput, Obstacle, PairGap, Port } from "./input.ts";
3
17
  import { applyPack, type PackOutput } from "./output.ts";
4
- import { resizeProblems, sizeFits } from "./resize.ts";
18
+ import { resizeProblems, shapeFits, sizeFits } from "./resize.ts";
5
19
  import { SHAPE_KIND_IDS, shapeKindProblem, type ShapeSupport } from "./shapes.ts";
6
20
  import { DEFAULT_TOLERANCE, EPS, RECORD_EPS } from "./tolerance.ts";
7
21
  import { turnBox } from "./turn.ts";
@@ -19,8 +33,10 @@ export function placedRect(box: LayoutBox): Rect | undefined {
19
33
  *
20
34
  * - Version 1 counts each shape by its bounding box. On a circle, that count is an upper bound. A count over 0 proves nothing.
21
35
  * - Version 2 counts two circles, and a circle in a circle container, by the distance of the centers. The other pairs stay on the bounding box.
36
+ * - Version 3 counts a pair with a convex polygon by the separating axis theorem. The other box is a rectangle or a convex polygon, and neither box has a margin.
37
+ * A convex polygon without a margin in a convex container counts by its corners. The counts of the other inputs do not change.
22
38
  */
23
- export const HARD_RULE_VERSION = 2;
39
+ export const HARD_RULE_VERSION = 3;
24
40
 
25
41
  /** A circle at its place on the board: its center and its radius, without a margin. */
26
42
  export interface PlacedCircle {
@@ -35,6 +51,20 @@ export function placedCircle(box: LayoutBox): PlacedCircle | undefined {
35
51
  return { cx: box.x + box.shape.cx, cy: box.y + box.shape.cy, r: box.shape.r };
36
52
  }
37
53
 
54
+ /**
55
+ * This function gives the corners of a placed box on the board, when its outline is convex and it has no margin. Each other box gives `undefined`.
56
+ * A box without a shape is its rectangle. A box with a shape gives `convexCorners` of the shape at the position of the box.
57
+ */
58
+ export function placedConvex(box: LayoutBox): Ring | undefined {
59
+ if (box.x === undefined || box.y === undefined) return undefined;
60
+ const m = marginSides(box.margin);
61
+ if (m.top !== 0 || m.right !== 0 || m.bottom !== 0 || m.left !== 0) return undefined;
62
+ const corners = convexCorners(box.shape ?? { kind: "rect", x: 0, y: 0, w: box.w, h: box.h });
63
+ if (corners === undefined) return undefined;
64
+ const { x, y } = box;
65
+ return corners.map(([cx, cy]) => [cx + x, cy + y] as const);
66
+ }
67
+
38
68
  /** This function gives the largest side of a margin. A circle has one distance to the things near it, so its margin is this side. */
39
69
  function marginReach(margin: Margin | undefined): number {
40
70
  const m = marginSides(margin);
@@ -54,6 +84,7 @@ function nearerThan(a: PlacedCircle, b: PlacedCircle, need: number): boolean {
54
84
  *
55
85
  * - Two circles break the rule when their centers are nearer than the two radii and the two margins, less `tolerance`. The margin of a circle is the largest side of its margin.
56
86
  * - Another pair breaks the rule when the bounding boxes with their margins overlap by more than `tolerance` on each axis. With a shape that is not a rectangle, this test is an upper bound.
87
+ * - A pair with a convex polygon and no margin also needs an overlap over `tolerance` on the normal of each side (`convexOverlap`). Thus that pair is exact.
57
88
  * - With `gap`, the gap replaces the two margins. Two circles are then apart by the two radii and the gap. For another pair, one box grows by the gap.
58
89
  * - A box without a position does not overlap.
59
90
  */
@@ -65,7 +96,19 @@ export function shapesOverlap(a: LayoutBox, b: LayoutBox, tolerance: number = DE
65
96
  const rb = placedRect(b);
66
97
  if (ra === undefined || rb === undefined) return false;
67
98
  const o = gap === undefined ? overlapOf(grow(ra, a.margin), grow(rb, b.margin)) : overlapOf(grow(ra, gap), rb);
68
- return o.x > tolerance && o.y > tolerance;
99
+ if (!(o.x > tolerance && o.y > tolerance)) return false;
100
+ return gap !== undefined || !convexApart(a, b, tolerance);
101
+ }
102
+
103
+ /**
104
+ * This function tells if the separating axis theorem puts two placed boxes apart, for `no-overlap` of version 3.
105
+ * Only a pair with a box of a `polygon` shape is tested, and both boxes need `placedConvex`. Each other pair gives `false`, so its count does not change.
106
+ */
107
+ function convexApart(a: LayoutBox, b: LayoutBox, tolerance: number): boolean {
108
+ if (a.shape?.kind !== "polygon" && b.shape?.kind !== "polygon") return false;
109
+ const ca = placedConvex(a);
110
+ const cb = placedConvex(b);
111
+ return ca !== undefined && cb !== undefined && convexOverlap(ca, cb) <= tolerance;
69
112
  }
70
113
 
71
114
  /** This function gives the gap of each pair of `pairGaps` by `pairKey`. The first entry of a pair wins. A pair of one box has no gap. */
@@ -81,6 +124,7 @@ function gapsOf(pairGaps: readonly PairGap[] | undefined): Map<string, number> {
81
124
  /**
82
125
  * This function counts the pairs of placed boxes that break `no-overlap`. `shapesOverlap` is the rule for one pair.
83
126
  * Two circles count by the distance of their centers. Each other pair counts by the bounding boxes, so a circle beside another shape is an upper bound (roadmap item L107).
127
+ * A pair with a convex polygon and no margin also needs an overlap on the normal of each side, so it is exact (version 3).
84
128
  *
85
129
  * A pair of `pairGaps`, in either order, uses its `gap` in place of the two margins. One box grows by the gap, and the other box does not grow.
86
130
  * Thus the pair breaks the rule only when the boxes are nearer than the gap on each axis. The other pairs do not change.
@@ -146,12 +190,15 @@ export function circleOverlaps(boxes: readonly LayoutBox[], tolerance: number =
146
190
  return count;
147
191
  }
148
192
 
149
- /** This function counts the overlaps by the bounding boxes with their margins. It skips the pairs of `skip` and the pairs of two circles. */
193
+ /**
194
+ * This function counts the overlaps by the bounding boxes with their margins. It skips the pairs of `skip` and the pairs of two circles.
195
+ * A pair that `convexApart` puts apart does not count.
196
+ */
150
197
  function marginOverlaps(boxes: readonly LayoutBox[], tolerance: number, skip: ReadonlyMap<string, number> | undefined): number {
151
- const rects: { readonly id: string; readonly r: Rect; readonly circle: boolean }[] = [];
198
+ const rects: { readonly box: LayoutBox; readonly id: string; readonly r: Rect; readonly circle: boolean }[] = [];
152
199
  for (const box of boxes) {
153
200
  const r = placedRect(box);
154
- if (r !== undefined) rects.push({ id: box.id, r: grow(r, box.margin), circle: box.shape?.kind === "circle" });
201
+ if (r !== undefined) rects.push({ box, id: box.id, r: grow(r, box.margin), circle: box.shape?.kind === "circle" });
155
202
  }
156
203
  rects.sort((a, b) => a.r.x - b.r.x);
157
204
  let count = 0;
@@ -163,7 +210,7 @@ function marginOverlaps(boxes: readonly LayoutBox[], tolerance: number, skip: Re
163
210
  if (rects[i]!.circle && rects[j]!.circle) continue;
164
211
  if (skip !== undefined && skip.has(pairKey(rects[i]!.id, rects[j]!.id))) continue;
165
212
  const o = overlapOf(a, b);
166
- if (o.x > tolerance && o.y > tolerance) count++;
213
+ if (o.x > tolerance && o.y > tolerance && !convexApart(rects[i]!.box, rects[j]!.box, tolerance)) count++;
167
214
  }
168
215
  }
169
216
  return count;
@@ -326,8 +373,10 @@ export function countLinksThroughShapes(boxes: readonly LayoutBox[], links: read
326
373
  *
327
374
  * With `exactContainer`, the default, a box of a shaped container with the size `fixed` also counts when it is not inside the shape, by `rectInRegion`.
328
375
  * 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.
329
- * A circle in a circle container does not use `rectInRegion`. It counts by distance, as in `circlesOutside`, also when the size is free.
330
376
  * An input without a container gives 0.
377
+ *
378
+ * A circle in a circle container does not use `rectInRegion`. It counts by distance, as in `circlesOutside`, also when the size is free.
379
+ * A box of a `polygon` shape with `placedConvex` in a convex shape does not use `rectInRegion`. It counts by its corners (`cornersInConvex`), so the count is exact (version 3).
331
380
  */
332
381
  export function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOLERANCE.overlap, options: ContainerTest = {}): number {
333
382
  const c = input.container;
@@ -350,11 +399,19 @@ export function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOL
350
399
  if ((fixW && outX) || (fixH && outY)) count++;
351
400
  else if (ring !== undefined && disc !== undefined) {
352
401
  if (circleOutside(disc, marginReach(box.margin) + inset, ring, tolerance)) count++;
353
- } else if (shape !== undefined && !rectInRegion(shape, shrink(grow(r, inset), tolerance))) count++;
402
+ } else if (shape !== undefined && !inShape(box, shape, r, inset, tolerance)) count++;
354
403
  }
355
404
  return count;
356
405
  }
357
406
 
407
+ /** This function tells if a placed box is inside a container shape for `countOutside`. A convex polygon box in a convex shape counts by its corners. */
408
+ function inShape(box: LayoutBox, shape: Region, r: Rect, inset: number, tolerance: number): boolean {
409
+ const inner = box.shape?.kind === "polygon" ? placedConvex(box) : undefined;
410
+ const outer = inner === undefined ? undefined : convexCorners(shape);
411
+ if (inner !== undefined && outer !== undefined) return cornersInConvex(inner, outer, inset, tolerance);
412
+ return rectInRegion(shape, shrink(grow(r, inset), tolerance));
413
+ }
414
+
358
415
  /** 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. */
359
416
  export function countPortsOffBorder(boxes: readonly LayoutBox[], eps: number = RECORD_EPS): number {
360
417
  let count = 0;
@@ -377,8 +434,8 @@ export interface PackHard {
377
434
  readonly "locked-kept": number;
378
435
  readonly complete: number;
379
436
  /**
380
- * The count of the placements whose size is not in the bounds of their box (`countResizeBreaks`).
381
- * `packHard` gives it only when a box of the input has `resize` or a placement has `w` or `h`. Thus the counts of the other inputs do not change.
437
+ * The count of the placements whose size or shape does not fit their box (`countResizeBreaks`).
438
+ * `packHard` gives it only when a box of the input has `resize` or a placement has `w`, `h` or `shape`. Thus the counts of the other inputs do not change.
382
439
  */
383
440
  readonly "size-kept"?: number;
384
441
  }
@@ -388,6 +445,9 @@ export interface PackHard {
388
445
  * `no-overlap` and `in-container` are exact for a `rect` and a `circle`. `limit` tells the inputs where the count of a circle is only safe (roadmap item L107).
389
446
  * For the other kinds, these rules test the bounding box. The count is safe: a shape is inside its bounding box, so the count is an upper bound. A count of 0 tells that the rule has no break.
390
447
  * `locked-kept` and `complete` read only the positions and the ids, so they support each kind.
448
+ *
449
+ * A convex `polygon` without a margin is exact beside a rectangle or a convex polygon, and in a convex container (version 3).
450
+ * The kind `polygon` stays `safe`, because a concave polygon is not exact.
391
451
  */
392
452
  export const PACK_HARD_RULES: readonly ShapeSupport<keyof PackHard>[] = /* @__PURE__ */ Object.freeze([
393
453
  {
@@ -561,19 +621,23 @@ export function countObstacleHits(
561
621
  }
562
622
 
563
623
  /**
564
- * This function gives the count of the placements whose size is not in the bounds of their box (`sizeFits`).
624
+ * This function counts the placements with a size outside the bounds of their box (`sizeFits`), or with a shape that does not fit (`shapeFits`).
565
625
  * The bounds are in the axes of the placed box: a turned box has the turned bounds. A placement without `w` or `h` keeps that size of the box.
626
+ * A placement with a shape on a box without `resize.reshape` counts. A placement counts one time, also when its size and its shape both break.
566
627
  * A placement of an id that is not in the input does not count.
567
628
  */
568
629
  export function countResizeBreaks(input: LayoutInput, output: PackOutput): number {
569
630
  const was = new Map(input.boxes.map((b) => [b.id, b]));
570
631
  let count = 0;
571
632
  for (const p of output.placements) {
572
- if (p.w === undefined && p.h === undefined) continue;
633
+ if (p.w === undefined && p.h === undefined && p.shape === undefined) continue;
573
634
  const box = was.get(p.id);
574
635
  if (box === undefined) continue;
575
636
  const placed = p.turn === 90 ? turnBox(box) : box;
576
- if (!sizeFits(placed, p.w ?? placed.w, p.h ?? placed.h)) count++;
637
+ const w = p.w ?? placed.w;
638
+ const h = p.h ?? placed.h;
639
+ const sized = (p.w === undefined && p.h === undefined) || sizeFits(placed, w, h);
640
+ if (!sized || (p.shape !== undefined && !shapeFits(placed, p.shape, w, h))) count++;
577
641
  }
578
642
  return count;
579
643
  }
@@ -586,7 +650,7 @@ export function countResizeBreaks(input: LayoutInput, output: PackOutput): numbe
586
650
  * A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`.
587
651
  * A locked box without a position in the input is a bad input, not a break. `checkInput` finds it.
588
652
  * Another box without a placement that is not in `overflow` breaks `complete`.
589
- * `size-kept` is in the result only when a box has `resize` or a placement has `w` or `h` (`countResizeBreaks`).
653
+ * `size-kept` is in the result only when a box has `resize` or a placement has `w`, `h` or `shape` (`countResizeBreaks`).
590
654
  *
591
655
  * `options` goes to `countOutside` for `in-container`.
592
656
  */
@@ -620,9 +684,9 @@ export function packHard(input: LayoutInput, output: PackOutput, tolerance: numb
620
684
  };
621
685
  }
622
686
 
623
- /** This function tells if a box of the input has `resize` or a placement of the output has `w` or `h`. */
687
+ /** This function tells if a box of the input has `resize` or a placement of the output has `w`, `h` or `shape`. */
624
688
  function resizes(input: LayoutInput, output: PackOutput): boolean {
625
- return input.boxes.some((b) => b.resize !== undefined) || output.placements.some((p) => p.w !== undefined || p.h !== undefined);
689
+ return input.boxes.some((b) => b.resize !== undefined) || output.placements.some((p) => p.w !== undefined || p.h !== undefined || p.shape !== undefined);
626
690
  }
627
691
 
628
692
  /**
package/src/text.ts CHANGED
@@ -717,9 +717,9 @@ export type TextMeasureId = "text.lines" | "text.raggedness" | "text.overflow" |
717
717
  /** The specs of the text measures. */
718
718
  export const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = /* @__PURE__ */ Object.freeze([
719
719
  { id: "text.lines", unit: "count", direction: "lower", min: 1, max: Infinity, minEffect: 0, family: "text" },
720
- { id: "text.raggedness", unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.005, family: "text" },
721
- { id: "text.overflow", unit: "share of the wrap width", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: "text", role: "guard" },
722
- { id: "text.cacheHit", unit: "0 to 1", direction: "higher", min: 0, max: 1, family: "text", role: "diagnostic" },
720
+ { id: "text.raggedness", unit: "share", direction: "lower", min: 0, max: 1, minEffect: 0.005, family: "text" },
721
+ { id: "text.overflow", unit: "wrap widths", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: "text", role: "guard" },
722
+ { id: "text.cacheHit", unit: "share", direction: "higher", min: 0, max: 1, family: "text", role: "diagnostic" },
723
723
  { id: "text.ms", unit: "milliseconds", direction: "lower", min: 0, max: Infinity, family: "text", role: "time" },
724
724
  ] as const);
725
725
 
@@ -1 +0,0 @@
1
- {"version":3,"file":"measures-CJZw-Y3H.d.ts","names":[],"sources":["../src/geometry.ts","../src/corpus.ts","../src/input.ts","../src/shapes.ts","../src/measures.ts"],"mappings":";KAGY;;cAGC,gBAAgB;UAEZ;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;;;;;;UAOM;WACN;WACA;WACA;WACA;;;iBAIK,OAAO,MAAM,YAAY;;iBAKzB,YAAY,MAAM,OAAO;;;;;iBAWzB,SAAS,MAAM,OAAO;;;;;;iBAWtB,UAAU,MAAM,MAAM,iBAAiB;;UAMtC;WACN;WACA;WACA;WACA;;;;;;KAOC;WACG;WAAuB;WAAoB;WAAoB;WAAoB;;WAEnF;WACA,QAAQ;WACR,iBAAiB;;WAEjB;WAAyB;WAAqB;WAAqB;;WACnE;WAA0B;WAAqB;WAAqB;WAAqB;;;KAG5F,kBAAkB;;iBAGd,YAAY,QAAQ,qBAAqB;;iBAOzC,KAAK,MAAM,MAAM,QAAQ,qBAAqB;;iBAM9C,SAAS,QAAQ,SAAS;;;;;iBA4B1B,WAAW,QAAQ;;iBAyBnB,UAAU,QAAQ,QAAQ,YAAY,aAAa;;;;;iBAoBnD,UAAU,GAAG,MAAM,GAAG;WAAkB;WAAoB;;;;;;;iBA2B5D,cAAc,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG;;;;;;iBAU/C,cAAc,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG,QAAQ;;iBASvD,qBAAqB,GAAG,OAAO,GAAG,OAAO,GAAG;;KAShD;;iBAGI,YAAY,WAAW,WAAW,MAAM;;;;;iBAQxC,aAAa,WAAW,WAAW,gBAAgB;;;;;;iBAiBnD,aAAa,MAAM,OAAO;;;;;;iBA8B1B,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