@vitavision/overlays 0.1.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,241 @@
1
+ /**
2
+ * A calibration-target detection over the image: one component for a chessboard, ChArUco,
3
+ * marker board, PuzzleBoard, ring grid or a loose set of corners.
4
+ *
5
+ * It replaces the per-board overlays of vitavision (`ChessboardOverlay`, `CharucoOverlay`,
6
+ * `MarkerboardOverlay`, `PuzzleboardOverlay`) and the glyph components behind them. Each part of
7
+ * a `TargetDetection` goes to the stage2d layer that fits it, so a detection of thousands of
8
+ * items is a few dozen DOM nodes (ADR-0004), and the pointer is resolved by the stage's hit-test
9
+ * registry, not the DOM:
10
+ *
11
+ * | Part | Layer | Glyph (visual-language §5) |
12
+ * |---|---|---|
13
+ * | `corners` | `GridLayer` | plus; edge directions when `angle` is set; lattice edges and `i,j` labels |
14
+ * | `markers` | `AreaSet` | quad outline and 12 % fill, corner 0 ticked, id inside |
15
+ * | `circles` | `PointSet` | ring; a centre dot marks black |
16
+ * | `rings` | `PointSet` + `EllipseSet` | fitted outer and inner ellipse, plus at the centre |
17
+ * | `edgeBits` | `EllipseSet` | dot on the edge: solid for 1, dashed for 0, opacity from confidence |
18
+ */
19
+
20
+ import {
21
+ GridLayer,
22
+ AreaSet,
23
+ PointSet,
24
+ type StagePointerEvent,
25
+ } from "@vitavision/stage2d";
26
+ import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
27
+
28
+ import { EllipseSet } from "./EllipseSet";
29
+ import { TARGET_MARKERS } from "./glyphs";
30
+ import { circlePoints, cornerNodes, edgeBitEllipses, markerAreas, ringCentres, ringEllipses } from "./layerItems";
31
+ import type { TargetDetection, TargetHit, TargetId, TargetPart } from "./model";
32
+
33
+ /** Props of `TargetOverlay`. */
34
+ export interface TargetOverlayProps {
35
+ /** The detection to draw. Pass a stable object: a new one rebuilds every layer's index. */
36
+ detection: TargetDetection;
37
+ /** Draw the lattice edges between neighbouring corners, one dashed axis and one solid. On by default. */
38
+ showEdges?: boolean | undefined;
39
+ /** Show labels (lattice indices, marker ids, ring ids) where the zoom leaves room for them. On by default. */
40
+ showLabels?: boolean | undefined;
41
+ /**
42
+ * The hovered id, when the app controls hover (a list beside the stage hovers items too). It
43
+ * applies to every part that has the id; keep ids unique within a detection.
44
+ */
45
+ hoveredId?: TargetId | null | undefined;
46
+ /** The selected ids, drawn at 2.5 px in the selection colour; points get a ring. */
47
+ selectedIds?: Iterable<TargetId> | undefined;
48
+ /**
49
+ * Called when the item under the pointer changes, once per change; `null` when it leaves every
50
+ * item. The `id` is the one given in the detection, so the app maps it back to its feature.
51
+ */
52
+ onHoverChange?: ((hit: TargetHit | null) => void) | undefined;
53
+ /**
54
+ * A press landed on an item. Setting it makes the layers claim presses on their items, so the
55
+ * stage does not pan from them. A mounted `StageSurface` hears a press first; there, ask
56
+ * `useStageHitTest` what is under it instead.
57
+ */
58
+ onItemPress?: ((hit: TargetHit, event: StagePointerEvent) => void) | undefined;
59
+ /**
60
+ * Dim the whole overlay (`true`), or the listed ids, or those a predicate accepts, to 35 %
61
+ * opacity. They still take hover and presses. Pass a stable value: a new one re-batches.
62
+ */
63
+ dimmed?: boolean | Iterable<TargetId> | ((id: TargetId) => boolean) | undefined;
64
+ /** Prefix of the hit-test layer ids (`<prefix>-corners`, `-markers`, `-circles`, `-rings`). Defaults to generated ids. */
65
+ layerIdPrefix?: string | undefined;
66
+ }
67
+
68
+ /** The ids of each part, to route a hovered or selected id to the layers that have it. */
69
+ function idsByPart(detection: TargetDetection): Record<TargetPart, ReadonlySet<TargetId>> {
70
+ const ids = (items: readonly { id: TargetId }[] | undefined) => new Set((items ?? []).map((item) => item.id));
71
+ return {
72
+ corner: ids(detection.corners),
73
+ marker: ids(detection.markers),
74
+ circle: ids(detection.circles),
75
+ ring: ids(detection.rings),
76
+ };
77
+ }
78
+
79
+ /** The `dimmed` prop as the predicate the layers take, or `undefined` for none. */
80
+ function dimPredicate(dimmed: TargetOverlayProps["dimmed"]): ((id: TargetId) => boolean) | undefined {
81
+ if (dimmed === undefined || dimmed === false) return undefined;
82
+ if (dimmed === true) return () => true;
83
+ if (typeof dimmed === "function") return dimmed;
84
+ const set = new Set(dimmed);
85
+ return (id) => set.has(id);
86
+ }
87
+
88
+ /**
89
+ * A detected calibration target inside an `ImageStage`.
90
+ *
91
+ * - **Batched**: one path per appearance in each layer, picking through spatial indices. Labels
92
+ * appear only where items are 24 screen px apart, at most 200 at a time.
93
+ * - **States**: hover 2 px, selected 2.5 px in the selection colour with a ring, dimmed at 35 %.
94
+ * - **Colour**: roles only (`feature`, `model`, `structure`, `selection`). Scores are never drawn
95
+ * as red, amber or green; polarity and bits are carried by shape (hollow or dotted, solid or
96
+ * dashed), not by hue.
97
+ * - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move
98
+ * between layers (a corner, then the marker under it) without a flicker: the change is reported
99
+ * once.
100
+ *
101
+ * The layers it renders carry their own accessible names ("Corners: 54 points, 0 selected").
102
+ */
103
+ export function TargetOverlay({
104
+ detection,
105
+ showEdges = true,
106
+ showLabels = true,
107
+ hoveredId,
108
+ selectedIds,
109
+ onHoverChange,
110
+ onItemPress,
111
+ dimmed,
112
+ layerIdPrefix,
113
+ }: TargetOverlayProps) {
114
+ const nodes = useMemo(() => cornerNodes(detection), [detection]);
115
+ const areas = useMemo(() => markerAreas(detection), [detection]);
116
+ const circles = useMemo(() => circlePoints(detection), [detection]);
117
+ const rings = detection.rings;
118
+ const ringPoints = useMemo(() => ringCentres(rings ?? []), [rings]);
119
+ const ringShapes = useMemo(() => ringEllipses(rings ?? []), [rings]);
120
+ const bits = useMemo(() => edgeBitEllipses(detection.edgeBits ?? []), [detection.edgeBits]);
121
+ const ids = useMemo(() => idsByPart(detection), [detection]);
122
+
123
+ // Selection and hover are by id; each layer is given the ids it owns, so its count is right.
124
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
125
+ const selected = useMemo(() => {
126
+ const pick = (part: TargetPart) => new Set([...selectedSet].filter((id) => ids[part].has(id)));
127
+ return { corner: pick("corner"), marker: pick("marker"), circle: pick("circle"), ring: pick("ring") };
128
+ }, [selectedSet, ids]);
129
+ const isDimmed = useMemo(() => dimPredicate(dimmed), [dimmed]);
130
+
131
+ // Hover. The layers report separately, so moving from a corner to the marker under it is
132
+ // `corner → null` then `marker → id` in one event. The net result is read when the event is
133
+ // done, and reported once.
134
+ const [ownHover, setOwnHover] = useState<TargetHit | null>(null);
135
+ const hoverRef = useRef<TargetHit | null>(null);
136
+ const reportedRef = useRef<TargetHit | null>(null);
137
+ const scheduledRef = useRef(false);
138
+ const onHoverChangeRef = useRef(onHoverChange);
139
+ useLayoutEffect(() => {
140
+ onHoverChangeRef.current = onHoverChange;
141
+ });
142
+ const hoverFrom = useCallback((part: TargetPart) => (id: TargetId | null) => {
143
+ if (id !== null) hoverRef.current = { id, part };
144
+ else if (hoverRef.current?.part === part) hoverRef.current = null;
145
+ setOwnHover(hoverRef.current);
146
+ if (scheduledRef.current) return;
147
+ scheduledRef.current = true;
148
+ queueMicrotask(() => {
149
+ scheduledRef.current = false;
150
+ const now = hoverRef.current;
151
+ const before = reportedRef.current;
152
+ if (now?.id === before?.id && now?.part === before?.part) return;
153
+ reportedRef.current = now;
154
+ onHoverChangeRef.current?.(now);
155
+ });
156
+ }, []);
157
+ const hoverOf = (part: TargetPart): TargetId | null => {
158
+ if (hoveredId !== undefined) return hoveredId !== null && ids[part].has(hoveredId) ? hoveredId : null;
159
+ return ownHover?.part === part ? ownHover.id : null;
160
+ };
161
+
162
+ const pressFrom = (part: TargetPart) =>
163
+ onItemPress ? (id: TargetId, event: StagePointerEvent) => onItemPress({ id, part }, event) : undefined;
164
+ const layerId = (name: string) => (layerIdPrefix === undefined ? undefined : `${layerIdPrefix}-${name}`);
165
+
166
+ const hasCorners = nodes.length > 0;
167
+ const hasMarkers = areas.length > 0;
168
+ const hasCircles = circles.length > 0;
169
+ const hasRings = ringPoints.length > 0;
170
+ const edgeStyle = { visible: showEdges };
171
+
172
+ return (
173
+ <>
174
+ {hasMarkers && (
175
+ <AreaSet
176
+ items={areas}
177
+ firstVertexTick
178
+ labels={showLabels}
179
+ hoveredId={hoverOf("marker")}
180
+ selectedIds={selected.marker}
181
+ dimmed={isDimmed}
182
+ onHoverChange={hoverFrom("marker")}
183
+ onItemPress={pressFrom("marker")}
184
+ layerId={layerId("markers")}
185
+ label="Markers"
186
+ />
187
+ )}
188
+ {bits.length > 0 && <EllipseSet items={bits} minRadius={3} dimmed={isDimmed} />}
189
+ {hasRings && (
190
+ <>
191
+ <EllipseSet items={ringShapes.outer} hoveredId={hoverOf("ring")} selectedIds={selected.ring} dimmed={isDimmed} />
192
+ {ringShapes.inner.length > 0 && (
193
+ <EllipseSet items={ringShapes.inner} role="model" hoveredId={hoverOf("ring")} selectedIds={selected.ring} dimmed={isDimmed} />
194
+ )}
195
+ <PointSet
196
+ items={ringPoints}
197
+ kind="plus"
198
+ markers={TARGET_MARKERS}
199
+ labels={showLabels}
200
+ hoveredId={hoverOf("ring")}
201
+ selectedIds={selected.ring}
202
+ dimmed={isDimmed}
203
+ onHoverChange={hoverFrom("ring")}
204
+ onItemPress={pressFrom("ring")}
205
+ layerId={layerId("rings")}
206
+ label="Rings"
207
+ />
208
+ </>
209
+ )}
210
+ {hasCorners && (
211
+ <GridLayer
212
+ nodes={nodes}
213
+ markers={TARGET_MARKERS}
214
+ edges={{ i: edgeStyle, j: { ...edgeStyle, dashed: true } }}
215
+ labels={showLabels}
216
+ hoveredId={hoverOf("corner")}
217
+ selectedIds={selected.corner}
218
+ dimmed={isDimmed}
219
+ onHoverChange={hoverFrom("corner")}
220
+ onItemPress={pressFrom("corner")}
221
+ layerId={layerId("corners")}
222
+ label="Corners"
223
+ />
224
+ )}
225
+ {hasCircles && (
226
+ <PointSet
227
+ items={circles}
228
+ markers={TARGET_MARKERS}
229
+ labels={showLabels}
230
+ hoveredId={hoverOf("circle")}
231
+ selectedIds={selected.circle}
232
+ dimmed={isDimmed}
233
+ onHoverChange={hoverFrom("circle")}
234
+ onItemPress={pressFrom("circle")}
235
+ layerId={layerId("circles")}
236
+ label="Circles"
237
+ />
238
+ )}
239
+ </>
240
+ );
241
+ }
package/src/glyphs.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The glyphs of a calibration-target overlay, as path generators.
3
+ *
4
+ * A glyph is a `MarkerShape` for `@vitavision/stage2d`'s `PointSet`: a pure function from a
5
+ * position to SVG path data, so a layer appends thousands of them into one `<path>` (ADR-0004).
6
+ * They are registered under the names in `TARGET_MARKERS`, which `TargetOverlay` passes as
7
+ * `markers`. Sizes are screen pixels, from `unit` (image pixels per screen pixel).
8
+ *
9
+ * `MarkerShape.path` receives one number per item, `angle`. A corner with two edge directions
10
+ * needs two, so `packAxes` folds both into that one number (see below); that is the only reason
11
+ * the packing exists.
12
+ *
13
+ * Pure: no React, no DOM.
14
+ */
15
+
16
+ import { circlePath, type MarkerShape } from "@vitavision/stage2d";
17
+
18
+ /** Round to 1/1000 of an image pixel. */
19
+ function round(value: number): number {
20
+ return Math.round(value * 1000) / 1000;
21
+ }
22
+
23
+ /** Quantisation steps per half turn when two axes share one number: 2²⁶, so about 4.7e-8 rad. */
24
+ const STEPS = 2 ** 26;
25
+ /** Packed values start here; a plain angle (normalised to [0, π)) is always below it. */
26
+ const PACKED_FLOOR = 8;
27
+
28
+ /** An angle as a direction of a line: modulo π, in [0, π). */
29
+ function lineAngle(angle: number): number {
30
+ const wrapped = angle % Math.PI;
31
+ return wrapped < 0 ? wrapped + Math.PI : wrapped;
32
+ }
33
+
34
+ /**
35
+ * Fold one or two edge directions into the single `angle` number a `MarkerShape` receives.
36
+ *
37
+ * Directions are lines (`θ` and `θ + π` are the same line), so each is taken modulo π. With one
38
+ * direction the result is that angle in [0, π). With two they are quantised to 2⁻²⁶ of a half
39
+ * turn (4.7e-8 rad, under a millionth of a screen pixel on a 10 px glyph) and packed into one
40
+ * integer-valued double above 8, which stays exact because it is below 2⁵³. `unpackAxes` is the
41
+ * inverse.
42
+ *
43
+ * @param angle - The first direction, radians.
44
+ * @param angle2 - The second direction, radians. Optional.
45
+ * @returns A number to put in `PointSetItem.angle` for the `directed` marker.
46
+ */
47
+ export function packAxes(angle: number, angle2?: number): number {
48
+ if (angle2 === undefined) return lineAngle(angle);
49
+ const q = (a: number) => Math.round((lineAngle(a) / Math.PI) * STEPS) % STEPS;
50
+ return PACKED_FLOOR + q(angle) * STEPS + q(angle2);
51
+ }
52
+
53
+ /**
54
+ * The directions folded into `angle` by `packAxes`.
55
+ *
56
+ * @param packed - A value from `packAxes`, or a plain angle in radians.
57
+ * @returns One direction for a plain angle, two for a packed value; each in [0, π).
58
+ */
59
+ export function unpackAxes(packed: number): number[] {
60
+ if (!Number.isFinite(packed)) return [];
61
+ if (packed < PACKED_FLOOR) return [lineAngle(packed)];
62
+ const rest = packed - PACKED_FLOOR;
63
+ const first = Math.floor(rest / STEPS);
64
+ return [(first / STEPS) * Math.PI, ((rest - first * STEPS) / STEPS) * Math.PI];
65
+ }
66
+
67
+ /** Half-length of a directed corner's axes, and the gap left at its centre, in screen pixels. */
68
+ const AXIS_REACH = 8;
69
+ const AXIS_GAP = 2;
70
+
71
+ /**
72
+ * A corner with its edge directions: one or two lines through the point, 8 px each way with a
73
+ * 2 px gap at the centre, so the corner itself stays visible. Give it `angle: packAxes(a, b)`.
74
+ */
75
+ const directed: MarkerShape = {
76
+ paint: "line",
77
+ size: AXIS_REACH,
78
+ path: (x, y, unit, packed) => {
79
+ let d = "";
80
+ for (const angle of unpackAxes(packed)) {
81
+ const c = Math.cos(angle);
82
+ const s = Math.sin(angle);
83
+ const near = AXIS_GAP * unit;
84
+ const far = AXIS_REACH * unit;
85
+ d +=
86
+ `M${round(x - far * c)} ${round(y - far * s)}L${round(x - near * c)} ${round(y - near * s)}` +
87
+ `M${round(x + near * c)} ${round(y + near * s)}L${round(x + far * c)} ${round(y + far * s)}`;
88
+ }
89
+ return d;
90
+ },
91
+ };
92
+
93
+ /** Radius of a matched circle's glyph, screen pixels. */
94
+ const CIRCLE_RADIUS = 5.5;
95
+ /** Radius of the centre mark of a black circle, screen pixels; stroked, it reads as a filled dot. */
96
+ const CENTRE_RADIUS = 0.8;
97
+
98
+ /** A white circle of a marker board: a hollow ring of radius 5.5 px. */
99
+ const circleWhite: MarkerShape = {
100
+ paint: "line",
101
+ size: CIRCLE_RADIUS,
102
+ path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit),
103
+ };
104
+
105
+ /** A black circle: the same ring with a dot at its centre, so polarity is a shape and not a colour. */
106
+ const circleBlack: MarkerShape = {
107
+ paint: "line",
108
+ size: CIRCLE_RADIUS,
109
+ path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit) + circlePath(x, y, CENTRE_RADIUS * unit),
110
+ };
111
+
112
+ /** The marker names `TargetOverlay` uses, to pass to `PointSet`'s `markers`. */
113
+ export const TARGET_MARKERS = {
114
+ /** Edge directions of a corner; see `packAxes`. */
115
+ directed,
116
+ /** A white matched circle. */
117
+ "circle-white": circleWhite,
118
+ /** A black matched circle. */
119
+ "circle-black": circleBlack,
120
+ } as const satisfies Readonly<Record<string, MarkerShape>>;
121
+
122
+ /**
123
+ * An ellipse as two arcs, exactly: no polygon approximation, so it stays round at any zoom.
124
+ *
125
+ * @param cx - Centre x, image pixels.
126
+ * @param cy - Centre y, image pixels.
127
+ * @param rx - Semi-axis along the rotated x axis, image pixels.
128
+ * @param ry - Semi-axis along the rotated y axis, image pixels.
129
+ * @param angle - Rotation of the `rx` axis, radians clockwise on screen.
130
+ * @returns Path data, or `""` for a degenerate ellipse (a non-finite value, or a radius not above zero).
131
+ */
132
+ export function ellipsePath(cx: number, cy: number, rx: number, ry: number, angle = 0): string {
133
+ if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return "";
134
+ const dx = rx * Math.cos(angle);
135
+ const dy = rx * Math.sin(angle);
136
+ const degrees = round((angle * 180) / Math.PI);
137
+ const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;
138
+ return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;
139
+ }
package/src/index.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `@vitavision/overlays` — calibration-target overlays on the `@vitavision/stage2d` stage.
3
+ *
4
+ * One component, `TargetOverlay`, draws a `TargetDetection` (a chessboard, ChArUco, marker
5
+ * board, PuzzleBoard, ring grid or loose corners) through stage2d's batched layers, in the
6
+ * overlay grammar's roles and glyphs. The input model, the lattice builders and the glyph path
7
+ * generators are exported too, for an app that composes the layers itself.
8
+ */
9
+
10
+ export { TargetOverlay, type TargetOverlayProps } from "./TargetOverlay";
11
+
12
+ export { EllipseSet, type EllipseSetItem, type EllipseSetProps } from "./EllipseSet";
13
+
14
+ export {
15
+ TARGET_KINDS,
16
+ isLatticeKind,
17
+ type CirclePolarity,
18
+ type TargetCircle,
19
+ type TargetCorner,
20
+ type TargetDetection,
21
+ type TargetEdgeBit,
22
+ type TargetEllipse,
23
+ type TargetHit,
24
+ type TargetId,
25
+ type TargetKind,
26
+ type TargetMarker,
27
+ type TargetPart,
28
+ type TargetRing,
29
+ } from "./model";
30
+
31
+ export {
32
+ cornerGrid,
33
+ gridEdges,
34
+ gridKey,
35
+ idByGrid,
36
+ markerPolygons,
37
+ type CornerGrid,
38
+ type GridBounds,
39
+ type GridCorner,
40
+ type GridSegment,
41
+ type MarkerPolygon,
42
+ } from "./lattice";
43
+
44
+ export {
45
+ PUZZLEBOARD_PERIOD,
46
+ edgeBitsFromPuzzleboard,
47
+ type PuzzleboardAlignment,
48
+ type PuzzleboardEdge,
49
+ } from "./puzzleboard";
50
+
51
+ export { TARGET_MARKERS, ellipsePath, packAxes, unpackAxes } from "./glyphs";
52
+
53
+ export {
54
+ circlePoints,
55
+ cornerNodes,
56
+ edgeBitEllipses,
57
+ markerAreas,
58
+ ringCentres,
59
+ ringEllipses,
60
+ } from "./layerItems";
package/src/lattice.ts ADDED
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The lattice of a detected board: which corner sits at which `(i, j)`, which corners are
3
+ * neighbours, and the polygons of the markers.
4
+ *
5
+ * Ported from vitavision's `overlayData.ts` (`buildCornerGrid`, `buildGridEdges`,
6
+ * `buildFeatureIdByGrid`, `buildMarkerPolygons`), where ChArUco, chessboard, marker board and
7
+ * PuzzleBoard each carried a copy (PuzzleBoard's `buildPuzzleGrid` was a fourth). One
8
+ * implementation now serves all four, on the normalised `TargetDetection` input.
9
+ *
10
+ * Pure: no React, no DOM.
11
+ */
12
+
13
+ import { latticeEdges } from "@vitavision/stage2d";
14
+
15
+ import type { TargetCorner, TargetId, TargetMarker } from "./model";
16
+
17
+ /** A corner that has a place on the board. */
18
+ export type GridCorner = TargetCorner & { i: number; j: number };
19
+
20
+ /** The extent of a lattice, inclusive. */
21
+ export interface GridBounds {
22
+ /** Smallest `i`. */
23
+ minI: number;
24
+ /** Largest `i`. */
25
+ maxI: number;
26
+ /** Smallest `j`. */
27
+ minJ: number;
28
+ /** Largest `j`. */
29
+ maxJ: number;
30
+ }
31
+
32
+ /** The corners of a board, indexed by lattice position. */
33
+ export interface CornerGrid {
34
+ /** The corners with an integer `(i, j)`, in input order. A repeated `(i, j)` keeps its first corner. */
35
+ nodes: readonly GridCorner[];
36
+ /** Position in `nodes` by `gridKey(i, j)`. */
37
+ byIndex: ReadonlyMap<string, number>;
38
+ /** Positions in `nodes` grouped by `i` (ascending), each group sorted by `j`. */
39
+ rows: readonly (readonly number[])[];
40
+ /** Positions in `nodes` grouped by `j` (ascending), each group sorted by `i`. */
41
+ cols: readonly (readonly number[])[];
42
+ /** The extent, or `null` for an empty grid. */
43
+ bounds: GridBounds | null;
44
+ }
45
+
46
+ /** A segment between two neighbouring corners. */
47
+ export interface GridSegment {
48
+ /** Id of the end with the lower index along the edge's axis. */
49
+ a: TargetId;
50
+ /** Id of the end with the higher index. */
51
+ b: TargetId;
52
+ /** Start x. */
53
+ x1: number;
54
+ /** Start y. */
55
+ y1: number;
56
+ /** End x. */
57
+ x2: number;
58
+ /** End y. */
59
+ y2: number;
60
+ }
61
+
62
+ /** A marker as a closed polygon. */
63
+ export interface MarkerPolygon {
64
+ /** The marker's id. */
65
+ id: TargetId;
66
+ /** Flat `[x0, y0, x1, y1, …]`; the last vertex joins the first. */
67
+ points: number[];
68
+ /** The mean of the vertices. */
69
+ centre: { x: number; y: number };
70
+ /** The marker's own label, if it has one. */
71
+ label?: string | undefined;
72
+ }
73
+
74
+ /**
75
+ * The key of a lattice position, as `idByGrid` and `CornerGrid.byIndex` use.
76
+ *
77
+ * @param i - Index along the first axis.
78
+ * @param j - Index along the second axis.
79
+ * @returns `"i:j"`.
80
+ */
81
+ export function gridKey(i: number, j: number): string {
82
+ return `${i}:${j}`;
83
+ }
84
+
85
+ /** Whether a corner carries an integer lattice index. */
86
+ function isGridCorner(corner: TargetCorner): corner is GridCorner {
87
+ return Number.isInteger(corner.i) && Number.isInteger(corner.j);
88
+ }
89
+
90
+ /**
91
+ * Index a board's corners by lattice position.
92
+ *
93
+ * Corners without an integer `(i, j)` are not part of the grid. When two corners claim one
94
+ * position the first wins, as it does in `latticeEdges`.
95
+ *
96
+ * @param corners - The detected corners, in any order, with gaps allowed.
97
+ * @returns The grid.
98
+ */
99
+ export function cornerGrid(corners: readonly TargetCorner[]): CornerGrid {
100
+ const nodes: GridCorner[] = [];
101
+ const byIndex = new Map<string, number>();
102
+ const rowMap = new Map<number, number[]>();
103
+ const colMap = new Map<number, number[]>();
104
+ let bounds: GridBounds | null = null;
105
+
106
+ for (const corner of corners) {
107
+ if (!isGridCorner(corner)) continue;
108
+ const key = gridKey(corner.i, corner.j);
109
+ if (byIndex.has(key)) continue;
110
+ const position = nodes.length;
111
+ nodes.push(corner);
112
+ byIndex.set(key, position);
113
+ const row = rowMap.get(corner.i);
114
+ if (row) row.push(position);
115
+ else rowMap.set(corner.i, [position]);
116
+ const col = colMap.get(corner.j);
117
+ if (col) col.push(position);
118
+ else colMap.set(corner.j, [position]);
119
+ bounds = bounds
120
+ ? {
121
+ minI: Math.min(bounds.minI, corner.i),
122
+ maxI: Math.max(bounds.maxI, corner.i),
123
+ minJ: Math.min(bounds.minJ, corner.j),
124
+ maxJ: Math.max(bounds.maxJ, corner.j),
125
+ }
126
+ : { minI: corner.i, maxI: corner.i, minJ: corner.j, maxJ: corner.j };
127
+ }
128
+
129
+ const ordered = (groups: Map<number, number[]>, by: "i" | "j") =>
130
+ [...groups.entries()]
131
+ .sort(([a], [b]) => a - b)
132
+ .map(([, group]) => group.sort((p, q) => nodes[p]![by] - nodes[q]![by]));
133
+ return { nodes, byIndex, rows: ordered(rowMap, "j"), cols: ordered(colMap, "i"), bounds };
134
+ }
135
+
136
+ /**
137
+ * The edges between neighbouring corners of a grid: `(i, j)` to `(i, j + 1)` are the row edges,
138
+ * `(i, j)` to `(i + 1, j)` the column edges. A missed corner leaves a gap, never a long edge.
139
+ * It is `latticeEdges` from `@vitavision/stage2d` with positions attached.
140
+ *
141
+ * @param grid - From `cornerGrid`.
142
+ * @returns The two edge lists.
143
+ */
144
+ export function gridEdges(grid: CornerGrid): { rowEdges: GridSegment[]; colEdges: GridSegment[] } {
145
+ const rowEdges: GridSegment[] = [];
146
+ const colEdges: GridSegment[] = [];
147
+ for (const edge of latticeEdges(grid.nodes)) {
148
+ const a = grid.nodes[edge.a]!;
149
+ const b = grid.nodes[edge.b]!;
150
+ (edge.axis === "j" ? rowEdges : colEdges).push({ a: a.id, b: b.id, x1: a.x, y1: a.y, x2: b.x, y2: b.y });
151
+ }
152
+ return { rowEdges, colEdges };
153
+ }
154
+
155
+ /**
156
+ * The id of the corner at each lattice position, to map a board cell back to an app's feature.
157
+ *
158
+ * @param corners - The detected corners.
159
+ * @returns Ids by `gridKey(i, j)`. A corner without an integer index is left out; the first of two sharing a position wins.
160
+ */
161
+ export function idByGrid(corners: readonly TargetCorner[]): Map<string, TargetId> {
162
+ const map = new Map<string, TargetId>();
163
+ for (const corner of corners) {
164
+ if (!isGridCorner(corner)) continue;
165
+ const key = gridKey(corner.i, corner.j);
166
+ if (!map.has(key)) map.set(key, corner.id);
167
+ }
168
+ return map;
169
+ }
170
+
171
+ /**
172
+ * The markers as polygons, with their centres.
173
+ *
174
+ * @param markers - The detected markers.
175
+ * @returns A polygon per marker that has at least three finite vertices; the others are dropped.
176
+ */
177
+ export function markerPolygons(markers: readonly TargetMarker[]): MarkerPolygon[] {
178
+ const out: MarkerPolygon[] = [];
179
+ for (const marker of markers) {
180
+ const n = marker.corners.length;
181
+ if (n < 6 || n % 2 !== 0 || !marker.corners.every(Number.isFinite)) continue;
182
+ let sx = 0;
183
+ let sy = 0;
184
+ for (let k = 0; k < n; k += 2) {
185
+ sx += marker.corners[k]!;
186
+ sy += marker.corners[k + 1]!;
187
+ }
188
+ const polygon: MarkerPolygon = {
189
+ id: marker.id,
190
+ points: [...marker.corners],
191
+ centre: { x: sx / (n / 2), y: sy / (n / 2) },
192
+ };
193
+ if (marker.label !== undefined) polygon.label = marker.label;
194
+ out.push(polygon);
195
+ }
196
+ return out;
197
+ }