@vitavision/overlays 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +60 -0
- package/dist/index.js +101 -9
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/src/TargetOverlay.tsx +48 -2
- package/src/glyphs.ts +32 -0
- package/src/index.ts +2 -0
- package/src/layerItems.ts +37 -0
- package/src/model.ts +36 -0
package/dist/index.d.ts
CHANGED
|
@@ -59,6 +59,18 @@ interface TargetCorner {
|
|
|
59
59
|
cov?: readonly [xx: number, xy: number, yy: number] | undefined;
|
|
60
60
|
/** Text beside it. Defaults to the lattice index `i,j` on a board, else the id. */
|
|
61
61
|
label?: string | undefined;
|
|
62
|
+
/**
|
|
63
|
+
* The feature is excluded from use (left out of a fit, switched off by the person): it is
|
|
64
|
+
* drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on
|
|
65
|
+
* it, so it is not drawn like a rejected point. It still takes hover and presses.
|
|
66
|
+
*/
|
|
67
|
+
excluded?: boolean | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* The feature is flagged: a thin ring is drawn around it, for "this feature disagrees with
|
|
70
|
+
* what it should be" (a decoded id that differs from the master pattern, say). It composes
|
|
71
|
+
* with `excluded`, hover and selection.
|
|
72
|
+
*/
|
|
73
|
+
flagged?: boolean | undefined;
|
|
62
74
|
}
|
|
63
75
|
/** One decoded fiducial marker (ArUco, AprilTag): a quad. */
|
|
64
76
|
interface TargetMarker {
|
|
@@ -90,6 +102,18 @@ interface TargetCircle {
|
|
|
90
102
|
j?: number | undefined;
|
|
91
103
|
/** Text beside it. Defaults to `(i, j)` when both are set. */
|
|
92
104
|
label?: string | undefined;
|
|
105
|
+
/**
|
|
106
|
+
* The feature is excluded from use (left out of a fit, switched off by the person): it is
|
|
107
|
+
* drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on
|
|
108
|
+
* it, so it is not drawn like a rejected point. It still takes hover and presses.
|
|
109
|
+
*/
|
|
110
|
+
excluded?: boolean | undefined;
|
|
111
|
+
/**
|
|
112
|
+
* The feature is flagged: a thin ring is drawn around it, for "this feature disagrees with
|
|
113
|
+
* what it should be" (a decoded id that differs from the master pattern, say). It composes
|
|
114
|
+
* with `excluded`, hover and selection.
|
|
115
|
+
*/
|
|
116
|
+
flagged?: boolean | undefined;
|
|
93
117
|
}
|
|
94
118
|
/** A fitted ellipse. */
|
|
95
119
|
interface TargetEllipse {
|
|
@@ -114,6 +138,18 @@ interface TargetRing {
|
|
|
114
138
|
inner?: TargetEllipse | undefined;
|
|
115
139
|
/** Text beside the centre. Defaults to the id. */
|
|
116
140
|
label?: string | undefined;
|
|
141
|
+
/**
|
|
142
|
+
* The ring is excluded from use (left out of a fit, switched off by the person): it is
|
|
143
|
+
* drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on
|
|
144
|
+
* it, so it is not drawn like a rejected point. It still takes hover and presses.
|
|
145
|
+
*/
|
|
146
|
+
excluded?: boolean | undefined;
|
|
147
|
+
/**
|
|
148
|
+
* The ring is flagged: a thin ring is drawn around its centre, for "this feature disagrees with
|
|
149
|
+
* what it should be" (a decoded id that differs from the master pattern, say). It composes
|
|
150
|
+
* with `excluded`, hover and selection.
|
|
151
|
+
*/
|
|
152
|
+
flagged?: boolean | undefined;
|
|
117
153
|
}
|
|
118
154
|
/**
|
|
119
155
|
* One decoded bit of a PuzzleBoard, drawn as a dot on the edge between two corners.
|
|
@@ -218,6 +254,10 @@ interface TargetOverlayProps {
|
|
|
218
254
|
* - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move
|
|
219
255
|
* between layers (a corner, then the marker under it) without a flicker: the change is reported
|
|
220
256
|
* once.
|
|
257
|
+
* - **Excluded and flagged features**: a corner, circle or ring with `excluded` is drawn dimmed
|
|
258
|
+
* with a small cross through it (a state, not a rejection); one with `flagged` has a thin ring
|
|
259
|
+
* around it (a mismatch with the master pattern, say). Both are drawn in the `label` role on a
|
|
260
|
+
* halo, compose with hover, selection and each other, and are not picked themselves.
|
|
221
261
|
* - **Uncertainty** (opt-in, `uncertainty`): each corner's covariance as a 1σ ellipse × the
|
|
222
262
|
* given scale, under the corners.
|
|
223
263
|
*
|
|
@@ -381,6 +421,10 @@ export declare const TARGET_MARKERS: {
|
|
|
381
421
|
readonly "circle-white": MarkerShape;
|
|
382
422
|
/** A black matched circle. */
|
|
383
423
|
readonly "circle-black": MarkerShape;
|
|
424
|
+
/** The cross through an excluded feature. */
|
|
425
|
+
readonly excluded: MarkerShape;
|
|
426
|
+
/** The ring around a flagged feature. */
|
|
427
|
+
readonly flagged: MarkerShape;
|
|
384
428
|
};
|
|
385
429
|
//#endregion
|
|
386
430
|
//#region src/layerItems.d.ts
|
|
@@ -463,6 +507,22 @@ export declare function covarianceEllipse(cov: readonly [xx: number, xy: number,
|
|
|
463
507
|
* @returns One ellipse per corner with a drawable covariance, in order.
|
|
464
508
|
*/
|
|
465
509
|
export declare function uncertaintyEllipses(corners: readonly TargetCorner[], scale: number): EllipseSetItem$1[];
|
|
510
|
+
/**
|
|
511
|
+
* The strike-through points of the excluded features: a corner, circle or ring with
|
|
512
|
+
* `excluded` set gets one `excluded` glyph at its position. Markers carry no flags.
|
|
513
|
+
*
|
|
514
|
+
* @param detection - The detection.
|
|
515
|
+
* @returns One point per excluded feature, corners first, then circles, then rings.
|
|
516
|
+
*/
|
|
517
|
+
export declare function excludedPoints(detection: TargetDetection): PointSetItem[];
|
|
518
|
+
/**
|
|
519
|
+
* The ring points of the flagged features: a corner, circle or ring with `flagged` set gets one
|
|
520
|
+
* `flagged` glyph at its position.
|
|
521
|
+
*
|
|
522
|
+
* @param detection - The detection.
|
|
523
|
+
* @returns One point per flagged feature, corners first, then circles, then rings.
|
|
524
|
+
*/
|
|
525
|
+
export declare function flaggedPoints(detection: TargetDetection): PointSetItem[];
|
|
466
526
|
//#endregion
|
|
467
527
|
//#region src/calibTargets.d.ts
|
|
468
528
|
/** An image point `[x, y]`, pixels with the centre of pixel `i` at `i` (calib-targets' `Point2`). */
|
package/dist/index.js
CHANGED
|
@@ -50,21 +50,46 @@ const directed = {
|
|
|
50
50
|
const CIRCLE_RADIUS = 5.5;
|
|
51
51
|
/** Radius of the centre mark of a black circle, screen pixels; stroked, it reads as a filled dot. */
|
|
52
52
|
const CENTRE_RADIUS = .8;
|
|
53
|
+
/** A white circle of a marker board: a hollow ring of radius 5.5 px. */
|
|
54
|
+
const circleWhite = {
|
|
55
|
+
paint: "line",
|
|
56
|
+
size: CIRCLE_RADIUS,
|
|
57
|
+
path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit)
|
|
58
|
+
};
|
|
59
|
+
/** A black circle: the same ring with a dot at its centre, so polarity is a shape and not a colour. */
|
|
60
|
+
const circleBlack = {
|
|
61
|
+
paint: "line",
|
|
62
|
+
size: CIRCLE_RADIUS,
|
|
63
|
+
path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit) + circlePath(x, y, CENTRE_RADIUS * unit)
|
|
64
|
+
};
|
|
65
|
+
/** Half-length of an excluded feature's strike-through cross, screen pixels. */
|
|
66
|
+
const EXCLUDED_REACH = 6;
|
|
67
|
+
/** Radius of a flagged feature's ring, screen pixels: outside the selection ring (about 9 px). */
|
|
68
|
+
const FLAG_RADIUS = 12;
|
|
53
69
|
/** The marker names `TargetOverlay` uses, to pass to `PointSet`'s `markers`. */
|
|
54
70
|
const TARGET_MARKERS = {
|
|
55
71
|
/** Edge directions of a corner, from `angle` and `angle2`. */
|
|
56
72
|
directed,
|
|
57
73
|
/** A white matched circle. */
|
|
58
|
-
"circle-white":
|
|
74
|
+
"circle-white": circleWhite,
|
|
75
|
+
/** A black matched circle. */
|
|
76
|
+
"circle-black": circleBlack,
|
|
77
|
+
/** The cross through an excluded feature. */
|
|
78
|
+
excluded: {
|
|
59
79
|
paint: "line",
|
|
60
|
-
size:
|
|
61
|
-
|
|
80
|
+
size: EXCLUDED_REACH,
|
|
81
|
+
role: "label",
|
|
82
|
+
path: (x, y, unit) => {
|
|
83
|
+
const a = EXCLUDED_REACH * unit;
|
|
84
|
+
return `M${round(x - a)} ${round(y - a)}l${round(2 * a)} ${round(2 * a)}M${round(x - a)} ${round(y + a)}l${round(2 * a)} ${round(-2 * a)}`;
|
|
85
|
+
}
|
|
62
86
|
},
|
|
63
|
-
/**
|
|
64
|
-
|
|
87
|
+
/** The ring around a flagged feature. */
|
|
88
|
+
flagged: {
|
|
65
89
|
paint: "line",
|
|
66
|
-
size:
|
|
67
|
-
|
|
90
|
+
size: FLAG_RADIUS,
|
|
91
|
+
role: "label",
|
|
92
|
+
path: (x, y, unit) => circlePath(x, y, FLAG_RADIUS * unit)
|
|
68
93
|
}
|
|
69
94
|
};
|
|
70
95
|
//#endregion
|
|
@@ -446,6 +471,42 @@ function uncertaintyEllipses(corners, scale) {
|
|
|
446
471
|
}
|
|
447
472
|
return out;
|
|
448
473
|
}
|
|
474
|
+
/** The feature points of a detection (corners, circles, ring centres) that carry `flag`, as one point each of `kind`. */
|
|
475
|
+
function markedPoints(detection, flag, kind) {
|
|
476
|
+
const out = [];
|
|
477
|
+
const add = (items) => {
|
|
478
|
+
for (const item of items ?? []) if (item[flag] === true) out.push({
|
|
479
|
+
id: item.id,
|
|
480
|
+
x: item.x,
|
|
481
|
+
y: item.y,
|
|
482
|
+
kind
|
|
483
|
+
});
|
|
484
|
+
};
|
|
485
|
+
add(detection.corners);
|
|
486
|
+
add(detection.circles);
|
|
487
|
+
add(detection.rings);
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* The strike-through points of the excluded features: a corner, circle or ring with
|
|
492
|
+
* `excluded` set gets one `excluded` glyph at its position. Markers carry no flags.
|
|
493
|
+
*
|
|
494
|
+
* @param detection - The detection.
|
|
495
|
+
* @returns One point per excluded feature, corners first, then circles, then rings.
|
|
496
|
+
*/
|
|
497
|
+
function excludedPoints(detection) {
|
|
498
|
+
return markedPoints(detection, "excluded", "excluded");
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* The ring points of the flagged features: a corner, circle or ring with `flagged` set gets one
|
|
502
|
+
* `flagged` glyph at its position.
|
|
503
|
+
*
|
|
504
|
+
* @param detection - The detection.
|
|
505
|
+
* @returns One point per flagged feature, corners first, then circles, then rings.
|
|
506
|
+
*/
|
|
507
|
+
function flaggedPoints(detection) {
|
|
508
|
+
return markedPoints(detection, "flagged", "flagged");
|
|
509
|
+
}
|
|
449
510
|
//#endregion
|
|
450
511
|
//#region src/TargetOverlay.tsx
|
|
451
512
|
/**
|
|
@@ -466,6 +527,8 @@ function uncertaintyEllipses(corners, scale) {
|
|
|
466
527
|
* | `rings` | `PointSet` + `EllipseSet` | fitted outer and inner ellipse, plus at the centre |
|
|
467
528
|
* | `edgeBits` | `EllipseSet` | dot on the edge: solid for 1, dashed for 0, opacity from confidence |
|
|
468
529
|
* | corners' `cov` | `EllipseSet` | with `uncertainty`: the 1σ ellipse × the scale, in `model` |
|
|
530
|
+
* | `excluded` features | `PointSet` | the feature dimmed, a small cross through it |
|
|
531
|
+
* | `flagged` features | `PointSet` | a thin ring around the feature |
|
|
469
532
|
*/
|
|
470
533
|
/** The ids of each part, to route a hovered or selected id to the layers that have it. */
|
|
471
534
|
function idsByPart(detection) {
|
|
@@ -497,6 +560,10 @@ function dimPredicate(dimmed) {
|
|
|
497
560
|
* - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move
|
|
498
561
|
* between layers (a corner, then the marker under it) without a flicker: the change is reported
|
|
499
562
|
* once.
|
|
563
|
+
* - **Excluded and flagged features**: a corner, circle or ring with `excluded` is drawn dimmed
|
|
564
|
+
* with a small cross through it (a state, not a rejection); one with `flagged` has a thin ring
|
|
565
|
+
* around it (a mismatch with the master pattern, say). Both are drawn in the `label` role on a
|
|
566
|
+
* halo, compose with hover, selection and each other, and are not picked themselves.
|
|
500
567
|
* - **Uncertainty** (opt-in, `uncertainty`): each corner's covariance as a 1σ ellipse × the
|
|
501
568
|
* given scale, under the corners.
|
|
502
569
|
*
|
|
@@ -523,7 +590,14 @@ function TargetOverlay({ detection, showEdges = true, showLabels = true, hovered
|
|
|
523
590
|
ring: pick("ring")
|
|
524
591
|
};
|
|
525
592
|
}, [selectedSet, ids]);
|
|
526
|
-
const
|
|
593
|
+
const userDimmed = useMemo(() => dimPredicate(dimmed), [dimmed]);
|
|
594
|
+
const excluded = useMemo(() => excludedPoints(detection), [detection]);
|
|
595
|
+
const flagged = useMemo(() => flaggedPoints(detection), [detection]);
|
|
596
|
+
const isDimmed = useMemo(() => {
|
|
597
|
+
if (excluded.length === 0) return userDimmed;
|
|
598
|
+
const ids = new Set(excluded.map((item) => item.id));
|
|
599
|
+
return (id) => ids.has(id) || (userDimmed?.(id) ?? false);
|
|
600
|
+
}, [excluded, userDimmed]);
|
|
527
601
|
const [ownHover, setOwnHover] = useState(null);
|
|
528
602
|
const hoverRef = useRef(null);
|
|
529
603
|
const reportedRef = useRef(null);
|
|
@@ -652,6 +726,24 @@ function TargetOverlay({ detection, showEdges = true, showLabels = true, hovered
|
|
|
652
726
|
onItemPress: pressFrom("circle"),
|
|
653
727
|
layerId: layerId("circles"),
|
|
654
728
|
label: "Circles"
|
|
729
|
+
}),
|
|
730
|
+
excluded.length > 0 && /* @__PURE__ */ jsx(PointSet, {
|
|
731
|
+
items: excluded,
|
|
732
|
+
markers: TARGET_MARKERS,
|
|
733
|
+
labels: false,
|
|
734
|
+
dimmed: userDimmed,
|
|
735
|
+
pickable: false,
|
|
736
|
+
layerId: layerId("excluded"),
|
|
737
|
+
label: "Excluded features"
|
|
738
|
+
}),
|
|
739
|
+
flagged.length > 0 && /* @__PURE__ */ jsx(PointSet, {
|
|
740
|
+
items: flagged,
|
|
741
|
+
markers: TARGET_MARKERS,
|
|
742
|
+
labels: false,
|
|
743
|
+
dimmed: userDimmed,
|
|
744
|
+
pickable: false,
|
|
745
|
+
layerId: layerId("flagged"),
|
|
746
|
+
label: "Flagged features"
|
|
655
747
|
})
|
|
656
748
|
] });
|
|
657
749
|
}
|
|
@@ -872,6 +964,6 @@ function fromCalibTargets(result) {
|
|
|
872
964
|
return detection;
|
|
873
965
|
}
|
|
874
966
|
//#endregion
|
|
875
|
-
export { EllipseSet, PUZZLEBOARD_PERIOD, TARGET_KINDS, TARGET_MARKERS, TargetOverlay, circlePoints, cornerGrid, cornerNodes, covarianceEllipse, edgeBitEllipses, edgeBitsFromPuzzleboard, ellipsePath, fromCalibTargets, gridEdges, gridKey, idByGrid, isLatticeKind, markerAreas, markerPolygons, ringCentres, ringEllipses, uncertaintyEllipses };
|
|
967
|
+
export { EllipseSet, PUZZLEBOARD_PERIOD, TARGET_KINDS, TARGET_MARKERS, TargetOverlay, circlePoints, cornerGrid, cornerNodes, covarianceEllipse, edgeBitEllipses, edgeBitsFromPuzzleboard, ellipsePath, excludedPoints, flaggedPoints, fromCalibTargets, gridEdges, gridKey, idByGrid, isLatticeKind, markerAreas, markerPolygons, ringCentres, ringEllipses, uncertaintyEllipses };
|
|
876
968
|
|
|
877
969
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["EllipseSet"],"sources":["../src/glyphs.ts","../src/lattice.ts","../src/model.ts","../src/layerItems.ts","../src/TargetOverlay.tsx","../src/puzzleboard.ts","../src/calibTargets.ts"],"sourcesContent":["/**\n * The glyphs of a calibration-target overlay, as path generators.\n *\n * A glyph is a `MarkerShape` for `@vitavision/stage2d`'s `PointSet`: a pure function from a\n * position to SVG path data, so a layer appends thousands of them into one `<path>`.\n * They are registered under the names in `TARGET_MARKERS`, which `TargetOverlay` passes as\n * `markers`. Sizes are screen pixels, from `unit` (image pixels per screen pixel).\n *\n * Pure: no React, no DOM.\n */\n\nimport { circlePath, type MarkerShape } from \"@vitavision/stage2d\";\n\n/** Round to 1/1000 of an image pixel. */\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n\n/** An angle as a direction of a line: modulo π, in [0, π). */\nfunction lineAngle(angle: number): number {\n const wrapped = angle % Math.PI;\n return wrapped < 0 ? wrapped + Math.PI : wrapped;\n}\n\n/** Half-length of a directed corner's axes, and the gap left at its centre, in screen pixels. */\nconst AXIS_REACH = 8;\nconst AXIS_GAP = 2;\n\n/**\n * A corner with its edge directions: one or two lines through the point, 8 px each way with a\n * 2 px gap at the centre, so the corner itself stays visible. Give it `angle` and, for the\n * second direction, `angle2`. Directions are lines, so each is read modulo π.\n */\nconst directed: MarkerShape = {\n paint: \"line\",\n size: AXIS_REACH,\n path: (x, y, unit, angle, angle2) => {\n let d = \"\";\n for (const direction of angle2 === undefined ? [angle] : [angle, angle2]) {\n if (!Number.isFinite(direction)) continue;\n const line = lineAngle(direction);\n const c = Math.cos(line);\n const s = Math.sin(line);\n const near = AXIS_GAP * unit;\n const far = AXIS_REACH * unit;\n d +=\n `M${round(x - far * c)} ${round(y - far * s)}L${round(x - near * c)} ${round(y - near * s)}` +\n `M${round(x + near * c)} ${round(y + near * s)}L${round(x + far * c)} ${round(y + far * s)}`;\n }\n return d;\n },\n};\n\n/** Radius of a matched circle's glyph, screen pixels. */\nconst CIRCLE_RADIUS = 5.5;\n/** Radius of the centre mark of a black circle, screen pixels; stroked, it reads as a filled dot. */\nconst CENTRE_RADIUS = 0.8;\n\n/** A white circle of a marker board: a hollow ring of radius 5.5 px. */\nconst circleWhite: MarkerShape = {\n paint: \"line\",\n size: CIRCLE_RADIUS,\n path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit),\n};\n\n/** A black circle: the same ring with a dot at its centre, so polarity is a shape and not a colour. */\nconst circleBlack: MarkerShape = {\n paint: \"line\",\n size: CIRCLE_RADIUS,\n path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit) + circlePath(x, y, CENTRE_RADIUS * unit),\n};\n\n/** The marker names `TargetOverlay` uses, to pass to `PointSet`'s `markers`. */\nexport const TARGET_MARKERS = {\n /** Edge directions of a corner, from `angle` and `angle2`. */\n directed,\n /** A white matched circle. */\n \"circle-white\": circleWhite,\n /** A black matched circle. */\n \"circle-black\": circleBlack,\n} as const satisfies Readonly<Record<string, MarkerShape>>;\n","/**\n * The lattice of a detected board: which corner sits at which `(i, j)`, which corners are\n * neighbours, and the polygons of the markers.\n *\n * Ported from vitavision's `overlayData.ts` (`buildCornerGrid`, `buildGridEdges`,\n * `buildFeatureIdByGrid`, `buildMarkerPolygons`), where ChArUco, chessboard, marker board and\n * PuzzleBoard each carried a copy (PuzzleBoard's `buildPuzzleGrid` was a fourth). One\n * implementation now serves all four, on the normalised `TargetDetection` input.\n *\n * Pure: no React, no DOM.\n */\n\nimport { latticeEdges } from \"@vitavision/stage2d\";\n\nimport type { TargetCorner, TargetId, TargetMarker } from \"./model\";\n\n/** A corner that has a place on the board. */\nexport type GridCorner = TargetCorner & { i: number; j: number };\n\n/** The extent of a lattice, inclusive. */\nexport interface GridBounds {\n /** Smallest `i`. */\n minI: number;\n /** Largest `i`. */\n maxI: number;\n /** Smallest `j`. */\n minJ: number;\n /** Largest `j`. */\n maxJ: number;\n}\n\n/** The corners of a board, indexed by lattice position. */\nexport interface CornerGrid {\n /** The corners with an integer `(i, j)`, in input order. A repeated `(i, j)` keeps its first corner. */\n nodes: readonly GridCorner[];\n /** Position in `nodes` by `gridKey(i, j)`. */\n byIndex: ReadonlyMap<string, number>;\n /** Positions in `nodes` grouped by `i` (ascending), each group sorted by `j`. */\n rows: readonly (readonly number[])[];\n /** Positions in `nodes` grouped by `j` (ascending), each group sorted by `i`. */\n cols: readonly (readonly number[])[];\n /** The extent, or `null` for an empty grid. */\n bounds: GridBounds | null;\n}\n\n/** A segment between two neighbouring corners. */\nexport interface GridSegment {\n /** Id of the end with the lower index along the edge's axis. */\n a: TargetId;\n /** Id of the end with the higher index. */\n b: TargetId;\n /** Start x. */\n x1: number;\n /** Start y. */\n y1: number;\n /** End x. */\n x2: number;\n /** End y. */\n y2: number;\n}\n\n/** A marker as a closed polygon. */\nexport interface MarkerPolygon {\n /** The marker's id. */\n id: TargetId;\n /** Flat `[x0, y0, x1, y1, …]`; the last vertex joins the first. */\n points: number[];\n /** The mean of the vertices. */\n centre: { x: number; y: number };\n /** The marker's own label, if it has one. */\n label?: string | undefined;\n}\n\n/**\n * The key of a lattice position, as `idByGrid` and `CornerGrid.byIndex` use.\n *\n * @param i - Index along the first axis.\n * @param j - Index along the second axis.\n * @returns `\"i:j\"`.\n */\nexport function gridKey(i: number, j: number): string {\n return `${i}:${j}`;\n}\n\n/** Whether a corner carries an integer lattice index. */\nfunction isGridCorner(corner: TargetCorner): corner is GridCorner {\n return Number.isInteger(corner.i) && Number.isInteger(corner.j);\n}\n\n/**\n * Index a board's corners by lattice position.\n *\n * Corners without an integer `(i, j)` are not part of the grid. When two corners claim one\n * position the first wins, as it does in `latticeEdges`.\n *\n * @param corners - The detected corners, in any order, with gaps allowed.\n * @returns The grid.\n */\nexport function cornerGrid(corners: readonly TargetCorner[]): CornerGrid {\n const nodes: GridCorner[] = [];\n const byIndex = new Map<string, number>();\n const rowMap = new Map<number, number[]>();\n const colMap = new Map<number, number[]>();\n let bounds: GridBounds | null = null;\n\n for (const corner of corners) {\n if (!isGridCorner(corner)) continue;\n const key = gridKey(corner.i, corner.j);\n if (byIndex.has(key)) continue;\n const position = nodes.length;\n nodes.push(corner);\n byIndex.set(key, position);\n const row = rowMap.get(corner.i);\n if (row) row.push(position);\n else rowMap.set(corner.i, [position]);\n const col = colMap.get(corner.j);\n if (col) col.push(position);\n else colMap.set(corner.j, [position]);\n bounds = bounds\n ? {\n minI: Math.min(bounds.minI, corner.i),\n maxI: Math.max(bounds.maxI, corner.i),\n minJ: Math.min(bounds.minJ, corner.j),\n maxJ: Math.max(bounds.maxJ, corner.j),\n }\n : { minI: corner.i, maxI: corner.i, minJ: corner.j, maxJ: corner.j };\n }\n\n const ordered = (groups: Map<number, number[]>, by: \"i\" | \"j\") =>\n [...groups.entries()].sort(([a], [b]) => a - b).map(([, group]) => group.sort((p, q) => nodes[p]![by] - nodes[q]![by]));\n return { nodes, byIndex, rows: ordered(rowMap, \"j\"), cols: ordered(colMap, \"i\"), bounds };\n}\n\n/**\n * The edges between neighbouring corners of a grid: `(i, j)` to `(i, j + 1)` are the row edges,\n * `(i, j)` to `(i + 1, j)` the column edges. A missed corner leaves a gap, never a long edge.\n * It is `latticeEdges` from `@vitavision/stage2d` with positions attached.\n *\n * @param grid - From `cornerGrid`.\n * @returns The two edge lists.\n */\nexport function gridEdges(grid: CornerGrid): { rowEdges: GridSegment[]; colEdges: GridSegment[] } {\n const rowEdges: GridSegment[] = [];\n const colEdges: GridSegment[] = [];\n for (const edge of latticeEdges(grid.nodes)) {\n const a = grid.nodes[edge.a]!;\n const b = grid.nodes[edge.b]!;\n (edge.axis === \"j\" ? rowEdges : colEdges).push({ a: a.id, b: b.id, x1: a.x, y1: a.y, x2: b.x, y2: b.y });\n }\n return { rowEdges, colEdges };\n}\n\n/**\n * The id of the corner at each lattice position, to map a board cell back to an app's feature.\n *\n * @param corners - The detected corners.\n * @returns Ids by `gridKey(i, j)`. A corner without an integer index is left out; the first of two sharing a position wins.\n */\nexport function idByGrid(corners: readonly TargetCorner[]): Map<string, TargetId> {\n const map = new Map<string, TargetId>();\n for (const corner of corners) {\n if (!isGridCorner(corner)) continue;\n const key = gridKey(corner.i, corner.j);\n if (!map.has(key)) map.set(key, corner.id);\n }\n return map;\n}\n\n/**\n * The markers as polygons, with their centres.\n *\n * @param markers - The detected markers.\n * @returns A polygon per marker that has at least three finite vertices; the others are dropped.\n */\nexport function markerPolygons(markers: readonly TargetMarker[]): MarkerPolygon[] {\n const out: MarkerPolygon[] = [];\n for (const marker of markers) {\n const n = marker.corners.length;\n if (n < 6 || n % 2 !== 0 || !marker.corners.every(Number.isFinite)) continue;\n let sx = 0;\n let sy = 0;\n for (let k = 0; k < n; k += 2) {\n sx += marker.corners[k]!;\n sy += marker.corners[k + 1]!;\n }\n const polygon: MarkerPolygon = {\n id: marker.id,\n points: [...marker.corners],\n centre: { x: sx / (n / 2), y: sy / (n / 2) },\n };\n if (marker.label !== undefined) polygon.label = marker.label;\n out.push(polygon);\n }\n return out;\n}\n","/**\n * The input model: one detection run, independent of the library that produced it.\n *\n * Every detector in the vitavision family (calib-targets' chessboard, ChArUco, marker board and\n * PuzzleBoard, ringgrid, chess-corners) returns its own result shape. An app maps that shape to a\n * `TargetDetection` once (for calib-targets, `fromCalibTargets` is that mapping), and the overlay\n * never learns which library ran. Nothing here imports a detector package: these are plain data\n * types.\n *\n * Conventions, the same as `@vitavision/stage2d`:\n * - Positions are **image pixels, with the centre of pixel `i` at coordinate `i`** (the frame\n * the WASM detectors report, `image_px_center`). The stage places them; do not add 0.5.\n * - `y` points down. Angles are **radians, clockwise on screen** (from +x towards +y).\n * - Lengths named `rx`, `ry` and `radius` are image pixels, so they scale with the image.\n *\n * Pure: no React, no DOM.\n */\n\n/** An item's identity. Ids are unique within one detection, across corners, markers, circles and rings. */\nexport type TargetId = string | number;\n\n/** What a detection is of. It chooses defaults, not what is drawn: whatever is present is drawn. */\nexport type TargetKind = \"chessboard\" | \"charuco\" | \"markerboard\" | \"puzzleboard\" | \"ringgrid\" | \"corners\" | \"circles\";\n\n/** Every `TargetKind`. */\nexport const TARGET_KINDS: readonly TargetKind[] = [\n \"chessboard\",\n \"charuco\",\n \"markerboard\",\n \"puzzleboard\",\n \"ringgrid\",\n \"corners\",\n \"circles\",\n];\n\n/** The kinds whose corners form a lattice, so their neighbours are joined by edges. */\nconst LATTICE_KINDS: ReadonlySet<TargetKind> = new Set([\"chessboard\", \"charuco\", \"markerboard\", \"puzzleboard\"]);\n\n/**\n * Whether a detection of this kind draws lattice edges between corner neighbours.\n *\n * @param kind - The detection's kind.\n * @returns `true` for the four calibration boards, `false` for loose corners, circles and rings.\n */\nexport function isLatticeKind(kind: TargetKind): boolean {\n return LATTICE_KINDS.has(kind);\n}\n\n/** One detected corner or X-junction. */\nexport interface TargetCorner {\n /** Its identity. Callbacks report this id back. */\n id: TargetId;\n /** Horizontal position, image pixels. */\n x: number;\n /** Vertical position, image pixels. */\n y: number;\n /** Lattice index along the first board axis, an integer. Absent for a corner with no place on a board. */\n i?: number | undefined;\n /** Lattice index along the second board axis, an integer. */\n j?: number | undefined;\n /**\n * The detector's confidence. It is carried for the app (a list, a filter) and never drawn as a\n * colour: a score is not a verdict.\n */\n score?: number | undefined;\n /** Orientation of the first edge through the corner, radians. Axes are lines, so `angle` and `angle + π` are the same. */\n angle?: number | undefined;\n /** Orientation of the second edge through the corner, radians. Needs `angle`. */\n angle2?: number | undefined;\n /**\n * The covariance of the position, image pixels squared: the three distinct entries\n * `[xx, xy, yy]` of the symmetric 2×2 matrix. `TargetOverlay`'s `uncertainty` prop draws it as\n * a 1σ ellipse; a matrix that is not positive definite is not drawn.\n */\n cov?: readonly [xx: number, xy: number, yy: number] | undefined;\n /** Text beside it. Defaults to the lattice index `i,j` on a board, else the id. */\n label?: string | undefined;\n}\n\n/** One decoded fiducial marker (ArUco, AprilTag): a quad. */\nexport interface TargetMarker {\n /** Its identity. For an ArUco marker, usually its dictionary id. */\n id: TargetId;\n /**\n * The quad's corners in the marker's own order, `[x0, y0, x1, y1, x2, y2, x3, y3]`. Corner 0 is\n * ticked, so the order reads as the marker's orientation.\n */\n corners: readonly number[];\n /** Text drawn inside it. Defaults to the id. */\n label?: string | undefined;\n}\n\n/** The printed colour of a circle in a marker board. */\nexport type CirclePolarity = \"white\" | \"black\";\n\n/** One detected circle of a marker board, matched or not to the board model. */\nexport interface TargetCircle {\n /** Its identity. */\n id: TargetId;\n /** Centre x, image pixels. */\n x: number;\n /** Centre y, image pixels. */\n y: number;\n /** Printed polarity. It is drawn as a shape (hollow ring, or ring with a centre dot), not as a colour. */\n polarity: CirclePolarity;\n /** The board cell it matched, first axis. */\n i?: number | undefined;\n /** The board cell it matched, second axis. */\n j?: number | undefined;\n /** Text beside it. Defaults to `(i, j)` when both are set. */\n label?: string | undefined;\n}\n\n/** A fitted ellipse. */\nexport interface TargetEllipse {\n /** Semi-axis along the rotated x axis, image pixels. */\n rx: number;\n /** Semi-axis along the rotated y axis, image pixels. */\n ry: number;\n /** Rotation of the `rx` axis, radians clockwise on screen. */\n angle: number;\n}\n\n/** One ring marker of a ring grid: two concentric fitted ellipses and a centre. */\nexport interface TargetRing {\n /** Its identity. */\n id: TargetId;\n /** Centre x, image pixels. */\n x: number;\n /** Centre y, image pixels. */\n y: number;\n /** The outer edge of the ring. */\n outer: TargetEllipse;\n /** The inner edge of the ring, when the detector fitted one. */\n inner?: TargetEllipse | undefined;\n /** Text beside the centre. Defaults to the id. */\n label?: string | undefined;\n}\n\n/**\n * One decoded bit of a PuzzleBoard, drawn as a dot on the edge between two corners.\n * `edgeBitsFromPuzzleboard` builds these from a PuzzleBoard result.\n */\nexport interface TargetEdgeBit {\n /** Its identity. Not reported by callbacks: edge bits are not picked. */\n id: TargetId;\n /** Midpoint x of the edge, image pixels. */\n x: number;\n /** Midpoint y of the edge, image pixels. */\n y: number;\n /** The dot's radius, image pixels: about a quarter of the edge. */\n radius: number;\n /** The decoded bit. 1 is a solid dot, 0 a dashed one. */\n bit: 0 | 1;\n /** Decode confidence in [0, 1]. It sets the dot's opacity. */\n confidence: number;\n}\n\n/** One detection run: what a detector found in one image. */\nexport interface TargetDetection {\n /** What was detected. */\n kind: TargetKind;\n /** Corners and X-junctions. */\n corners?: readonly TargetCorner[] | undefined;\n /** Decoded fiducial markers. */\n markers?: readonly TargetMarker[] | undefined;\n /** Marker-board circles. */\n circles?: readonly TargetCircle[] | undefined;\n /** Ring markers. */\n rings?: readonly TargetRing[] | undefined;\n /** PuzzleBoard edge bits. */\n edgeBits?: readonly TargetEdgeBit[] | undefined;\n}\n\n/** The part of a detection an item belongs to. */\nexport type TargetPart = \"corner\" | \"marker\" | \"circle\" | \"ring\";\n\n/** Which item the pointer is on. */\nexport interface TargetHit {\n /** The item's id, as given in the detection. */\n id: TargetId;\n /** The collection it came from. */\n part: TargetPart;\n}\n","/**\n * What each stage2d layer is given, for each part of a detection: the pure mapping from the\n * normalised `TargetDetection` to the items of `GridLayer`, `AreaSet`, `PointSet` and\n * `EllipseSet`. `TargetOverlay` is these plus the wiring, so this is where the overlay's\n * decisions are, and where they are tested without a DOM.\n *\n * Pure: no React, no DOM.\n */\n\nimport type { AreaSetItem, EllipseSetItem, GridNode, PointSetItem } from \"@vitavision/stage2d\";\n\nimport { markerPolygons } from \"./lattice\";\nimport {\n isLatticeKind,\n type TargetCircle,\n type TargetCorner,\n type TargetDetection,\n type TargetEdgeBit,\n type TargetEllipse,\n type TargetRing,\n} from \"./model\";\n\n/** The label of a corner: its own, else the lattice index on a board, else the id. */\nfunction cornerLabel(corner: TargetCorner, lattice: boolean): string {\n if (corner.label !== undefined) return corner.label;\n if (lattice && Number.isInteger(corner.i) && Number.isInteger(corner.j)) return `${corner.i},${corner.j}`;\n return String(corner.id);\n}\n\n/**\n * The nodes of the corner layer.\n *\n * A corner with an `angle` is a `directed` marker (its edge directions, one or two), any other a\n * `plus`. On a board kind the lattice indices are kept, so `GridLayer` joins neighbours; on any\n * other kind they are `NaN`, which `latticeEdges` reads as \"not part of a lattice\", so no edge is\n * drawn.\n *\n * @param detection - The detection.\n * @returns One node per corner, in order.\n */\nexport function cornerNodes(detection: TargetDetection): GridNode[] {\n const lattice = isLatticeKind(detection.kind);\n return (detection.corners ?? []).map((corner): GridNode => {\n const node: GridNode = {\n id: corner.id,\n x: corner.x,\n y: corner.y,\n i: lattice && Number.isInteger(corner.i) ? corner.i! : Number.NaN,\n j: lattice && Number.isInteger(corner.j) ? corner.j! : Number.NaN,\n label: cornerLabel(corner, lattice),\n };\n if (corner.angle !== undefined) {\n node.kind = \"directed\";\n node.angle = corner.angle;\n if (corner.angle2 !== undefined) node.angle2 = corner.angle2;\n }\n return node;\n });\n}\n\n/**\n * The regions of the marker layer: each marker's quad, labelled with its text or its id.\n *\n * @param detection - The detection.\n * @returns One area per marker with a usable quad.\n */\nexport function markerAreas(detection: TargetDetection): AreaSetItem[] {\n return markerPolygons(detection.markers ?? []).map((polygon) => ({\n id: polygon.id,\n points: polygon.points,\n label: polygon.label ?? String(polygon.id),\n }));\n}\n\n/** The label of a circle: its own, else `(i, j)` when it matched a cell. */\nfunction circleLabel(circle: TargetCircle): string | undefined {\n if (circle.label !== undefined) return circle.label;\n return Number.isInteger(circle.i) && Number.isInteger(circle.j) ? `(${circle.i}, ${circle.j})` : undefined;\n}\n\n/**\n * The points of the circle layer. Polarity picks the glyph: `circle-white` is a hollow ring,\n * `circle-black` a ring with a dot.\n *\n * @param detection - The detection.\n * @returns One point per circle.\n */\nexport function circlePoints(detection: TargetDetection): PointSetItem[] {\n return (detection.circles ?? []).map((circle) => {\n const item: PointSetItem = { id: circle.id, x: circle.x, y: circle.y, kind: `circle-${circle.polarity}` };\n const label = circleLabel(circle);\n if (label !== undefined) item.label = label;\n return item;\n });\n}\n\n/**\n * The points of the ring layer: a `plus` at each centre, picked anywhere inside the outer ellipse\n * (`pickRadius` is the larger semi-axis), labelled with the ring's text or its id.\n *\n * @param rings - The rings.\n * @returns One point per ring.\n */\nexport function ringCentres(rings: readonly TargetRing[]): PointSetItem[] {\n return rings.map((ring) => ({\n id: ring.id,\n x: ring.x,\n y: ring.y,\n kind: \"plus\",\n pickRadius: Math.max(ring.outer.rx, ring.outer.ry),\n label: ring.label ?? String(ring.id),\n }));\n}\n\n/**\n * The ellipses of the rings' two edges. The outer is `feature`, the inner `model` (a fitted\n * second edge), and the smaller inner one is told from the outer by size as well as by colour.\n *\n * @param rings - The rings.\n * @returns The outer ellipses, and the inner ones of the rings that have one.\n */\nexport function ringEllipses(rings: readonly TargetRing[]): { outer: EllipseSetItem[]; inner: EllipseSetItem[] } {\n const outer: EllipseSetItem[] = [];\n const inner: EllipseSetItem[] = [];\n for (const ring of rings) {\n outer.push({ id: ring.id, x: ring.x, y: ring.y, rx: ring.outer.rx, ry: ring.outer.ry, angle: ring.outer.angle, role: \"feature\" });\n if (ring.inner) {\n inner.push({ id: ring.id, x: ring.x, y: ring.y, rx: ring.inner.rx, ry: ring.inner.ry, angle: ring.inner.angle, role: \"model\" });\n }\n }\n return { outer, inner };\n}\n\n/** Opacity of a dot at confidence 0 and at confidence 1: a weak bit is visible, a sure one is solid. */\nconst BIT_OPACITY_MIN = 0.35;\n\n/**\n * The dots of the edge-bit layer: bit 1 is a solid `feature` circle, bit 0 a dashed `model`\n * one, and the opacity runs from 35 % at confidence 0 to 100 % at confidence 1.\n *\n * @param bits - The edge bits.\n * @returns One ellipse (a circle) per bit.\n */\nexport function edgeBitEllipses(bits: readonly TargetEdgeBit[]): EllipseSetItem[] {\n return bits.map((bit) => ({\n id: bit.id,\n x: bit.x,\n y: bit.y,\n rx: bit.radius,\n ry: bit.radius,\n role: bit.bit === 1 ? \"feature\" : \"model\",\n dashed: bit.bit === 0,\n opacity: BIT_OPACITY_MIN + (1 - BIT_OPACITY_MIN) * Math.min(1, Math.max(0, bit.confidence)),\n }));\n}\n\n/**\n * The ellipse of a 2×2 position covariance: `scale` standard deviations along each principal\n * axis.\n *\n * The semi-axes are `scale · √λ` for the matrix's two eigenvalues `λ₁ ≥ λ₂`, and `angle` is the\n * direction of the eigenvector of `λ₁` (radians, clockwise on screen, in `(-π/2, π/2]`). At\n * `scale = 1` this is the 1σ ellipse: the curve `dᵀ Σ⁻¹ d = 1`.\n *\n * @param cov - The covariance `[xx, xy, yy]`, image pixels squared.\n * @param scale - The gain applied to both semi-axes. Defaults to 1.\n * @returns The ellipse, or `null` when the matrix is not finite and positive definite, or the\n * scale is not a finite positive number: there is no ellipse to draw.\n */\nexport function covarianceEllipse(cov: readonly [xx: number, xy: number, yy: number], scale = 1): TargetEllipse | null {\n const [xx, xy, yy] = cov;\n if (!Number.isFinite(xx + xy + yy) || !(Number.isFinite(scale) && scale > 0)) return null;\n const det = xx * yy - xy * xy;\n // Positive definite: a positive diagonal and a positive determinant.\n if (!(xx > 0 && yy > 0 && det > 0)) return null;\n const mean = 0.5 * (xx + yy);\n const spread = Math.hypot(0.5 * (xx - yy), xy);\n const major = mean + spread;\n // λ₁λ₂ = det: the smaller eigenvalue from the product rather than from `mean - spread`.\n const minor = det / major;\n const half = 0.5 * Math.atan2(2 * xy, xx - yy);\n // `atan2(-0, x < 0)` is -π: keep the axis in (-π/2, π/2].\n const angle = half <= -Math.PI / 2 ? half + Math.PI : half;\n return { rx: scale * Math.sqrt(major), ry: scale * Math.sqrt(minor), angle };\n}\n\n/**\n * The ellipses of the uncertainty layer: each corner's position covariance as a 1σ ellipse,\n * both semi-axes multiplied by `scale`, centred on the corner and sharing its id, in the `model`\n * role. A corner with no covariance, or one that is not positive definite, has none.\n *\n * @param corners - The corners.\n * @param scale - The gain on the semi-axes. A detector's σ is a fraction of a pixel, so it is\n * drawn magnified; print the gain beside the image (\"ellipses ×40\").\n * @returns One ellipse per corner with a drawable covariance, in order.\n */\nexport function uncertaintyEllipses(corners: readonly TargetCorner[], scale: number): EllipseSetItem[] {\n const out: EllipseSetItem[] = [];\n for (const corner of corners) {\n if (!corner.cov) continue;\n const ellipse = covarianceEllipse(corner.cov, scale);\n if (ellipse) out.push({ id: corner.id, x: corner.x, y: corner.y, ...ellipse, role: \"model\" });\n }\n return out;\n}\n","/**\n * A calibration-target detection over the image: one component for a chessboard, ChArUco,\n * marker board, PuzzleBoard, ring grid or a loose set of corners.\n *\n * It replaces the per-board overlays of vitavision (`ChessboardOverlay`, `CharucoOverlay`,\n * `MarkerboardOverlay`, `PuzzleboardOverlay`) and the glyph components behind them. Each part of\n * a `TargetDetection` goes to the stage2d layer that fits it, so a detection of thousands of\n * items is a few dozen DOM nodes and the pointer is resolved by the stage's hit-test\n * registry, not the DOM:\n *\n * | Part | Layer | Glyph |\n * |---|---|---|\n * | `corners` | `GridLayer` | plus; edge directions when `angle` is set; lattice edges and `i,j` labels |\n * | `markers` | `AreaSet` | quad outline and 12 % fill, corner 0 ticked, id inside |\n * | `circles` | `PointSet` | ring; a centre dot marks black |\n * | `rings` | `PointSet` + `EllipseSet` | fitted outer and inner ellipse, plus at the centre |\n * | `edgeBits` | `EllipseSet` | dot on the edge: solid for 1, dashed for 0, opacity from confidence |\n * | corners' `cov` | `EllipseSet` | with `uncertainty`: the 1σ ellipse × the scale, in `model` |\n */\n\nimport { EllipseSet, GridLayer, AreaSet, PointSet, type StagePointerEvent } from \"@vitavision/stage2d\";\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\nimport { TARGET_MARKERS } from \"./glyphs\";\nimport { circlePoints, cornerNodes, edgeBitEllipses, markerAreas, ringCentres, ringEllipses, uncertaintyEllipses } from \"./layerItems\";\nimport type { TargetDetection, TargetHit, TargetId, TargetPart } from \"./model\";\n\n/** Props of `TargetOverlay`. */\nexport interface TargetOverlayProps {\n /** The detection to draw. Pass a stable object: a new one rebuilds every layer's index. */\n detection: TargetDetection;\n /** Draw the lattice edges between neighbouring corners, one dashed axis and one solid. On by default. */\n showEdges?: boolean | undefined;\n /** Show labels (lattice indices, marker ids, ring ids) where the zoom leaves room for them. On by default. */\n showLabels?: boolean | undefined;\n /**\n * The hovered id, when the app controls hover (a list beside the stage hovers items too). It\n * applies to every part that has the id; keep ids unique within a detection.\n */\n hoveredId?: TargetId | null | undefined;\n /** The selected ids, drawn at 2.5 px in the selection colour; points get a ring. */\n selectedIds?: Iterable<TargetId> | undefined;\n /**\n * Called when the item under the pointer changes, once per change; `null` when it leaves every\n * item. The `id` is the one given in the detection, so the app maps it back to its feature.\n */\n onHoverChange?: ((hit: TargetHit | null) => void) | undefined;\n /**\n * A press landed on an item. Setting it makes the layers claim presses on their items, so the\n * stage does not pan from them. A mounted `StageSurface` hears a press first; there, ask\n * `useStageHitTest` what is under it instead.\n */\n onItemPress?: ((hit: TargetHit, event: StagePointerEvent) => void) | undefined;\n /**\n * Dim the whole overlay (`true`), or the listed ids, or those a predicate accepts, to 35 %\n * opacity. They still take hover and presses. Pass a stable value: a new one re-batches.\n */\n dimmed?: boolean | Iterable<TargetId> | ((id: TargetId) => boolean) | undefined;\n /**\n * Draw each corner's position covariance (`cov`) as its 1σ ellipse with both semi-axes\n * multiplied by `scale`, in the `model` role, under the corners. Off by default.\n *\n * A detector's σ is a small fraction of a pixel, so the ellipses are drawn magnified: the\n * `scale` is the app's to choose and to print beside the image (\"ellipses ×40\"), as a\n * residual's gain is. Their shape and orientation are the data's. A corner with no covariance,\n * or one that is not positive definite, gets none. The ellipses take the corner's hover,\n * selection and dimming, and are not picked themselves.\n */\n uncertainty?: { scale: number } | undefined;\n /** Prefix of the hit-test layer ids (`<prefix>-corners`, `-markers`, `-circles`, `-rings`). Defaults to generated ids. */\n layerIdPrefix?: string | undefined;\n}\n\n/** The ids of each part, to route a hovered or selected id to the layers that have it. */\nfunction idsByPart(detection: TargetDetection): Record<TargetPart, ReadonlySet<TargetId>> {\n const ids = (items: readonly { id: TargetId }[] | undefined) => new Set((items ?? []).map((item) => item.id));\n return {\n corner: ids(detection.corners),\n marker: ids(detection.markers),\n circle: ids(detection.circles),\n ring: ids(detection.rings),\n };\n}\n\n/** The `dimmed` prop as the predicate the layers take, or `undefined` for none. */\nfunction dimPredicate(dimmed: TargetOverlayProps[\"dimmed\"]): ((id: TargetId) => boolean) | undefined {\n if (dimmed === undefined || dimmed === false) return undefined;\n if (dimmed === true) return () => true;\n if (typeof dimmed === \"function\") return dimmed;\n const set = new Set(dimmed);\n return (id) => set.has(id);\n}\n\n/**\n * A detected calibration target inside an `ImageStage`.\n *\n * - **Batched**: one path per appearance in each layer, picking through spatial indices. Labels\n * appear only where items are 24 screen px apart, at most 200 at a time.\n * - **States**: hover 2 px, selected 2.5 px in the selection colour with a ring, dimmed at 35 %.\n * - **Colour**: roles only (`feature`, `model`, `structure`, `selection`). Scores are never drawn\n * as red, amber or green; polarity and bits are carried by shape (hollow or dotted, solid or\n * dashed), not by hue.\n * - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move\n * between layers (a corner, then the marker under it) without a flicker: the change is reported\n * once.\n * - **Uncertainty** (opt-in, `uncertainty`): each corner's covariance as a 1σ ellipse × the\n * given scale, under the corners.\n *\n * The layers it renders carry their own accessible names (\"Corners: 54 points, 0 selected\").\n */\nexport function TargetOverlay({\n detection,\n showEdges = true,\n showLabels = true,\n hoveredId,\n selectedIds,\n onHoverChange,\n onItemPress,\n dimmed,\n uncertainty,\n layerIdPrefix,\n}: TargetOverlayProps) {\n const nodes = useMemo(() => cornerNodes(detection), [detection]);\n const areas = useMemo(() => markerAreas(detection), [detection]);\n const circles = useMemo(() => circlePoints(detection), [detection]);\n const rings = detection.rings;\n const ringPoints = useMemo(() => ringCentres(rings ?? []), [rings]);\n const ringShapes = useMemo(() => ringEllipses(rings ?? []), [rings]);\n const bits = useMemo(() => edgeBitEllipses(detection.edgeBits ?? []), [detection.edgeBits]);\n const uncertaintyScale = uncertainty?.scale;\n const covEllipses = useMemo(\n () => (uncertaintyScale === undefined ? [] : uncertaintyEllipses(detection.corners ?? [], uncertaintyScale)),\n [detection.corners, uncertaintyScale],\n );\n const ids = useMemo(() => idsByPart(detection), [detection]);\n\n // Selection and hover are by id; each layer is given the ids it owns, so its count is right.\n const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);\n const selected = useMemo(() => {\n const pick = (part: TargetPart) => new Set([...selectedSet].filter((id) => ids[part].has(id)));\n return { corner: pick(\"corner\"), marker: pick(\"marker\"), circle: pick(\"circle\"), ring: pick(\"ring\") };\n }, [selectedSet, ids]);\n const isDimmed = useMemo(() => dimPredicate(dimmed), [dimmed]);\n\n // Hover. The layers report separately, so moving from a corner to the marker under it is\n // `corner → null` then `marker → id` in one event. The net result is read when the event is\n // done, and reported once.\n const [ownHover, setOwnHover] = useState<TargetHit | null>(null);\n const hoverRef = useRef<TargetHit | null>(null);\n const reportedRef = useRef<TargetHit | null>(null);\n const scheduledRef = useRef(false);\n const onHoverChangeRef = useRef(onHoverChange);\n useLayoutEffect(() => {\n onHoverChangeRef.current = onHoverChange;\n });\n const hoverFrom = useCallback(\n (part: TargetPart) => (id: TargetId | null) => {\n if (id !== null) hoverRef.current = { id, part };\n else if (hoverRef.current?.part === part) hoverRef.current = null;\n setOwnHover(hoverRef.current);\n if (scheduledRef.current) return;\n scheduledRef.current = true;\n queueMicrotask(() => {\n scheduledRef.current = false;\n const now = hoverRef.current;\n const before = reportedRef.current;\n if (now?.id === before?.id && now?.part === before?.part) return;\n reportedRef.current = now;\n onHoverChangeRef.current?.(now);\n });\n },\n [],\n );\n const hoverOf = (part: TargetPart): TargetId | null => {\n if (hoveredId !== undefined) return hoveredId !== null && ids[part].has(hoveredId) ? hoveredId : null;\n return ownHover?.part === part ? ownHover.id : null;\n };\n\n const pressFrom = (part: TargetPart) =>\n onItemPress ? (id: TargetId, event: StagePointerEvent) => onItemPress({ id, part }, event) : undefined;\n const layerId = (name: string) => (layerIdPrefix === undefined ? undefined : `${layerIdPrefix}-${name}`);\n\n const hasCorners = nodes.length > 0;\n const hasMarkers = areas.length > 0;\n const hasCircles = circles.length > 0;\n const hasRings = ringPoints.length > 0;\n const edgeStyle = { visible: showEdges };\n\n return (\n <>\n {hasMarkers && (\n <AreaSet\n items={areas}\n firstVertexTick\n labels={showLabels}\n hoveredId={hoverOf(\"marker\")}\n selectedIds={selected.marker}\n dimmed={isDimmed}\n onHoverChange={hoverFrom(\"marker\")}\n onItemPress={pressFrom(\"marker\")}\n layerId={layerId(\"markers\")}\n label=\"Markers\"\n />\n )}\n {bits.length > 0 && <EllipseSet items={bits} minRadius={3} dimmed={isDimmed} pickable={false} />}\n {hasRings && (\n <>\n <EllipseSet items={ringShapes.outer} hoveredId={hoverOf(\"ring\")} selectedIds={selected.ring} dimmed={isDimmed} pickable={false} />\n {ringShapes.inner.length > 0 && (\n <EllipseSet\n items={ringShapes.inner}\n role=\"model\"\n hoveredId={hoverOf(\"ring\")}\n selectedIds={selected.ring}\n dimmed={isDimmed}\n pickable={false}\n />\n )}\n <PointSet\n items={ringPoints}\n kind=\"plus\"\n markers={TARGET_MARKERS}\n labels={showLabels}\n hoveredId={hoverOf(\"ring\")}\n selectedIds={selected.ring}\n dimmed={isDimmed}\n onHoverChange={hoverFrom(\"ring\")}\n onItemPress={pressFrom(\"ring\")}\n layerId={layerId(\"rings\")}\n label=\"Rings\"\n />\n </>\n )}\n {covEllipses.length > 0 && (\n <EllipseSet\n items={covEllipses}\n role=\"model\"\n hoveredId={hoverOf(\"corner\")}\n selectedIds={selected.corner}\n dimmed={isDimmed}\n pickable={false}\n label={`Position uncertainty: 1σ ellipses ×${uncertaintyScale}`}\n />\n )}\n {hasCorners && (\n <GridLayer\n nodes={nodes}\n markers={TARGET_MARKERS}\n edges={{ i: edgeStyle, j: { ...edgeStyle, dashed: true } }}\n labels={showLabels}\n hoveredId={hoverOf(\"corner\")}\n selectedIds={selected.corner}\n dimmed={isDimmed}\n onHoverChange={hoverFrom(\"corner\")}\n onItemPress={pressFrom(\"corner\")}\n layerId={layerId(\"corners\")}\n label=\"Corners\"\n />\n )}\n {hasCircles && (\n <PointSet\n items={circles}\n markers={TARGET_MARKERS}\n labels={showLabels}\n hoveredId={hoverOf(\"circle\")}\n selectedIds={selected.circle}\n dimmed={isDimmed}\n onHoverChange={hoverFrom(\"circle\")}\n onItemPress={pressFrom(\"circle\")}\n layerId={layerId(\"circles\")}\n label=\"Circles\"\n />\n )}\n </>\n );\n}\n","/**\n * PuzzleBoard edge bits: from a decoder's observed edges to the dots the overlay draws.\n *\n * A PuzzleBoard encodes its position in the bumps along the edges between corners. The decoder\n * reports each observed edge in the image's own local frame (`row`, `col`), and the alignment\n * that maps that frame into the board's master frame, which is periodic with period 501. The\n * corners are labelled with master indices, so an edge's two corners are found by mapping its\n * local end points through the alignment, modulo the period. This is the arithmetic of\n * vitavision's `PuzzleboardOverlay.buildEdgeMarkers`, as a pure function over structural types,\n * so no detector package is imported.\n *\n * Pure: no React, no DOM.\n */\n\nimport { gridKey } from \"./lattice\";\nimport type { TargetCorner, TargetEdgeBit } from \"./model\";\n\n/** The period of the PuzzleBoard master pattern. */\nexport const PUZZLEBOARD_PERIOD = 501;\n\n/** One observed edge of a PuzzleBoard decode. */\nexport interface PuzzleboardEdge {\n /** Row of the edge's first corner, in the image's local frame. */\n row: number;\n /** Column of the edge's first corner, in the image's local frame. */\n col: number;\n /** `\"horizontal\"` joins local `(col, row)` to `(col + 1, row)`; `\"vertical\"` to `(col, row + 1)`. */\n orientation: \"horizontal\" | \"vertical\";\n /** The decoded bit. */\n bit: 0 | 1;\n /** Decode confidence, [0, 1]. */\n confidence: number;\n}\n\n/** The map from the local frame to master indices: `master = M · local + translation`, modulo the period. */\nexport interface PuzzleboardAlignment {\n /** The 2×2 integer matrix `[[a, b], [c, d]]`, acting on local `(i, j)`. */\n transform: { a: number; b: number; c: number; d: number };\n /** The translation, added after the matrix. */\n translation: readonly [number, number];\n}\n\n/** `value` modulo `period`, in `[0, period)` for any sign. */\nfunction wrap(value: number, period: number): number {\n return ((value % period) + period) % period;\n}\n\n/**\n * The edge bits of a PuzzleBoard decode, placed on the image.\n *\n * An edge is dropped when either of its corners was not detected. Each dot sits at the midpoint\n * of its edge with a radius of a quarter of the edge's length (the bump is about half an edge\n * wide); its opacity is the app's to take from `confidence`.\n *\n * @param edges - The observed edges.\n * @param corners - The labelled corners, whose `i` and `j` are **master** indices.\n * @param alignment - The local-to-master map.\n * @param period - The master pattern's period. Defaults to 501.\n * @returns One `TargetEdgeBit` per edge whose corners were both found, in input order. Empty when there is no alignment.\n */\nexport function edgeBitsFromPuzzleboard(\n edges: readonly PuzzleboardEdge[],\n corners: readonly TargetCorner[],\n alignment: PuzzleboardAlignment | null | undefined,\n period: number = PUZZLEBOARD_PERIOD,\n): TargetEdgeBit[] {\n if (!alignment || edges.length === 0 || corners.length === 0) return [];\n\n const byMaster = new Map<string, TargetCorner>();\n for (const corner of corners) {\n if (Number.isInteger(corner.i) && Number.isInteger(corner.j)) byMaster.set(gridKey(corner.i!, corner.j!), corner);\n }\n const { a, b, c, d } = alignment.transform;\n const [tx, ty] = alignment.translation;\n const toMaster = (i: number, j: number): string => gridKey(wrap(a * i + b * j + tx, period), wrap(c * i + d * j + ty, period));\n\n const out: TargetEdgeBit[] = [];\n edges.forEach((edge, index) => {\n // Local coordinates are (i = col, j = row).\n const from = byMaster.get(toMaster(edge.col, edge.row));\n const to = byMaster.get(edge.orientation === \"horizontal\" ? toMaster(edge.col + 1, edge.row) : toMaster(edge.col, edge.row + 1));\n if (!from || !to) return;\n out.push({\n id: `${edge.orientation}-${edge.row}-${edge.col}-${index}`,\n x: 0.5 * (from.x + to.x),\n y: 0.5 * (from.y + to.y),\n radius: 0.25 * Math.hypot(to.x - from.x, to.y - from.y),\n bit: edge.bit,\n confidence: Math.min(1, Math.max(0, edge.confidence)),\n });\n });\n return out;\n}\n","/**\n * calib-targets results to `TargetDetection`: the one mapping from what the\n * `@vitavision/calib-targets` WASM detectors return to what `TargetOverlay` draws.\n *\n * The input types below are the minimal structure the mapping reads, written to be satisfied by\n * the package's own result types (`ChessboardDetection`, `CharucoDetection`,\n * `MarkerBoardDetection`, `PuzzleBoardDetection`, `Corner`, and the `diagnose_*` payloads), so this\n * package takes no dependency on it. Every field the mapping does not read is ignored, and every\n * field a newer calib-targets adds is optional here, so results with and without it both fit.\n *\n * Pure: no React, no DOM.\n */\n\nimport type { TargetCircle, TargetCorner, TargetDetection, TargetKind, TargetMarker } from \"./model\";\nimport { edgeBitsFromPuzzleboard, type PuzzleboardEdge } from \"./puzzleboard\";\n\n/** An image point `[x, y]`, pixels with the centre of pixel `i` at `i` (calib-targets' `Point2`). */\nexport type CalibTargetsPoint = readonly [x: number, y: number];\n\n/** A position covariance, image pixels squared (calib-targets' `position_covariance`). */\nexport interface CalibTargetsCovariance {\n /** Variance along x. */\n xx: number;\n /** Covariance of x and y. */\n xy: number;\n /** Variance along y. */\n yy: number;\n}\n\n/** An integer lattice coordinate (calib-targets' `Coord`): `u` along the first board axis, `v` the second. */\nexport interface CalibTargetsCoord {\n /** First axis, rightwards on the board. */\n u: number;\n /** Second axis, downwards on the board. */\n v: number;\n}\n\n/** A labelled board corner: what `ChessboardCorner`, `CharucoCorner`, `MarkerBoardCorner` and `PuzzleBoardCorner` share. */\nexport interface CalibTargetsLabeledCorner {\n /** Sub-pixel image position. */\n position: CalibTargetsPoint;\n /** Lattice label; `null` for a corner with no place on the board. */\n grid: CalibTargetsCoord | null;\n /** The detector's score, higher is better. */\n score: number;\n /** Position covariance, when the detector reports one. */\n position_covariance?: CalibTargetsCovariance | null | undefined;\n}\n\n/** One axis estimate of a raw corner (calib-targets' `AxisEstimate`). */\nexport interface CalibTargetsAxis {\n /** Direction of the axis, radians in the image frame (clockwise on screen). */\n angle: number;\n}\n\n/** A raw ChESS corner, as `detect_corners` returns it (calib-targets' `Corner`). */\nexport interface CalibTargetsCorner {\n /** Sub-pixel image position. */\n position: CalibTargetsPoint;\n /** The two grid axes through the corner. */\n axes: readonly [CalibTargetsAxis, CalibTargetsAxis];\n /** Corner response, higher is stronger. */\n strength: number;\n /** Position covariance, when the detector reports one. */\n position_covariance?: CalibTargetsCovariance | null | undefined;\n}\n\n/** A chessboard detection (`ChessboardDetection`). */\nexport interface CalibTargetsChessboardDetection {\n /** The labelled corners. */\n corners: readonly CalibTargetsLabeledCorner[];\n}\n\n/** A decoded ArUco marker of a ChArUco detection (`MarkerDetection`). */\nexport interface CalibTargetsMarker {\n /** The marker's dictionary id. */\n id: number;\n /** Its four corners in the image, in the marker's own order; `null` when they were not projected. */\n corners_img: readonly [CalibTargetsPoint, CalibTargetsPoint, CalibTargetsPoint, CalibTargetsPoint] | null;\n}\n\n/** A ChArUco detection (`CharucoDetection`). */\nexport interface CalibTargetsCharucoDetection {\n /** The labelled corners. */\n corners: readonly CalibTargetsLabeledCorner[];\n /** The markers consistent with the board alignment. */\n markers: readonly CalibTargetsMarker[];\n}\n\n/** A checkerboard marker board detection (`MarkerBoardDetection`). */\nexport interface CalibTargetsMarkerBoardDetection {\n /** The labelled corners. */\n corners: readonly CalibTargetsLabeledCorner[];\n}\n\n/** A scored circle hypothesis of a marker board (`CircleCandidate`). */\nexport interface CalibTargetsCircleCandidate {\n /** Centre of the circle in the image. */\n center_img: CalibTargetsPoint;\n}\n\n/** A board circle paired with a detected one (`CircleMatch`). */\nexport interface CalibTargetsCircleMatch {\n /** The circle the board layout expects: its cell and printed polarity. */\n expected: { cell: { i: number; j: number }; polarity: \"white\" | \"black\" };\n /** Index into `circle_candidates` of the circle that matched it, or `null` for none. */\n matched_index: number | null;\n}\n\n/** The part of `diagnose_marker_board`'s `diagnostics` the overlay draws (`MarkerBoardDiagnostics`). */\nexport interface CalibTargetsMarkerBoardDiagnostics {\n /** The circle hypotheses. */\n circle_candidates: readonly CalibTargetsCircleCandidate[];\n /** The board's circles and the candidates they matched. */\n circle_matches: readonly CalibTargetsCircleMatch[];\n}\n\n/** A grid alignment (`GridAlignment`): `master = matrix · local + translation`. */\nexport interface CalibTargetsAlignment {\n /** Row-major integer matrix, applied to local `(u, v)` before the translation. */\n matrix: readonly [readonly [number, number], readonly [number, number]];\n /** Integer translation, grid units. */\n translation: readonly [number, number];\n}\n\n/** A PuzzleBoard detection (`PuzzleBoardDetection`); its corners carry master labels. */\nexport interface CalibTargetsPuzzleBoardDetection {\n /** The labelled corners, `grid` in the master frame. */\n corners: readonly CalibTargetsLabeledCorner[];\n /** The map from the decoder's local frame to the master frame. */\n alignment: CalibTargetsAlignment;\n}\n\n/** One observed edge bit, in the decoder's local frame (`PuzzleBoardObservedEdge`). */\nexport interface CalibTargetsObservedEdge {\n /** Row of the edge's first corner. */\n row: number;\n /** Column of the edge's first corner. */\n col: number;\n /** Which neighbour the edge runs to. */\n orientation: \"horizontal\" | \"vertical\";\n /** The observed bit, 0 or 1. */\n bit: number;\n /** Per-bit confidence, [0, 1]. */\n confidence: number;\n}\n\n/** The part of `diagnose_puzzleboard`'s `diagnostics` the overlay draws (`PuzzleBoardDiagnostics`). */\nexport interface CalibTargetsPuzzleBoardDiagnostics {\n /** Every sampled edge, before alignment. */\n observed_edges: readonly CalibTargetsObservedEdge[];\n}\n\n/** A PuzzlePole detection: a PuzzleBoard wrapped round a cylinder; `grid` is (axial, around). */\nexport interface CalibTargetsPuzzlePoleDetection {\n /** The labelled corners. */\n corners: readonly CalibTargetsLabeledCorner[];\n}\n\n/**\n * One calib-targets result, tagged with the detector that produced it.\n *\n * A board detector returns `null` (or, from `diagnose_*`, `undefined`) when it finds nothing;\n * pass that through as `detection` and the result is an empty detection of the same kind.\n * `diagnostics` is the `diagnostics` of the matching `diagnose_*` call: it carries what the plain\n * result does not (the marker-board circles, the PuzzleBoard edge bits). Convert a `diagnose_*`\n * payload to plain objects first if your binding returns `Map`s.\n */\nexport type CalibTargetsResult =\n | {\n /** Raw ChESS corners, from `detect_corners`. */\n kind: \"corners\";\n /** The corners. */\n corners: readonly CalibTargetsCorner[];\n }\n | {\n /** A chessboard, from `detect_chessboard`. */\n kind: \"chessboard\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsChessboardDetection | null | undefined;\n }\n | {\n /** A ChArUco board, from `detect_charuco` or `diagnose_charuco`. */\n kind: \"charuco\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsCharucoDetection | null | undefined;\n }\n | {\n /** A checkerboard marker board, from `detect_marker_board` or `diagnose_marker_board`. */\n kind: \"markerboard\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsMarkerBoardDetection | null | undefined;\n /** `diagnose_marker_board`'s diagnostics, for the matched circles. */\n diagnostics?: CalibTargetsMarkerBoardDiagnostics | null | undefined;\n }\n | {\n /** A PuzzleBoard, from `detect_puzzleboard` or `diagnose_puzzleboard`. */\n kind: \"puzzleboard\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsPuzzleBoardDetection | null | undefined;\n /** `diagnose_puzzleboard`'s diagnostics, for the edge bits. */\n diagnostics?: CalibTargetsPuzzleBoardDiagnostics | null | undefined;\n }\n | {\n /** A PuzzlePole. Drawn as a PuzzleBoard lattice, without edge bits. */\n kind: \"puzzlepole\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsPuzzlePoleDetection | null | undefined;\n };\n\n/** The overlay kind of each calib-targets result kind. */\nconst OVERLAY_KIND: Readonly<Record<CalibTargetsResult[\"kind\"], TargetKind>> = {\n corners: \"corners\",\n chessboard: \"chessboard\",\n charuco: \"charuco\",\n markerboard: \"markerboard\",\n puzzleboard: \"puzzleboard\",\n puzzlepole: \"puzzleboard\",\n};\n\n/** A covariance as `TargetCorner.cov`, or `undefined` when there is none or it is not finite. */\nfunction covOf(cov: CalibTargetsCovariance | null | undefined): TargetCorner[\"cov\"] {\n if (!cov) return undefined;\n const { xx, xy, yy } = cov;\n return Number.isFinite(xx + xy + yy) ? [xx, xy, yy] : undefined;\n}\n\n/** A labelled corner as a `TargetCorner`, id `corner-<index>`; `(u, v)` becomes `(i, j)`. */\nfunction labeledCorner(corner: CalibTargetsLabeledCorner, index: number): TargetCorner {\n const out: TargetCorner = { id: `corner-${index}`, x: corner.position[0], y: corner.position[1], score: corner.score };\n if (corner.grid) {\n out.i = corner.grid.u;\n out.j = corner.grid.v;\n }\n const cov = covOf(corner.position_covariance);\n if (cov) out.cov = cov;\n return out;\n}\n\n/** A raw corner as a `TargetCorner` with both axis directions, id `corner-<index>`, labelled with its index. */\nfunction rawCorner(corner: CalibTargetsCorner, index: number): TargetCorner {\n const out: TargetCorner = {\n id: `corner-${index}`,\n x: corner.position[0],\n y: corner.position[1],\n score: corner.strength,\n angle: corner.axes[0].angle,\n angle2: corner.axes[1].angle,\n label: String(index),\n };\n const cov = covOf(corner.position_covariance);\n if (cov) out.cov = cov;\n return out;\n}\n\n/** The markers with a projected quad, id `marker-<index>`, labelled with the dictionary id. */\nfunction markersOf(markers: readonly CalibTargetsMarker[]): TargetMarker[] {\n const out: TargetMarker[] = [];\n markers.forEach((marker, index) => {\n if (!marker.corners_img) return;\n out.push({ id: `marker-${index}`, corners: marker.corners_img.flatMap(([x, y]) => [x, y]), label: String(marker.id) });\n });\n return out;\n}\n\n/**\n * The matched circles of a marker board, id `circle-<index>` (index into `circle_matches`): at\n * the matched candidate's centre, with the board's cell and printed polarity. An unmatched board\n * circle is not drawn, nor is a candidate no board circle matched.\n */\nfunction circlesOf(diagnostics: CalibTargetsMarkerBoardDiagnostics): TargetCircle[] {\n const out: TargetCircle[] = [];\n diagnostics.circle_matches.forEach((match, index) => {\n const candidate = match.matched_index === null ? undefined : diagnostics.circle_candidates[match.matched_index];\n if (!candidate) return;\n out.push({\n id: `circle-${index}`,\n x: candidate.center_img[0],\n y: candidate.center_img[1],\n polarity: match.expected.polarity,\n i: match.expected.cell.i,\n j: match.expected.cell.j,\n });\n });\n return out;\n}\n\n/** The observed edges as `edgeBitsFromPuzzleboard` takes them: a nonzero bit is 1. */\nfunction edgesOf(edges: readonly CalibTargetsObservedEdge[]): PuzzleboardEdge[] {\n return edges.map((edge) => ({\n row: edge.row,\n col: edge.col,\n orientation: edge.orientation,\n bit: edge.bit === 0 ? 0 : 1,\n confidence: edge.confidence,\n }));\n}\n\n/**\n * The `TargetDetection` of a calib-targets result.\n *\n * - **Kinds.** `chessboard`, `charuco`, `markerboard`, `puzzleboard` and raw `corners` map to the\n * overlay kind of the same name; a `puzzlepole` is drawn as a `puzzleboard` lattice.\n * - **Corners.** Positions pass through unchanged (calib-targets reports the centre of pixel `i`\n * at `i`, as the overlay expects). A labelled corner's grid `(u, v)` becomes `(i, j)`, so a\n * board draws its lattice and labels corners `i,j`. A raw corner draws its two axes (`angle`,\n * `angle2`) and is labelled with its index; its `strength` is the `score`.\n * - **Covariance.** A corner's `position_covariance`, when present and finite, becomes `cov`;\n * `TargetOverlay` draws it with `uncertainty`.\n * - **Markers** (ChArUco) are the quads of `corners_img`, labelled with the dictionary id; a\n * marker without a projected quad is left out.\n * - **Circles** (marker board, from `diagnostics`) are the board circles a candidate matched,\n * at the candidate's centre with the board's cell and polarity.\n * - **Edge bits** (PuzzleBoard, from `diagnostics`) are the observed edges placed through the\n * alignment with `edgeBitsFromPuzzleboard`.\n *\n * Ids are `corner-<n>`, `marker-<n>` and `circle-<n>`, where `n` is the index into the result's\n * `corners`, `markers` or `circle_matches`, so a hover or a press maps straight back to it.\n *\n * @param result - The result, tagged with its kind.\n * @returns The detection for `TargetOverlay`. Parts with no items are left out.\n */\nexport function fromCalibTargets(result: CalibTargetsResult): TargetDetection {\n const detection: TargetDetection = { kind: OVERLAY_KIND[result.kind] };\n\n if (result.kind === \"corners\") {\n if (result.corners.length > 0) detection.corners = result.corners.map(rawCorner);\n return detection;\n }\n if (!result.detection) return detection;\n\n const corners = result.detection.corners.map(labeledCorner);\n if (corners.length > 0) detection.corners = corners;\n\n switch (result.kind) {\n case \"charuco\": {\n const markers = markersOf(result.detection.markers);\n if (markers.length > 0) detection.markers = markers;\n break;\n }\n case \"markerboard\": {\n const circles = result.diagnostics ? circlesOf(result.diagnostics) : [];\n if (circles.length > 0) detection.circles = circles;\n break;\n }\n case \"puzzleboard\": {\n if (!result.diagnostics) break;\n const { matrix, translation } = result.detection.alignment;\n const alignment = {\n transform: { a: matrix[0][0], b: matrix[0][1], c: matrix[1][0], d: matrix[1][1] },\n translation: [translation[0], translation[1]] as const,\n };\n const edgeBits = edgeBitsFromPuzzleboard(edgesOf(result.diagnostics.observed_edges), corners, alignment);\n if (edgeBits.length > 0) detection.edgeBits = edgeBits;\n break;\n }\n default:\n break;\n }\n return detection;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAS,MAAM,OAAuB;CACpC,OAAO,KAAK,MAAM,QAAQ,GAAI,IAAI;AACpC;;AAGA,SAAS,UAAU,OAAuB;CACxC,MAAM,UAAU,QAAQ,KAAK;CAC7B,OAAO,UAAU,IAAI,UAAU,KAAK,KAAK;AAC3C;;AAGA,MAAM,aAAa;AACnB,MAAM,WAAW;;;;;;AAOjB,MAAM,WAAwB;CAC5B,OAAO;CACP,MAAM;CACN,OAAO,GAAG,GAAG,MAAM,OAAO,WAAW;EACnC,IAAI,IAAI;EACR,KAAK,MAAM,aAAa,WAAW,KAAA,IAAY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AAc,GAAG,SAAS,SAAS;GACvG,IAAI,SAAS,SAAS,GAAG,UAAU,WAAW;GAC9C;EACF;CAGF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["EllipseSet"],"sources":["../src/glyphs.ts","../src/lattice.ts","../src/model.ts","../src/layerItems.ts","../src/TargetOverlay.tsx","../src/puzzleboard.ts","../src/calibTargets.ts"],"sourcesContent":["/**\n * The glyphs of a calibration-target overlay, as path generators.\n *\n * A glyph is a `MarkerShape` for `@vitavision/stage2d`'s `PointSet`: a pure function from a\n * position to SVG path data, so a layer appends thousands of them into one `<path>`.\n * They are registered under the names in `TARGET_MARKERS`, which `TargetOverlay` passes as\n * `markers`. Sizes are screen pixels, from `unit` (image pixels per screen pixel).\n *\n * Pure: no React, no DOM.\n */\n\nimport { circlePath, type MarkerShape } from \"@vitavision/stage2d\";\n\n/** Round to 1/1000 of an image pixel. */\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n\n/** An angle as a direction of a line: modulo π, in [0, π). */\nfunction lineAngle(angle: number): number {\n const wrapped = angle % Math.PI;\n return wrapped < 0 ? wrapped + Math.PI : wrapped;\n}\n\n/** Half-length of a directed corner's axes, and the gap left at its centre, in screen pixels. */\nconst AXIS_REACH = 8;\nconst AXIS_GAP = 2;\n\n/**\n * A corner with its edge directions: one or two lines through the point, 8 px each way with a\n * 2 px gap at the centre, so the corner itself stays visible. Give it `angle` and, for the\n * second direction, `angle2`. Directions are lines, so each is read modulo π.\n */\nconst directed: MarkerShape = {\n paint: \"line\",\n size: AXIS_REACH,\n path: (x, y, unit, angle, angle2) => {\n let d = \"\";\n for (const direction of angle2 === undefined ? [angle] : [angle, angle2]) {\n if (!Number.isFinite(direction)) continue;\n const line = lineAngle(direction);\n const c = Math.cos(line);\n const s = Math.sin(line);\n const near = AXIS_GAP * unit;\n const far = AXIS_REACH * unit;\n d +=\n `M${round(x - far * c)} ${round(y - far * s)}L${round(x - near * c)} ${round(y - near * s)}` +\n `M${round(x + near * c)} ${round(y + near * s)}L${round(x + far * c)} ${round(y + far * s)}`;\n }\n return d;\n },\n};\n\n/** Radius of a matched circle's glyph, screen pixels. */\nconst CIRCLE_RADIUS = 5.5;\n/** Radius of the centre mark of a black circle, screen pixels; stroked, it reads as a filled dot. */\nconst CENTRE_RADIUS = 0.8;\n\n/** A white circle of a marker board: a hollow ring of radius 5.5 px. */\nconst circleWhite: MarkerShape = {\n paint: \"line\",\n size: CIRCLE_RADIUS,\n path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit),\n};\n\n/** A black circle: the same ring with a dot at its centre, so polarity is a shape and not a colour. */\nconst circleBlack: MarkerShape = {\n paint: \"line\",\n size: CIRCLE_RADIUS,\n path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit) + circlePath(x, y, CENTRE_RADIUS * unit),\n};\n\n/** Half-length of an excluded feature's strike-through cross, screen pixels. */\nconst EXCLUDED_REACH = 6;\n/** Radius of a flagged feature's ring, screen pixels: outside the selection ring (about 9 px). */\nconst FLAG_RADIUS = 12;\n\n/**\n * The strike-through of an excluded feature: a small diagonal cross, 6 px arms, over the dimmed\n * feature. Painted in the `label` role so it holds on the dimmed mark on a light or dark image,\n * and in no verdict colour: an excluded feature is switched off, not wrong.\n */\nconst excluded: MarkerShape = {\n paint: \"line\",\n size: EXCLUDED_REACH,\n role: \"label\",\n path: (x, y, unit) => {\n const a = EXCLUDED_REACH * unit;\n return `M${round(x - a)} ${round(y - a)}l${round(2 * a)} ${round(2 * a)}M${round(x - a)} ${round(y + a)}l${round(2 * a)} ${round(-2 * a)}`;\n },\n};\n\n/** The ring of a flagged feature: a thin circle of radius 12 px, in the `label` role. */\nconst flagged: MarkerShape = {\n paint: \"line\",\n size: FLAG_RADIUS,\n role: \"label\",\n path: (x, y, unit) => circlePath(x, y, FLAG_RADIUS * unit),\n};\n\n/** The marker names `TargetOverlay` uses, to pass to `PointSet`'s `markers`. */\nexport const TARGET_MARKERS = {\n /** Edge directions of a corner, from `angle` and `angle2`. */\n directed,\n /** A white matched circle. */\n \"circle-white\": circleWhite,\n /** A black matched circle. */\n \"circle-black\": circleBlack,\n /** The cross through an excluded feature. */\n excluded,\n /** The ring around a flagged feature. */\n flagged,\n} as const satisfies Readonly<Record<string, MarkerShape>>;\n","/**\n * The lattice of a detected board: which corner sits at which `(i, j)`, which corners are\n * neighbours, and the polygons of the markers.\n *\n * Ported from vitavision's `overlayData.ts` (`buildCornerGrid`, `buildGridEdges`,\n * `buildFeatureIdByGrid`, `buildMarkerPolygons`), where ChArUco, chessboard, marker board and\n * PuzzleBoard each carried a copy (PuzzleBoard's `buildPuzzleGrid` was a fourth). One\n * implementation now serves all four, on the normalised `TargetDetection` input.\n *\n * Pure: no React, no DOM.\n */\n\nimport { latticeEdges } from \"@vitavision/stage2d\";\n\nimport type { TargetCorner, TargetId, TargetMarker } from \"./model\";\n\n/** A corner that has a place on the board. */\nexport type GridCorner = TargetCorner & { i: number; j: number };\n\n/** The extent of a lattice, inclusive. */\nexport interface GridBounds {\n /** Smallest `i`. */\n minI: number;\n /** Largest `i`. */\n maxI: number;\n /** Smallest `j`. */\n minJ: number;\n /** Largest `j`. */\n maxJ: number;\n}\n\n/** The corners of a board, indexed by lattice position. */\nexport interface CornerGrid {\n /** The corners with an integer `(i, j)`, in input order. A repeated `(i, j)` keeps its first corner. */\n nodes: readonly GridCorner[];\n /** Position in `nodes` by `gridKey(i, j)`. */\n byIndex: ReadonlyMap<string, number>;\n /** Positions in `nodes` grouped by `i` (ascending), each group sorted by `j`. */\n rows: readonly (readonly number[])[];\n /** Positions in `nodes` grouped by `j` (ascending), each group sorted by `i`. */\n cols: readonly (readonly number[])[];\n /** The extent, or `null` for an empty grid. */\n bounds: GridBounds | null;\n}\n\n/** A segment between two neighbouring corners. */\nexport interface GridSegment {\n /** Id of the end with the lower index along the edge's axis. */\n a: TargetId;\n /** Id of the end with the higher index. */\n b: TargetId;\n /** Start x. */\n x1: number;\n /** Start y. */\n y1: number;\n /** End x. */\n x2: number;\n /** End y. */\n y2: number;\n}\n\n/** A marker as a closed polygon. */\nexport interface MarkerPolygon {\n /** The marker's id. */\n id: TargetId;\n /** Flat `[x0, y0, x1, y1, …]`; the last vertex joins the first. */\n points: number[];\n /** The mean of the vertices. */\n centre: { x: number; y: number };\n /** The marker's own label, if it has one. */\n label?: string | undefined;\n}\n\n/**\n * The key of a lattice position, as `idByGrid` and `CornerGrid.byIndex` use.\n *\n * @param i - Index along the first axis.\n * @param j - Index along the second axis.\n * @returns `\"i:j\"`.\n */\nexport function gridKey(i: number, j: number): string {\n return `${i}:${j}`;\n}\n\n/** Whether a corner carries an integer lattice index. */\nfunction isGridCorner(corner: TargetCorner): corner is GridCorner {\n return Number.isInteger(corner.i) && Number.isInteger(corner.j);\n}\n\n/**\n * Index a board's corners by lattice position.\n *\n * Corners without an integer `(i, j)` are not part of the grid. When two corners claim one\n * position the first wins, as it does in `latticeEdges`.\n *\n * @param corners - The detected corners, in any order, with gaps allowed.\n * @returns The grid.\n */\nexport function cornerGrid(corners: readonly TargetCorner[]): CornerGrid {\n const nodes: GridCorner[] = [];\n const byIndex = new Map<string, number>();\n const rowMap = new Map<number, number[]>();\n const colMap = new Map<number, number[]>();\n let bounds: GridBounds | null = null;\n\n for (const corner of corners) {\n if (!isGridCorner(corner)) continue;\n const key = gridKey(corner.i, corner.j);\n if (byIndex.has(key)) continue;\n const position = nodes.length;\n nodes.push(corner);\n byIndex.set(key, position);\n const row = rowMap.get(corner.i);\n if (row) row.push(position);\n else rowMap.set(corner.i, [position]);\n const col = colMap.get(corner.j);\n if (col) col.push(position);\n else colMap.set(corner.j, [position]);\n bounds = bounds\n ? {\n minI: Math.min(bounds.minI, corner.i),\n maxI: Math.max(bounds.maxI, corner.i),\n minJ: Math.min(bounds.minJ, corner.j),\n maxJ: Math.max(bounds.maxJ, corner.j),\n }\n : { minI: corner.i, maxI: corner.i, minJ: corner.j, maxJ: corner.j };\n }\n\n const ordered = (groups: Map<number, number[]>, by: \"i\" | \"j\") =>\n [...groups.entries()].sort(([a], [b]) => a - b).map(([, group]) => group.sort((p, q) => nodes[p]![by] - nodes[q]![by]));\n return { nodes, byIndex, rows: ordered(rowMap, \"j\"), cols: ordered(colMap, \"i\"), bounds };\n}\n\n/**\n * The edges between neighbouring corners of a grid: `(i, j)` to `(i, j + 1)` are the row edges,\n * `(i, j)` to `(i + 1, j)` the column edges. A missed corner leaves a gap, never a long edge.\n * It is `latticeEdges` from `@vitavision/stage2d` with positions attached.\n *\n * @param grid - From `cornerGrid`.\n * @returns The two edge lists.\n */\nexport function gridEdges(grid: CornerGrid): { rowEdges: GridSegment[]; colEdges: GridSegment[] } {\n const rowEdges: GridSegment[] = [];\n const colEdges: GridSegment[] = [];\n for (const edge of latticeEdges(grid.nodes)) {\n const a = grid.nodes[edge.a]!;\n const b = grid.nodes[edge.b]!;\n (edge.axis === \"j\" ? rowEdges : colEdges).push({ a: a.id, b: b.id, x1: a.x, y1: a.y, x2: b.x, y2: b.y });\n }\n return { rowEdges, colEdges };\n}\n\n/**\n * The id of the corner at each lattice position, to map a board cell back to an app's feature.\n *\n * @param corners - The detected corners.\n * @returns Ids by `gridKey(i, j)`. A corner without an integer index is left out; the first of two sharing a position wins.\n */\nexport function idByGrid(corners: readonly TargetCorner[]): Map<string, TargetId> {\n const map = new Map<string, TargetId>();\n for (const corner of corners) {\n if (!isGridCorner(corner)) continue;\n const key = gridKey(corner.i, corner.j);\n if (!map.has(key)) map.set(key, corner.id);\n }\n return map;\n}\n\n/**\n * The markers as polygons, with their centres.\n *\n * @param markers - The detected markers.\n * @returns A polygon per marker that has at least three finite vertices; the others are dropped.\n */\nexport function markerPolygons(markers: readonly TargetMarker[]): MarkerPolygon[] {\n const out: MarkerPolygon[] = [];\n for (const marker of markers) {\n const n = marker.corners.length;\n if (n < 6 || n % 2 !== 0 || !marker.corners.every(Number.isFinite)) continue;\n let sx = 0;\n let sy = 0;\n for (let k = 0; k < n; k += 2) {\n sx += marker.corners[k]!;\n sy += marker.corners[k + 1]!;\n }\n const polygon: MarkerPolygon = {\n id: marker.id,\n points: [...marker.corners],\n centre: { x: sx / (n / 2), y: sy / (n / 2) },\n };\n if (marker.label !== undefined) polygon.label = marker.label;\n out.push(polygon);\n }\n return out;\n}\n","/**\n * The input model: one detection run, independent of the library that produced it.\n *\n * Every detector in the vitavision family (calib-targets' chessboard, ChArUco, marker board and\n * PuzzleBoard, ringgrid, chess-corners) returns its own result shape. An app maps that shape to a\n * `TargetDetection` once (for calib-targets, `fromCalibTargets` is that mapping), and the overlay\n * never learns which library ran. Nothing here imports a detector package: these are plain data\n * types.\n *\n * Conventions, the same as `@vitavision/stage2d`:\n * - Positions are **image pixels, with the centre of pixel `i` at coordinate `i`** (the frame\n * the WASM detectors report, `image_px_center`). The stage places them; do not add 0.5.\n * - `y` points down. Angles are **radians, clockwise on screen** (from +x towards +y).\n * - Lengths named `rx`, `ry` and `radius` are image pixels, so they scale with the image.\n *\n * Pure: no React, no DOM.\n */\n\n/** An item's identity. Ids are unique within one detection, across corners, markers, circles and rings. */\nexport type TargetId = string | number;\n\n/** What a detection is of. It chooses defaults, not what is drawn: whatever is present is drawn. */\nexport type TargetKind = \"chessboard\" | \"charuco\" | \"markerboard\" | \"puzzleboard\" | \"ringgrid\" | \"corners\" | \"circles\";\n\n/** Every `TargetKind`. */\nexport const TARGET_KINDS: readonly TargetKind[] = [\n \"chessboard\",\n \"charuco\",\n \"markerboard\",\n \"puzzleboard\",\n \"ringgrid\",\n \"corners\",\n \"circles\",\n];\n\n/** The kinds whose corners form a lattice, so their neighbours are joined by edges. */\nconst LATTICE_KINDS: ReadonlySet<TargetKind> = new Set([\"chessboard\", \"charuco\", \"markerboard\", \"puzzleboard\"]);\n\n/**\n * Whether a detection of this kind draws lattice edges between corner neighbours.\n *\n * @param kind - The detection's kind.\n * @returns `true` for the four calibration boards, `false` for loose corners, circles and rings.\n */\nexport function isLatticeKind(kind: TargetKind): boolean {\n return LATTICE_KINDS.has(kind);\n}\n\n/** One detected corner or X-junction. */\nexport interface TargetCorner {\n /** Its identity. Callbacks report this id back. */\n id: TargetId;\n /** Horizontal position, image pixels. */\n x: number;\n /** Vertical position, image pixels. */\n y: number;\n /** Lattice index along the first board axis, an integer. Absent for a corner with no place on a board. */\n i?: number | undefined;\n /** Lattice index along the second board axis, an integer. */\n j?: number | undefined;\n /**\n * The detector's confidence. It is carried for the app (a list, a filter) and never drawn as a\n * colour: a score is not a verdict.\n */\n score?: number | undefined;\n /** Orientation of the first edge through the corner, radians. Axes are lines, so `angle` and `angle + π` are the same. */\n angle?: number | undefined;\n /** Orientation of the second edge through the corner, radians. Needs `angle`. */\n angle2?: number | undefined;\n /**\n * The covariance of the position, image pixels squared: the three distinct entries\n * `[xx, xy, yy]` of the symmetric 2×2 matrix. `TargetOverlay`'s `uncertainty` prop draws it as\n * a 1σ ellipse; a matrix that is not positive definite is not drawn.\n */\n cov?: readonly [xx: number, xy: number, yy: number] | undefined;\n /** Text beside it. Defaults to the lattice index `i,j` on a board, else the id. */\n label?: string | undefined;\n /**\n * The feature is excluded from use (left out of a fit, switched off by the person): it is\n * drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on\n * it, so it is not drawn like a rejected point. It still takes hover and presses.\n */\n excluded?: boolean | undefined;\n /**\n * The feature is flagged: a thin ring is drawn around it, for \"this feature disagrees with\n * what it should be\" (a decoded id that differs from the master pattern, say). It composes\n * with `excluded`, hover and selection.\n */\n flagged?: boolean | undefined;\n}\n\n/** One decoded fiducial marker (ArUco, AprilTag): a quad. */\nexport interface TargetMarker {\n /** Its identity. For an ArUco marker, usually its dictionary id. */\n id: TargetId;\n /**\n * The quad's corners in the marker's own order, `[x0, y0, x1, y1, x2, y2, x3, y3]`. Corner 0 is\n * ticked, so the order reads as the marker's orientation.\n */\n corners: readonly number[];\n /** Text drawn inside it. Defaults to the id. */\n label?: string | undefined;\n}\n\n/** The printed colour of a circle in a marker board. */\nexport type CirclePolarity = \"white\" | \"black\";\n\n/** One detected circle of a marker board, matched or not to the board model. */\nexport interface TargetCircle {\n /** Its identity. */\n id: TargetId;\n /** Centre x, image pixels. */\n x: number;\n /** Centre y, image pixels. */\n y: number;\n /** Printed polarity. It is drawn as a shape (hollow ring, or ring with a centre dot), not as a colour. */\n polarity: CirclePolarity;\n /** The board cell it matched, first axis. */\n i?: number | undefined;\n /** The board cell it matched, second axis. */\n j?: number | undefined;\n /** Text beside it. Defaults to `(i, j)` when both are set. */\n label?: string | undefined;\n /**\n * The feature is excluded from use (left out of a fit, switched off by the person): it is\n * drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on\n * it, so it is not drawn like a rejected point. It still takes hover and presses.\n */\n excluded?: boolean | undefined;\n /**\n * The feature is flagged: a thin ring is drawn around it, for \"this feature disagrees with\n * what it should be\" (a decoded id that differs from the master pattern, say). It composes\n * with `excluded`, hover and selection.\n */\n flagged?: boolean | undefined;\n}\n\n/** A fitted ellipse. */\nexport interface TargetEllipse {\n /** Semi-axis along the rotated x axis, image pixels. */\n rx: number;\n /** Semi-axis along the rotated y axis, image pixels. */\n ry: number;\n /** Rotation of the `rx` axis, radians clockwise on screen. */\n angle: number;\n}\n\n/** One ring marker of a ring grid: two concentric fitted ellipses and a centre. */\nexport interface TargetRing {\n /** Its identity. */\n id: TargetId;\n /** Centre x, image pixels. */\n x: number;\n /** Centre y, image pixels. */\n y: number;\n /** The outer edge of the ring. */\n outer: TargetEllipse;\n /** The inner edge of the ring, when the detector fitted one. */\n inner?: TargetEllipse | undefined;\n /** Text beside the centre. Defaults to the id. */\n label?: string | undefined;\n /**\n * The ring is excluded from use (left out of a fit, switched off by the person): it is\n * drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on\n * it, so it is not drawn like a rejected point. It still takes hover and presses.\n */\n excluded?: boolean | undefined;\n /**\n * The ring is flagged: a thin ring is drawn around its centre, for \"this feature disagrees with\n * what it should be\" (a decoded id that differs from the master pattern, say). It composes\n * with `excluded`, hover and selection.\n */\n flagged?: boolean | undefined;\n}\n\n/**\n * One decoded bit of a PuzzleBoard, drawn as a dot on the edge between two corners.\n * `edgeBitsFromPuzzleboard` builds these from a PuzzleBoard result.\n */\nexport interface TargetEdgeBit {\n /** Its identity. Not reported by callbacks: edge bits are not picked. */\n id: TargetId;\n /** Midpoint x of the edge, image pixels. */\n x: number;\n /** Midpoint y of the edge, image pixels. */\n y: number;\n /** The dot's radius, image pixels: about a quarter of the edge. */\n radius: number;\n /** The decoded bit. 1 is a solid dot, 0 a dashed one. */\n bit: 0 | 1;\n /** Decode confidence in [0, 1]. It sets the dot's opacity. */\n confidence: number;\n}\n\n/** One detection run: what a detector found in one image. */\nexport interface TargetDetection {\n /** What was detected. */\n kind: TargetKind;\n /** Corners and X-junctions. */\n corners?: readonly TargetCorner[] | undefined;\n /** Decoded fiducial markers. */\n markers?: readonly TargetMarker[] | undefined;\n /** Marker-board circles. */\n circles?: readonly TargetCircle[] | undefined;\n /** Ring markers. */\n rings?: readonly TargetRing[] | undefined;\n /** PuzzleBoard edge bits. */\n edgeBits?: readonly TargetEdgeBit[] | undefined;\n}\n\n/** The part of a detection an item belongs to. */\nexport type TargetPart = \"corner\" | \"marker\" | \"circle\" | \"ring\";\n\n/** Which item the pointer is on. */\nexport interface TargetHit {\n /** The item's id, as given in the detection. */\n id: TargetId;\n /** The collection it came from. */\n part: TargetPart;\n}\n","/**\n * What each stage2d layer is given, for each part of a detection: the pure mapping from the\n * normalised `TargetDetection` to the items of `GridLayer`, `AreaSet`, `PointSet` and\n * `EllipseSet`. `TargetOverlay` is these plus the wiring, so this is where the overlay's\n * decisions are, and where they are tested without a DOM.\n *\n * Pure: no React, no DOM.\n */\n\nimport type { AreaSetItem, EllipseSetItem, GridNode, PointSetItem } from \"@vitavision/stage2d\";\n\nimport { markerPolygons } from \"./lattice\";\nimport {\n isLatticeKind,\n type TargetCircle,\n type TargetCorner,\n type TargetDetection,\n type TargetEdgeBit,\n type TargetEllipse,\n type TargetId,\n type TargetRing,\n} from \"./model\";\n\n/** The label of a corner: its own, else the lattice index on a board, else the id. */\nfunction cornerLabel(corner: TargetCorner, lattice: boolean): string {\n if (corner.label !== undefined) return corner.label;\n if (lattice && Number.isInteger(corner.i) && Number.isInteger(corner.j)) return `${corner.i},${corner.j}`;\n return String(corner.id);\n}\n\n/**\n * The nodes of the corner layer.\n *\n * A corner with an `angle` is a `directed` marker (its edge directions, one or two), any other a\n * `plus`. On a board kind the lattice indices are kept, so `GridLayer` joins neighbours; on any\n * other kind they are `NaN`, which `latticeEdges` reads as \"not part of a lattice\", so no edge is\n * drawn.\n *\n * @param detection - The detection.\n * @returns One node per corner, in order.\n */\nexport function cornerNodes(detection: TargetDetection): GridNode[] {\n const lattice = isLatticeKind(detection.kind);\n return (detection.corners ?? []).map((corner): GridNode => {\n const node: GridNode = {\n id: corner.id,\n x: corner.x,\n y: corner.y,\n i: lattice && Number.isInteger(corner.i) ? corner.i! : Number.NaN,\n j: lattice && Number.isInteger(corner.j) ? corner.j! : Number.NaN,\n label: cornerLabel(corner, lattice),\n };\n if (corner.angle !== undefined) {\n node.kind = \"directed\";\n node.angle = corner.angle;\n if (corner.angle2 !== undefined) node.angle2 = corner.angle2;\n }\n return node;\n });\n}\n\n/**\n * The regions of the marker layer: each marker's quad, labelled with its text or its id.\n *\n * @param detection - The detection.\n * @returns One area per marker with a usable quad.\n */\nexport function markerAreas(detection: TargetDetection): AreaSetItem[] {\n return markerPolygons(detection.markers ?? []).map((polygon) => ({\n id: polygon.id,\n points: polygon.points,\n label: polygon.label ?? String(polygon.id),\n }));\n}\n\n/** The label of a circle: its own, else `(i, j)` when it matched a cell. */\nfunction circleLabel(circle: TargetCircle): string | undefined {\n if (circle.label !== undefined) return circle.label;\n return Number.isInteger(circle.i) && Number.isInteger(circle.j) ? `(${circle.i}, ${circle.j})` : undefined;\n}\n\n/**\n * The points of the circle layer. Polarity picks the glyph: `circle-white` is a hollow ring,\n * `circle-black` a ring with a dot.\n *\n * @param detection - The detection.\n * @returns One point per circle.\n */\nexport function circlePoints(detection: TargetDetection): PointSetItem[] {\n return (detection.circles ?? []).map((circle) => {\n const item: PointSetItem = { id: circle.id, x: circle.x, y: circle.y, kind: `circle-${circle.polarity}` };\n const label = circleLabel(circle);\n if (label !== undefined) item.label = label;\n return item;\n });\n}\n\n/**\n * The points of the ring layer: a `plus` at each centre, picked anywhere inside the outer ellipse\n * (`pickRadius` is the larger semi-axis), labelled with the ring's text or its id.\n *\n * @param rings - The rings.\n * @returns One point per ring.\n */\nexport function ringCentres(rings: readonly TargetRing[]): PointSetItem[] {\n return rings.map((ring) => ({\n id: ring.id,\n x: ring.x,\n y: ring.y,\n kind: \"plus\",\n pickRadius: Math.max(ring.outer.rx, ring.outer.ry),\n label: ring.label ?? String(ring.id),\n }));\n}\n\n/**\n * The ellipses of the rings' two edges. The outer is `feature`, the inner `model` (a fitted\n * second edge), and the smaller inner one is told from the outer by size as well as by colour.\n *\n * @param rings - The rings.\n * @returns The outer ellipses, and the inner ones of the rings that have one.\n */\nexport function ringEllipses(rings: readonly TargetRing[]): { outer: EllipseSetItem[]; inner: EllipseSetItem[] } {\n const outer: EllipseSetItem[] = [];\n const inner: EllipseSetItem[] = [];\n for (const ring of rings) {\n outer.push({ id: ring.id, x: ring.x, y: ring.y, rx: ring.outer.rx, ry: ring.outer.ry, angle: ring.outer.angle, role: \"feature\" });\n if (ring.inner) {\n inner.push({ id: ring.id, x: ring.x, y: ring.y, rx: ring.inner.rx, ry: ring.inner.ry, angle: ring.inner.angle, role: \"model\" });\n }\n }\n return { outer, inner };\n}\n\n/** Opacity of a dot at confidence 0 and at confidence 1: a weak bit is visible, a sure one is solid. */\nconst BIT_OPACITY_MIN = 0.35;\n\n/**\n * The dots of the edge-bit layer: bit 1 is a solid `feature` circle, bit 0 a dashed `model`\n * one, and the opacity runs from 35 % at confidence 0 to 100 % at confidence 1.\n *\n * @param bits - The edge bits.\n * @returns One ellipse (a circle) per bit.\n */\nexport function edgeBitEllipses(bits: readonly TargetEdgeBit[]): EllipseSetItem[] {\n return bits.map((bit) => ({\n id: bit.id,\n x: bit.x,\n y: bit.y,\n rx: bit.radius,\n ry: bit.radius,\n role: bit.bit === 1 ? \"feature\" : \"model\",\n dashed: bit.bit === 0,\n opacity: BIT_OPACITY_MIN + (1 - BIT_OPACITY_MIN) * Math.min(1, Math.max(0, bit.confidence)),\n }));\n}\n\n/**\n * The ellipse of a 2×2 position covariance: `scale` standard deviations along each principal\n * axis.\n *\n * The semi-axes are `scale · √λ` for the matrix's two eigenvalues `λ₁ ≥ λ₂`, and `angle` is the\n * direction of the eigenvector of `λ₁` (radians, clockwise on screen, in `(-π/2, π/2]`). At\n * `scale = 1` this is the 1σ ellipse: the curve `dᵀ Σ⁻¹ d = 1`.\n *\n * @param cov - The covariance `[xx, xy, yy]`, image pixels squared.\n * @param scale - The gain applied to both semi-axes. Defaults to 1.\n * @returns The ellipse, or `null` when the matrix is not finite and positive definite, or the\n * scale is not a finite positive number: there is no ellipse to draw.\n */\nexport function covarianceEllipse(cov: readonly [xx: number, xy: number, yy: number], scale = 1): TargetEllipse | null {\n const [xx, xy, yy] = cov;\n if (!Number.isFinite(xx + xy + yy) || !(Number.isFinite(scale) && scale > 0)) return null;\n const det = xx * yy - xy * xy;\n // Positive definite: a positive diagonal and a positive determinant.\n if (!(xx > 0 && yy > 0 && det > 0)) return null;\n const mean = 0.5 * (xx + yy);\n const spread = Math.hypot(0.5 * (xx - yy), xy);\n const major = mean + spread;\n // λ₁λ₂ = det: the smaller eigenvalue from the product rather than from `mean - spread`.\n const minor = det / major;\n const half = 0.5 * Math.atan2(2 * xy, xx - yy);\n // `atan2(-0, x < 0)` is -π: keep the axis in (-π/2, π/2].\n const angle = half <= -Math.PI / 2 ? half + Math.PI : half;\n return { rx: scale * Math.sqrt(major), ry: scale * Math.sqrt(minor), angle };\n}\n\n/**\n * The ellipses of the uncertainty layer: each corner's position covariance as a 1σ ellipse,\n * both semi-axes multiplied by `scale`, centred on the corner and sharing its id, in the `model`\n * role. A corner with no covariance, or one that is not positive definite, has none.\n *\n * @param corners - The corners.\n * @param scale - The gain on the semi-axes. A detector's σ is a fraction of a pixel, so it is\n * drawn magnified; print the gain beside the image (\"ellipses ×40\").\n * @returns One ellipse per corner with a drawable covariance, in order.\n */\nexport function uncertaintyEllipses(corners: readonly TargetCorner[], scale: number): EllipseSetItem[] {\n const out: EllipseSetItem[] = [];\n for (const corner of corners) {\n if (!corner.cov) continue;\n const ellipse = covarianceEllipse(corner.cov, scale);\n if (ellipse) out.push({ id: corner.id, x: corner.x, y: corner.y, ...ellipse, role: \"model\" });\n }\n return out;\n}\n\n/** The feature points of a detection (corners, circles, ring centres) that carry `flag`, as one point each of `kind`. */\nfunction markedPoints(detection: TargetDetection, flag: \"excluded\" | \"flagged\", kind: string): PointSetItem[] {\n const out: PointSetItem[] = [];\n const add = (\n items: readonly { id: TargetId; x: number; y: number; excluded?: boolean | undefined; flagged?: boolean | undefined }[] | undefined,\n ) => {\n for (const item of items ?? []) if (item[flag] === true) out.push({ id: item.id, x: item.x, y: item.y, kind });\n };\n add(detection.corners);\n add(detection.circles);\n add(detection.rings);\n return out;\n}\n\n/**\n * The strike-through points of the excluded features: a corner, circle or ring with\n * `excluded` set gets one `excluded` glyph at its position. Markers carry no flags.\n *\n * @param detection - The detection.\n * @returns One point per excluded feature, corners first, then circles, then rings.\n */\nexport function excludedPoints(detection: TargetDetection): PointSetItem[] {\n return markedPoints(detection, \"excluded\", \"excluded\");\n}\n\n/**\n * The ring points of the flagged features: a corner, circle or ring with `flagged` set gets one\n * `flagged` glyph at its position.\n *\n * @param detection - The detection.\n * @returns One point per flagged feature, corners first, then circles, then rings.\n */\nexport function flaggedPoints(detection: TargetDetection): PointSetItem[] {\n return markedPoints(detection, \"flagged\", \"flagged\");\n}\n","/**\n * A calibration-target detection over the image: one component for a chessboard, ChArUco,\n * marker board, PuzzleBoard, ring grid or a loose set of corners.\n *\n * It replaces the per-board overlays of vitavision (`ChessboardOverlay`, `CharucoOverlay`,\n * `MarkerboardOverlay`, `PuzzleboardOverlay`) and the glyph components behind them. Each part of\n * a `TargetDetection` goes to the stage2d layer that fits it, so a detection of thousands of\n * items is a few dozen DOM nodes and the pointer is resolved by the stage's hit-test\n * registry, not the DOM:\n *\n * | Part | Layer | Glyph |\n * |---|---|---|\n * | `corners` | `GridLayer` | plus; edge directions when `angle` is set; lattice edges and `i,j` labels |\n * | `markers` | `AreaSet` | quad outline and 12 % fill, corner 0 ticked, id inside |\n * | `circles` | `PointSet` | ring; a centre dot marks black |\n * | `rings` | `PointSet` + `EllipseSet` | fitted outer and inner ellipse, plus at the centre |\n * | `edgeBits` | `EllipseSet` | dot on the edge: solid for 1, dashed for 0, opacity from confidence |\n * | corners' `cov` | `EllipseSet` | with `uncertainty`: the 1σ ellipse × the scale, in `model` |\n * | `excluded` features | `PointSet` | the feature dimmed, a small cross through it |\n * | `flagged` features | `PointSet` | a thin ring around the feature |\n */\n\nimport { EllipseSet, GridLayer, AreaSet, PointSet, type StagePointerEvent } from \"@vitavision/stage2d\";\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\nimport { TARGET_MARKERS } from \"./glyphs\";\nimport {\n circlePoints,\n cornerNodes,\n edgeBitEllipses,\n excludedPoints,\n flaggedPoints,\n markerAreas,\n ringCentres,\n ringEllipses,\n uncertaintyEllipses,\n} from \"./layerItems\";\nimport type { TargetDetection, TargetHit, TargetId, TargetPart } from \"./model\";\n\n/** Props of `TargetOverlay`. */\nexport interface TargetOverlayProps {\n /** The detection to draw. Pass a stable object: a new one rebuilds every layer's index. */\n detection: TargetDetection;\n /** Draw the lattice edges between neighbouring corners, one dashed axis and one solid. On by default. */\n showEdges?: boolean | undefined;\n /** Show labels (lattice indices, marker ids, ring ids) where the zoom leaves room for them. On by default. */\n showLabels?: boolean | undefined;\n /**\n * The hovered id, when the app controls hover (a list beside the stage hovers items too). It\n * applies to every part that has the id; keep ids unique within a detection.\n */\n hoveredId?: TargetId | null | undefined;\n /** The selected ids, drawn at 2.5 px in the selection colour; points get a ring. */\n selectedIds?: Iterable<TargetId> | undefined;\n /**\n * Called when the item under the pointer changes, once per change; `null` when it leaves every\n * item. The `id` is the one given in the detection, so the app maps it back to its feature.\n */\n onHoverChange?: ((hit: TargetHit | null) => void) | undefined;\n /**\n * A press landed on an item. Setting it makes the layers claim presses on their items, so the\n * stage does not pan from them. A mounted `StageSurface` hears a press first; there, ask\n * `useStageHitTest` what is under it instead.\n */\n onItemPress?: ((hit: TargetHit, event: StagePointerEvent) => void) | undefined;\n /**\n * Dim the whole overlay (`true`), or the listed ids, or those a predicate accepts, to 35 %\n * opacity. They still take hover and presses. Pass a stable value: a new one re-batches.\n */\n dimmed?: boolean | Iterable<TargetId> | ((id: TargetId) => boolean) | undefined;\n /**\n * Draw each corner's position covariance (`cov`) as its 1σ ellipse with both semi-axes\n * multiplied by `scale`, in the `model` role, under the corners. Off by default.\n *\n * A detector's σ is a small fraction of a pixel, so the ellipses are drawn magnified: the\n * `scale` is the app's to choose and to print beside the image (\"ellipses ×40\"), as a\n * residual's gain is. Their shape and orientation are the data's. A corner with no covariance,\n * or one that is not positive definite, gets none. The ellipses take the corner's hover,\n * selection and dimming, and are not picked themselves.\n */\n uncertainty?: { scale: number } | undefined;\n /** Prefix of the hit-test layer ids (`<prefix>-corners`, `-markers`, `-circles`, `-rings`). Defaults to generated ids. */\n layerIdPrefix?: string | undefined;\n}\n\n/** The ids of each part, to route a hovered or selected id to the layers that have it. */\nfunction idsByPart(detection: TargetDetection): Record<TargetPart, ReadonlySet<TargetId>> {\n const ids = (items: readonly { id: TargetId }[] | undefined) => new Set((items ?? []).map((item) => item.id));\n return {\n corner: ids(detection.corners),\n marker: ids(detection.markers),\n circle: ids(detection.circles),\n ring: ids(detection.rings),\n };\n}\n\n/** The `dimmed` prop as the predicate the layers take, or `undefined` for none. */\nfunction dimPredicate(dimmed: TargetOverlayProps[\"dimmed\"]): ((id: TargetId) => boolean) | undefined {\n if (dimmed === undefined || dimmed === false) return undefined;\n if (dimmed === true) return () => true;\n if (typeof dimmed === \"function\") return dimmed;\n const set = new Set(dimmed);\n return (id) => set.has(id);\n}\n\n/**\n * A detected calibration target inside an `ImageStage`.\n *\n * - **Batched**: one path per appearance in each layer, picking through spatial indices. Labels\n * appear only where items are 24 screen px apart, at most 200 at a time.\n * - **States**: hover 2 px, selected 2.5 px in the selection colour with a ring, dimmed at 35 %.\n * - **Colour**: roles only (`feature`, `model`, `structure`, `selection`). Scores are never drawn\n * as red, amber or green; polarity and bits are carried by shape (hollow or dotted, solid or\n * dashed), not by hue.\n * - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move\n * between layers (a corner, then the marker under it) without a flicker: the change is reported\n * once.\n * - **Excluded and flagged features**: a corner, circle or ring with `excluded` is drawn dimmed\n * with a small cross through it (a state, not a rejection); one with `flagged` has a thin ring\n * around it (a mismatch with the master pattern, say). Both are drawn in the `label` role on a\n * halo, compose with hover, selection and each other, and are not picked themselves.\n * - **Uncertainty** (opt-in, `uncertainty`): each corner's covariance as a 1σ ellipse × the\n * given scale, under the corners.\n *\n * The layers it renders carry their own accessible names (\"Corners: 54 points, 0 selected\").\n */\nexport function TargetOverlay({\n detection,\n showEdges = true,\n showLabels = true,\n hoveredId,\n selectedIds,\n onHoverChange,\n onItemPress,\n dimmed,\n uncertainty,\n layerIdPrefix,\n}: TargetOverlayProps) {\n const nodes = useMemo(() => cornerNodes(detection), [detection]);\n const areas = useMemo(() => markerAreas(detection), [detection]);\n const circles = useMemo(() => circlePoints(detection), [detection]);\n const rings = detection.rings;\n const ringPoints = useMemo(() => ringCentres(rings ?? []), [rings]);\n const ringShapes = useMemo(() => ringEllipses(rings ?? []), [rings]);\n const bits = useMemo(() => edgeBitEllipses(detection.edgeBits ?? []), [detection.edgeBits]);\n const uncertaintyScale = uncertainty?.scale;\n const covEllipses = useMemo(\n () => (uncertaintyScale === undefined ? [] : uncertaintyEllipses(detection.corners ?? [], uncertaintyScale)),\n [detection.corners, uncertaintyScale],\n );\n const ids = useMemo(() => idsByPart(detection), [detection]);\n\n // Selection and hover are by id; each layer is given the ids it owns, so its count is right.\n const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);\n const selected = useMemo(() => {\n const pick = (part: TargetPart) => new Set([...selectedSet].filter((id) => ids[part].has(id)));\n return { corner: pick(\"corner\"), marker: pick(\"marker\"), circle: pick(\"circle\"), ring: pick(\"ring\") };\n }, [selectedSet, ids]);\n const userDimmed = useMemo(() => dimPredicate(dimmed), [dimmed]);\n const excluded = useMemo(() => excludedPoints(detection), [detection]);\n const flagged = useMemo(() => flaggedPoints(detection), [detection]);\n // An excluded feature is dimmed on every layer that draws it; the strike-through is not.\n const isDimmed = useMemo(() => {\n if (excluded.length === 0) return userDimmed;\n const ids = new Set(excluded.map((item) => item.id));\n return (id: TargetId) => ids.has(id) || (userDimmed?.(id) ?? false);\n }, [excluded, userDimmed]);\n\n // Hover. The layers report separately, so moving from a corner to the marker under it is\n // `corner → null` then `marker → id` in one event. The net result is read when the event is\n // done, and reported once.\n const [ownHover, setOwnHover] = useState<TargetHit | null>(null);\n const hoverRef = useRef<TargetHit | null>(null);\n const reportedRef = useRef<TargetHit | null>(null);\n const scheduledRef = useRef(false);\n const onHoverChangeRef = useRef(onHoverChange);\n useLayoutEffect(() => {\n onHoverChangeRef.current = onHoverChange;\n });\n const hoverFrom = useCallback(\n (part: TargetPart) => (id: TargetId | null) => {\n if (id !== null) hoverRef.current = { id, part };\n else if (hoverRef.current?.part === part) hoverRef.current = null;\n setOwnHover(hoverRef.current);\n if (scheduledRef.current) return;\n scheduledRef.current = true;\n queueMicrotask(() => {\n scheduledRef.current = false;\n const now = hoverRef.current;\n const before = reportedRef.current;\n if (now?.id === before?.id && now?.part === before?.part) return;\n reportedRef.current = now;\n onHoverChangeRef.current?.(now);\n });\n },\n [],\n );\n const hoverOf = (part: TargetPart): TargetId | null => {\n if (hoveredId !== undefined) return hoveredId !== null && ids[part].has(hoveredId) ? hoveredId : null;\n return ownHover?.part === part ? ownHover.id : null;\n };\n\n const pressFrom = (part: TargetPart) =>\n onItemPress ? (id: TargetId, event: StagePointerEvent) => onItemPress({ id, part }, event) : undefined;\n const layerId = (name: string) => (layerIdPrefix === undefined ? undefined : `${layerIdPrefix}-${name}`);\n\n const hasCorners = nodes.length > 0;\n const hasMarkers = areas.length > 0;\n const hasCircles = circles.length > 0;\n const hasRings = ringPoints.length > 0;\n const edgeStyle = { visible: showEdges };\n\n return (\n <>\n {hasMarkers && (\n <AreaSet\n items={areas}\n firstVertexTick\n labels={showLabels}\n hoveredId={hoverOf(\"marker\")}\n selectedIds={selected.marker}\n dimmed={isDimmed}\n onHoverChange={hoverFrom(\"marker\")}\n onItemPress={pressFrom(\"marker\")}\n layerId={layerId(\"markers\")}\n label=\"Markers\"\n />\n )}\n {bits.length > 0 && <EllipseSet items={bits} minRadius={3} dimmed={isDimmed} pickable={false} />}\n {hasRings && (\n <>\n <EllipseSet items={ringShapes.outer} hoveredId={hoverOf(\"ring\")} selectedIds={selected.ring} dimmed={isDimmed} pickable={false} />\n {ringShapes.inner.length > 0 && (\n <EllipseSet\n items={ringShapes.inner}\n role=\"model\"\n hoveredId={hoverOf(\"ring\")}\n selectedIds={selected.ring}\n dimmed={isDimmed}\n pickable={false}\n />\n )}\n <PointSet\n items={ringPoints}\n kind=\"plus\"\n markers={TARGET_MARKERS}\n labels={showLabels}\n hoveredId={hoverOf(\"ring\")}\n selectedIds={selected.ring}\n dimmed={isDimmed}\n onHoverChange={hoverFrom(\"ring\")}\n onItemPress={pressFrom(\"ring\")}\n layerId={layerId(\"rings\")}\n label=\"Rings\"\n />\n </>\n )}\n {covEllipses.length > 0 && (\n <EllipseSet\n items={covEllipses}\n role=\"model\"\n hoveredId={hoverOf(\"corner\")}\n selectedIds={selected.corner}\n dimmed={isDimmed}\n pickable={false}\n label={`Position uncertainty: 1σ ellipses ×${uncertaintyScale}`}\n />\n )}\n {hasCorners && (\n <GridLayer\n nodes={nodes}\n markers={TARGET_MARKERS}\n edges={{ i: edgeStyle, j: { ...edgeStyle, dashed: true } }}\n labels={showLabels}\n hoveredId={hoverOf(\"corner\")}\n selectedIds={selected.corner}\n dimmed={isDimmed}\n onHoverChange={hoverFrom(\"corner\")}\n onItemPress={pressFrom(\"corner\")}\n layerId={layerId(\"corners\")}\n label=\"Corners\"\n />\n )}\n {hasCircles && (\n <PointSet\n items={circles}\n markers={TARGET_MARKERS}\n labels={showLabels}\n hoveredId={hoverOf(\"circle\")}\n selectedIds={selected.circle}\n dimmed={isDimmed}\n onHoverChange={hoverFrom(\"circle\")}\n onItemPress={pressFrom(\"circle\")}\n layerId={layerId(\"circles\")}\n label=\"Circles\"\n />\n )}\n {excluded.length > 0 && (\n <PointSet\n items={excluded}\n markers={TARGET_MARKERS}\n labels={false}\n dimmed={userDimmed}\n pickable={false}\n layerId={layerId(\"excluded\")}\n label=\"Excluded features\"\n />\n )}\n {flagged.length > 0 && (\n <PointSet\n items={flagged}\n markers={TARGET_MARKERS}\n labels={false}\n dimmed={userDimmed}\n pickable={false}\n layerId={layerId(\"flagged\")}\n label=\"Flagged features\"\n />\n )}\n </>\n );\n}\n","/**\n * PuzzleBoard edge bits: from a decoder's observed edges to the dots the overlay draws.\n *\n * A PuzzleBoard encodes its position in the bumps along the edges between corners. The decoder\n * reports each observed edge in the image's own local frame (`row`, `col`), and the alignment\n * that maps that frame into the board's master frame, which is periodic with period 501. The\n * corners are labelled with master indices, so an edge's two corners are found by mapping its\n * local end points through the alignment, modulo the period. This is the arithmetic of\n * vitavision's `PuzzleboardOverlay.buildEdgeMarkers`, as a pure function over structural types,\n * so no detector package is imported.\n *\n * Pure: no React, no DOM.\n */\n\nimport { gridKey } from \"./lattice\";\nimport type { TargetCorner, TargetEdgeBit } from \"./model\";\n\n/** The period of the PuzzleBoard master pattern. */\nexport const PUZZLEBOARD_PERIOD = 501;\n\n/** One observed edge of a PuzzleBoard decode. */\nexport interface PuzzleboardEdge {\n /** Row of the edge's first corner, in the image's local frame. */\n row: number;\n /** Column of the edge's first corner, in the image's local frame. */\n col: number;\n /** `\"horizontal\"` joins local `(col, row)` to `(col + 1, row)`; `\"vertical\"` to `(col, row + 1)`. */\n orientation: \"horizontal\" | \"vertical\";\n /** The decoded bit. */\n bit: 0 | 1;\n /** Decode confidence, [0, 1]. */\n confidence: number;\n}\n\n/** The map from the local frame to master indices: `master = M · local + translation`, modulo the period. */\nexport interface PuzzleboardAlignment {\n /** The 2×2 integer matrix `[[a, b], [c, d]]`, acting on local `(i, j)`. */\n transform: { a: number; b: number; c: number; d: number };\n /** The translation, added after the matrix. */\n translation: readonly [number, number];\n}\n\n/** `value` modulo `period`, in `[0, period)` for any sign. */\nfunction wrap(value: number, period: number): number {\n return ((value % period) + period) % period;\n}\n\n/**\n * The edge bits of a PuzzleBoard decode, placed on the image.\n *\n * An edge is dropped when either of its corners was not detected. Each dot sits at the midpoint\n * of its edge with a radius of a quarter of the edge's length (the bump is about half an edge\n * wide); its opacity is the app's to take from `confidence`.\n *\n * @param edges - The observed edges.\n * @param corners - The labelled corners, whose `i` and `j` are **master** indices.\n * @param alignment - The local-to-master map.\n * @param period - The master pattern's period. Defaults to 501.\n * @returns One `TargetEdgeBit` per edge whose corners were both found, in input order. Empty when there is no alignment.\n */\nexport function edgeBitsFromPuzzleboard(\n edges: readonly PuzzleboardEdge[],\n corners: readonly TargetCorner[],\n alignment: PuzzleboardAlignment | null | undefined,\n period: number = PUZZLEBOARD_PERIOD,\n): TargetEdgeBit[] {\n if (!alignment || edges.length === 0 || corners.length === 0) return [];\n\n const byMaster = new Map<string, TargetCorner>();\n for (const corner of corners) {\n if (Number.isInteger(corner.i) && Number.isInteger(corner.j)) byMaster.set(gridKey(corner.i!, corner.j!), corner);\n }\n const { a, b, c, d } = alignment.transform;\n const [tx, ty] = alignment.translation;\n const toMaster = (i: number, j: number): string => gridKey(wrap(a * i + b * j + tx, period), wrap(c * i + d * j + ty, period));\n\n const out: TargetEdgeBit[] = [];\n edges.forEach((edge, index) => {\n // Local coordinates are (i = col, j = row).\n const from = byMaster.get(toMaster(edge.col, edge.row));\n const to = byMaster.get(edge.orientation === \"horizontal\" ? toMaster(edge.col + 1, edge.row) : toMaster(edge.col, edge.row + 1));\n if (!from || !to) return;\n out.push({\n id: `${edge.orientation}-${edge.row}-${edge.col}-${index}`,\n x: 0.5 * (from.x + to.x),\n y: 0.5 * (from.y + to.y),\n radius: 0.25 * Math.hypot(to.x - from.x, to.y - from.y),\n bit: edge.bit,\n confidence: Math.min(1, Math.max(0, edge.confidence)),\n });\n });\n return out;\n}\n","/**\n * calib-targets results to `TargetDetection`: the one mapping from what the\n * `@vitavision/calib-targets` WASM detectors return to what `TargetOverlay` draws.\n *\n * The input types below are the minimal structure the mapping reads, written to be satisfied by\n * the package's own result types (`ChessboardDetection`, `CharucoDetection`,\n * `MarkerBoardDetection`, `PuzzleBoardDetection`, `Corner`, and the `diagnose_*` payloads), so this\n * package takes no dependency on it. Every field the mapping does not read is ignored, and every\n * field a newer calib-targets adds is optional here, so results with and without it both fit.\n *\n * Pure: no React, no DOM.\n */\n\nimport type { TargetCircle, TargetCorner, TargetDetection, TargetKind, TargetMarker } from \"./model\";\nimport { edgeBitsFromPuzzleboard, type PuzzleboardEdge } from \"./puzzleboard\";\n\n/** An image point `[x, y]`, pixels with the centre of pixel `i` at `i` (calib-targets' `Point2`). */\nexport type CalibTargetsPoint = readonly [x: number, y: number];\n\n/** A position covariance, image pixels squared (calib-targets' `position_covariance`). */\nexport interface CalibTargetsCovariance {\n /** Variance along x. */\n xx: number;\n /** Covariance of x and y. */\n xy: number;\n /** Variance along y. */\n yy: number;\n}\n\n/** An integer lattice coordinate (calib-targets' `Coord`): `u` along the first board axis, `v` the second. */\nexport interface CalibTargetsCoord {\n /** First axis, rightwards on the board. */\n u: number;\n /** Second axis, downwards on the board. */\n v: number;\n}\n\n/** A labelled board corner: what `ChessboardCorner`, `CharucoCorner`, `MarkerBoardCorner` and `PuzzleBoardCorner` share. */\nexport interface CalibTargetsLabeledCorner {\n /** Sub-pixel image position. */\n position: CalibTargetsPoint;\n /** Lattice label; `null` for a corner with no place on the board. */\n grid: CalibTargetsCoord | null;\n /** The detector's score, higher is better. */\n score: number;\n /** Position covariance, when the detector reports one. */\n position_covariance?: CalibTargetsCovariance | null | undefined;\n}\n\n/** One axis estimate of a raw corner (calib-targets' `AxisEstimate`). */\nexport interface CalibTargetsAxis {\n /** Direction of the axis, radians in the image frame (clockwise on screen). */\n angle: number;\n}\n\n/** A raw ChESS corner, as `detect_corners` returns it (calib-targets' `Corner`). */\nexport interface CalibTargetsCorner {\n /** Sub-pixel image position. */\n position: CalibTargetsPoint;\n /** The two grid axes through the corner. */\n axes: readonly [CalibTargetsAxis, CalibTargetsAxis];\n /** Corner response, higher is stronger. */\n strength: number;\n /** Position covariance, when the detector reports one. */\n position_covariance?: CalibTargetsCovariance | null | undefined;\n}\n\n/** A chessboard detection (`ChessboardDetection`). */\nexport interface CalibTargetsChessboardDetection {\n /** The labelled corners. */\n corners: readonly CalibTargetsLabeledCorner[];\n}\n\n/** A decoded ArUco marker of a ChArUco detection (`MarkerDetection`). */\nexport interface CalibTargetsMarker {\n /** The marker's dictionary id. */\n id: number;\n /** Its four corners in the image, in the marker's own order; `null` when they were not projected. */\n corners_img: readonly [CalibTargetsPoint, CalibTargetsPoint, CalibTargetsPoint, CalibTargetsPoint] | null;\n}\n\n/** A ChArUco detection (`CharucoDetection`). */\nexport interface CalibTargetsCharucoDetection {\n /** The labelled corners. */\n corners: readonly CalibTargetsLabeledCorner[];\n /** The markers consistent with the board alignment. */\n markers: readonly CalibTargetsMarker[];\n}\n\n/** A checkerboard marker board detection (`MarkerBoardDetection`). */\nexport interface CalibTargetsMarkerBoardDetection {\n /** The labelled corners. */\n corners: readonly CalibTargetsLabeledCorner[];\n}\n\n/** A scored circle hypothesis of a marker board (`CircleCandidate`). */\nexport interface CalibTargetsCircleCandidate {\n /** Centre of the circle in the image. */\n center_img: CalibTargetsPoint;\n}\n\n/** A board circle paired with a detected one (`CircleMatch`). */\nexport interface CalibTargetsCircleMatch {\n /** The circle the board layout expects: its cell and printed polarity. */\n expected: { cell: { i: number; j: number }; polarity: \"white\" | \"black\" };\n /** Index into `circle_candidates` of the circle that matched it, or `null` for none. */\n matched_index: number | null;\n}\n\n/** The part of `diagnose_marker_board`'s `diagnostics` the overlay draws (`MarkerBoardDiagnostics`). */\nexport interface CalibTargetsMarkerBoardDiagnostics {\n /** The circle hypotheses. */\n circle_candidates: readonly CalibTargetsCircleCandidate[];\n /** The board's circles and the candidates they matched. */\n circle_matches: readonly CalibTargetsCircleMatch[];\n}\n\n/** A grid alignment (`GridAlignment`): `master = matrix · local + translation`. */\nexport interface CalibTargetsAlignment {\n /** Row-major integer matrix, applied to local `(u, v)` before the translation. */\n matrix: readonly [readonly [number, number], readonly [number, number]];\n /** Integer translation, grid units. */\n translation: readonly [number, number];\n}\n\n/** A PuzzleBoard detection (`PuzzleBoardDetection`); its corners carry master labels. */\nexport interface CalibTargetsPuzzleBoardDetection {\n /** The labelled corners, `grid` in the master frame. */\n corners: readonly CalibTargetsLabeledCorner[];\n /** The map from the decoder's local frame to the master frame. */\n alignment: CalibTargetsAlignment;\n}\n\n/** One observed edge bit, in the decoder's local frame (`PuzzleBoardObservedEdge`). */\nexport interface CalibTargetsObservedEdge {\n /** Row of the edge's first corner. */\n row: number;\n /** Column of the edge's first corner. */\n col: number;\n /** Which neighbour the edge runs to. */\n orientation: \"horizontal\" | \"vertical\";\n /** The observed bit, 0 or 1. */\n bit: number;\n /** Per-bit confidence, [0, 1]. */\n confidence: number;\n}\n\n/** The part of `diagnose_puzzleboard`'s `diagnostics` the overlay draws (`PuzzleBoardDiagnostics`). */\nexport interface CalibTargetsPuzzleBoardDiagnostics {\n /** Every sampled edge, before alignment. */\n observed_edges: readonly CalibTargetsObservedEdge[];\n}\n\n/** A PuzzlePole detection: a PuzzleBoard wrapped round a cylinder; `grid` is (axial, around). */\nexport interface CalibTargetsPuzzlePoleDetection {\n /** The labelled corners. */\n corners: readonly CalibTargetsLabeledCorner[];\n}\n\n/**\n * One calib-targets result, tagged with the detector that produced it.\n *\n * A board detector returns `null` (or, from `diagnose_*`, `undefined`) when it finds nothing;\n * pass that through as `detection` and the result is an empty detection of the same kind.\n * `diagnostics` is the `diagnostics` of the matching `diagnose_*` call: it carries what the plain\n * result does not (the marker-board circles, the PuzzleBoard edge bits). Convert a `diagnose_*`\n * payload to plain objects first if your binding returns `Map`s.\n */\nexport type CalibTargetsResult =\n | {\n /** Raw ChESS corners, from `detect_corners`. */\n kind: \"corners\";\n /** The corners. */\n corners: readonly CalibTargetsCorner[];\n }\n | {\n /** A chessboard, from `detect_chessboard`. */\n kind: \"chessboard\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsChessboardDetection | null | undefined;\n }\n | {\n /** A ChArUco board, from `detect_charuco` or `diagnose_charuco`. */\n kind: \"charuco\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsCharucoDetection | null | undefined;\n }\n | {\n /** A checkerboard marker board, from `detect_marker_board` or `diagnose_marker_board`. */\n kind: \"markerboard\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsMarkerBoardDetection | null | undefined;\n /** `diagnose_marker_board`'s diagnostics, for the matched circles. */\n diagnostics?: CalibTargetsMarkerBoardDiagnostics | null | undefined;\n }\n | {\n /** A PuzzleBoard, from `detect_puzzleboard` or `diagnose_puzzleboard`. */\n kind: \"puzzleboard\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsPuzzleBoardDetection | null | undefined;\n /** `diagnose_puzzleboard`'s diagnostics, for the edge bits. */\n diagnostics?: CalibTargetsPuzzleBoardDiagnostics | null | undefined;\n }\n | {\n /** A PuzzlePole. Drawn as a PuzzleBoard lattice, without edge bits. */\n kind: \"puzzlepole\";\n /** The detection, or `null` when none was found. */\n detection: CalibTargetsPuzzlePoleDetection | null | undefined;\n };\n\n/** The overlay kind of each calib-targets result kind. */\nconst OVERLAY_KIND: Readonly<Record<CalibTargetsResult[\"kind\"], TargetKind>> = {\n corners: \"corners\",\n chessboard: \"chessboard\",\n charuco: \"charuco\",\n markerboard: \"markerboard\",\n puzzleboard: \"puzzleboard\",\n puzzlepole: \"puzzleboard\",\n};\n\n/** A covariance as `TargetCorner.cov`, or `undefined` when there is none or it is not finite. */\nfunction covOf(cov: CalibTargetsCovariance | null | undefined): TargetCorner[\"cov\"] {\n if (!cov) return undefined;\n const { xx, xy, yy } = cov;\n return Number.isFinite(xx + xy + yy) ? [xx, xy, yy] : undefined;\n}\n\n/** A labelled corner as a `TargetCorner`, id `corner-<index>`; `(u, v)` becomes `(i, j)`. */\nfunction labeledCorner(corner: CalibTargetsLabeledCorner, index: number): TargetCorner {\n const out: TargetCorner = { id: `corner-${index}`, x: corner.position[0], y: corner.position[1], score: corner.score };\n if (corner.grid) {\n out.i = corner.grid.u;\n out.j = corner.grid.v;\n }\n const cov = covOf(corner.position_covariance);\n if (cov) out.cov = cov;\n return out;\n}\n\n/** A raw corner as a `TargetCorner` with both axis directions, id `corner-<index>`, labelled with its index. */\nfunction rawCorner(corner: CalibTargetsCorner, index: number): TargetCorner {\n const out: TargetCorner = {\n id: `corner-${index}`,\n x: corner.position[0],\n y: corner.position[1],\n score: corner.strength,\n angle: corner.axes[0].angle,\n angle2: corner.axes[1].angle,\n label: String(index),\n };\n const cov = covOf(corner.position_covariance);\n if (cov) out.cov = cov;\n return out;\n}\n\n/** The markers with a projected quad, id `marker-<index>`, labelled with the dictionary id. */\nfunction markersOf(markers: readonly CalibTargetsMarker[]): TargetMarker[] {\n const out: TargetMarker[] = [];\n markers.forEach((marker, index) => {\n if (!marker.corners_img) return;\n out.push({ id: `marker-${index}`, corners: marker.corners_img.flatMap(([x, y]) => [x, y]), label: String(marker.id) });\n });\n return out;\n}\n\n/**\n * The matched circles of a marker board, id `circle-<index>` (index into `circle_matches`): at\n * the matched candidate's centre, with the board's cell and printed polarity. An unmatched board\n * circle is not drawn, nor is a candidate no board circle matched.\n */\nfunction circlesOf(diagnostics: CalibTargetsMarkerBoardDiagnostics): TargetCircle[] {\n const out: TargetCircle[] = [];\n diagnostics.circle_matches.forEach((match, index) => {\n const candidate = match.matched_index === null ? undefined : diagnostics.circle_candidates[match.matched_index];\n if (!candidate) return;\n out.push({\n id: `circle-${index}`,\n x: candidate.center_img[0],\n y: candidate.center_img[1],\n polarity: match.expected.polarity,\n i: match.expected.cell.i,\n j: match.expected.cell.j,\n });\n });\n return out;\n}\n\n/** The observed edges as `edgeBitsFromPuzzleboard` takes them: a nonzero bit is 1. */\nfunction edgesOf(edges: readonly CalibTargetsObservedEdge[]): PuzzleboardEdge[] {\n return edges.map((edge) => ({\n row: edge.row,\n col: edge.col,\n orientation: edge.orientation,\n bit: edge.bit === 0 ? 0 : 1,\n confidence: edge.confidence,\n }));\n}\n\n/**\n * The `TargetDetection` of a calib-targets result.\n *\n * - **Kinds.** `chessboard`, `charuco`, `markerboard`, `puzzleboard` and raw `corners` map to the\n * overlay kind of the same name; a `puzzlepole` is drawn as a `puzzleboard` lattice.\n * - **Corners.** Positions pass through unchanged (calib-targets reports the centre of pixel `i`\n * at `i`, as the overlay expects). A labelled corner's grid `(u, v)` becomes `(i, j)`, so a\n * board draws its lattice and labels corners `i,j`. A raw corner draws its two axes (`angle`,\n * `angle2`) and is labelled with its index; its `strength` is the `score`.\n * - **Covariance.** A corner's `position_covariance`, when present and finite, becomes `cov`;\n * `TargetOverlay` draws it with `uncertainty`.\n * - **Markers** (ChArUco) are the quads of `corners_img`, labelled with the dictionary id; a\n * marker without a projected quad is left out.\n * - **Circles** (marker board, from `diagnostics`) are the board circles a candidate matched,\n * at the candidate's centre with the board's cell and polarity.\n * - **Edge bits** (PuzzleBoard, from `diagnostics`) are the observed edges placed through the\n * alignment with `edgeBitsFromPuzzleboard`.\n *\n * Ids are `corner-<n>`, `marker-<n>` and `circle-<n>`, where `n` is the index into the result's\n * `corners`, `markers` or `circle_matches`, so a hover or a press maps straight back to it.\n *\n * @param result - The result, tagged with its kind.\n * @returns The detection for `TargetOverlay`. Parts with no items are left out.\n */\nexport function fromCalibTargets(result: CalibTargetsResult): TargetDetection {\n const detection: TargetDetection = { kind: OVERLAY_KIND[result.kind] };\n\n if (result.kind === \"corners\") {\n if (result.corners.length > 0) detection.corners = result.corners.map(rawCorner);\n return detection;\n }\n if (!result.detection) return detection;\n\n const corners = result.detection.corners.map(labeledCorner);\n if (corners.length > 0) detection.corners = corners;\n\n switch (result.kind) {\n case \"charuco\": {\n const markers = markersOf(result.detection.markers);\n if (markers.length > 0) detection.markers = markers;\n break;\n }\n case \"markerboard\": {\n const circles = result.diagnostics ? circlesOf(result.diagnostics) : [];\n if (circles.length > 0) detection.circles = circles;\n break;\n }\n case \"puzzleboard\": {\n if (!result.diagnostics) break;\n const { matrix, translation } = result.detection.alignment;\n const alignment = {\n transform: { a: matrix[0][0], b: matrix[0][1], c: matrix[1][0], d: matrix[1][1] },\n translation: [translation[0], translation[1]] as const,\n };\n const edgeBits = edgeBitsFromPuzzleboard(edgesOf(result.diagnostics.observed_edges), corners, alignment);\n if (edgeBits.length > 0) detection.edgeBits = edgeBits;\n break;\n }\n default:\n break;\n }\n return detection;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAS,MAAM,OAAuB;CACpC,OAAO,KAAK,MAAM,QAAQ,GAAI,IAAI;AACpC;;AAGA,SAAS,UAAU,OAAuB;CACxC,MAAM,UAAU,QAAQ,KAAK;CAC7B,OAAO,UAAU,IAAI,UAAU,KAAK,KAAK;AAC3C;;AAGA,MAAM,aAAa;AACnB,MAAM,WAAW;;;;;;AAOjB,MAAM,WAAwB;CAC5B,OAAO;CACP,MAAM;CACN,OAAO,GAAG,GAAG,MAAM,OAAO,WAAW;EACnC,IAAI,IAAI;EACR,KAAK,MAAM,aAAa,WAAW,KAAA,IAAY,CAAC,KAAK,IAAI,CAAC,OAAO,MAAM,GAAG;GACxE,IAAI,CAAC,OAAO,SAAS,SAAS,GAAG;GACjC,M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AC5C;EACF;EACA,KAAK,eAAe;GAClB,IAAI,CAAC,OAAO,aAAa;GACzB,MAAM,EAAE,QAAQ,gBAAgB,OAAO,UAAU;GACjD,MAAM,YAAY;IAChB,WAAW;KAAE,GAAG,OAAO,EAAE,CAAC;KAAI,GAAG,OAAO,EAAE,CAAC;KAAI,GAAG,OAAO,EAAE,CAAC;KAAI,GAAG,OAAO,EAAE,CAAC;IAAG;IAChF,aAAa,CAAC,YAAY,IAAI,YAAY,EAAE;GAC9C;GACA,MAAM,WAAW,wBAAwB,QAAQ,OAAO,YAAY,cAAc,GAAG,SAAS,SAAS;GACvG,IAAI,SAAS,SAAS,GAAG,UAAU,WAAW;GAC9C;EACF;CAGF;CACA,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vitavision/overlays",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Calibration-target overlays: one TargetOverlay for chessboard, ChArUco, marker board, PuzzleBoard and ring-grid detections on the stage2d image stage.",
|
|
5
5
|
"license": "MIT OR Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -42,14 +42,14 @@
|
|
|
42
42
|
"api:check": "api-extractor run"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"@vitavision/stage2d": ">=0.
|
|
45
|
+
"@vitavision/stage2d": ">=0.16.0 <1.0.0-0",
|
|
46
46
|
"react": "^19.2.0",
|
|
47
47
|
"react-dom": "^19.2.0"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
50
|
"@storybook/react-vite": "10.6.0",
|
|
51
|
-
"@vitavision/stage2d": "^0.
|
|
52
|
-
"@vitavision/ui": "^0.14.
|
|
51
|
+
"@vitavision/stage2d": "^0.16.0",
|
|
52
|
+
"@vitavision/ui": "^0.14.2",
|
|
53
53
|
"storybook": "10.6.0"
|
|
54
54
|
}
|
|
55
55
|
}
|
package/src/TargetOverlay.tsx
CHANGED
|
@@ -16,13 +16,25 @@
|
|
|
16
16
|
* | `rings` | `PointSet` + `EllipseSet` | fitted outer and inner ellipse, plus at the centre |
|
|
17
17
|
* | `edgeBits` | `EllipseSet` | dot on the edge: solid for 1, dashed for 0, opacity from confidence |
|
|
18
18
|
* | corners' `cov` | `EllipseSet` | with `uncertainty`: the 1σ ellipse × the scale, in `model` |
|
|
19
|
+
* | `excluded` features | `PointSet` | the feature dimmed, a small cross through it |
|
|
20
|
+
* | `flagged` features | `PointSet` | a thin ring around the feature |
|
|
19
21
|
*/
|
|
20
22
|
|
|
21
23
|
import { EllipseSet, GridLayer, AreaSet, PointSet, type StagePointerEvent } from "@vitavision/stage2d";
|
|
22
24
|
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
23
25
|
|
|
24
26
|
import { TARGET_MARKERS } from "./glyphs";
|
|
25
|
-
import {
|
|
27
|
+
import {
|
|
28
|
+
circlePoints,
|
|
29
|
+
cornerNodes,
|
|
30
|
+
edgeBitEllipses,
|
|
31
|
+
excludedPoints,
|
|
32
|
+
flaggedPoints,
|
|
33
|
+
markerAreas,
|
|
34
|
+
ringCentres,
|
|
35
|
+
ringEllipses,
|
|
36
|
+
uncertaintyEllipses,
|
|
37
|
+
} from "./layerItems";
|
|
26
38
|
import type { TargetDetection, TargetHit, TargetId, TargetPart } from "./model";
|
|
27
39
|
|
|
28
40
|
/** Props of `TargetOverlay`. */
|
|
@@ -103,6 +115,10 @@ function dimPredicate(dimmed: TargetOverlayProps["dimmed"]): ((id: TargetId) =>
|
|
|
103
115
|
* - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move
|
|
104
116
|
* between layers (a corner, then the marker under it) without a flicker: the change is reported
|
|
105
117
|
* once.
|
|
118
|
+
* - **Excluded and flagged features**: a corner, circle or ring with `excluded` is drawn dimmed
|
|
119
|
+
* with a small cross through it (a state, not a rejection); one with `flagged` has a thin ring
|
|
120
|
+
* around it (a mismatch with the master pattern, say). Both are drawn in the `label` role on a
|
|
121
|
+
* halo, compose with hover, selection and each other, and are not picked themselves.
|
|
106
122
|
* - **Uncertainty** (opt-in, `uncertainty`): each corner's covariance as a 1σ ellipse × the
|
|
107
123
|
* given scale, under the corners.
|
|
108
124
|
*
|
|
@@ -140,7 +156,15 @@ export function TargetOverlay({
|
|
|
140
156
|
const pick = (part: TargetPart) => new Set([...selectedSet].filter((id) => ids[part].has(id)));
|
|
141
157
|
return { corner: pick("corner"), marker: pick("marker"), circle: pick("circle"), ring: pick("ring") };
|
|
142
158
|
}, [selectedSet, ids]);
|
|
143
|
-
const
|
|
159
|
+
const userDimmed = useMemo(() => dimPredicate(dimmed), [dimmed]);
|
|
160
|
+
const excluded = useMemo(() => excludedPoints(detection), [detection]);
|
|
161
|
+
const flagged = useMemo(() => flaggedPoints(detection), [detection]);
|
|
162
|
+
// An excluded feature is dimmed on every layer that draws it; the strike-through is not.
|
|
163
|
+
const isDimmed = useMemo(() => {
|
|
164
|
+
if (excluded.length === 0) return userDimmed;
|
|
165
|
+
const ids = new Set(excluded.map((item) => item.id));
|
|
166
|
+
return (id: TargetId) => ids.has(id) || (userDimmed?.(id) ?? false);
|
|
167
|
+
}, [excluded, userDimmed]);
|
|
144
168
|
|
|
145
169
|
// Hover. The layers report separately, so moving from a corner to the marker under it is
|
|
146
170
|
// `corner → null` then `marker → id` in one event. The net result is read when the event is
|
|
@@ -271,6 +295,28 @@ export function TargetOverlay({
|
|
|
271
295
|
label="Circles"
|
|
272
296
|
/>
|
|
273
297
|
)}
|
|
298
|
+
{excluded.length > 0 && (
|
|
299
|
+
<PointSet
|
|
300
|
+
items={excluded}
|
|
301
|
+
markers={TARGET_MARKERS}
|
|
302
|
+
labels={false}
|
|
303
|
+
dimmed={userDimmed}
|
|
304
|
+
pickable={false}
|
|
305
|
+
layerId={layerId("excluded")}
|
|
306
|
+
label="Excluded features"
|
|
307
|
+
/>
|
|
308
|
+
)}
|
|
309
|
+
{flagged.length > 0 && (
|
|
310
|
+
<PointSet
|
|
311
|
+
items={flagged}
|
|
312
|
+
markers={TARGET_MARKERS}
|
|
313
|
+
labels={false}
|
|
314
|
+
dimmed={userDimmed}
|
|
315
|
+
pickable={false}
|
|
316
|
+
layerId={layerId("flagged")}
|
|
317
|
+
label="Flagged features"
|
|
318
|
+
/>
|
|
319
|
+
)}
|
|
274
320
|
</>
|
|
275
321
|
);
|
|
276
322
|
}
|
package/src/glyphs.ts
CHANGED
|
@@ -70,6 +70,34 @@ const circleBlack: MarkerShape = {
|
|
|
70
70
|
path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit) + circlePath(x, y, CENTRE_RADIUS * unit),
|
|
71
71
|
};
|
|
72
72
|
|
|
73
|
+
/** Half-length of an excluded feature's strike-through cross, screen pixels. */
|
|
74
|
+
const EXCLUDED_REACH = 6;
|
|
75
|
+
/** Radius of a flagged feature's ring, screen pixels: outside the selection ring (about 9 px). */
|
|
76
|
+
const FLAG_RADIUS = 12;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The strike-through of an excluded feature: a small diagonal cross, 6 px arms, over the dimmed
|
|
80
|
+
* feature. Painted in the `label` role so it holds on the dimmed mark on a light or dark image,
|
|
81
|
+
* and in no verdict colour: an excluded feature is switched off, not wrong.
|
|
82
|
+
*/
|
|
83
|
+
const excluded: MarkerShape = {
|
|
84
|
+
paint: "line",
|
|
85
|
+
size: EXCLUDED_REACH,
|
|
86
|
+
role: "label",
|
|
87
|
+
path: (x, y, unit) => {
|
|
88
|
+
const a = EXCLUDED_REACH * unit;
|
|
89
|
+
return `M${round(x - a)} ${round(y - a)}l${round(2 * a)} ${round(2 * a)}M${round(x - a)} ${round(y + a)}l${round(2 * a)} ${round(-2 * a)}`;
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/** The ring of a flagged feature: a thin circle of radius 12 px, in the `label` role. */
|
|
94
|
+
const flagged: MarkerShape = {
|
|
95
|
+
paint: "line",
|
|
96
|
+
size: FLAG_RADIUS,
|
|
97
|
+
role: "label",
|
|
98
|
+
path: (x, y, unit) => circlePath(x, y, FLAG_RADIUS * unit),
|
|
99
|
+
};
|
|
100
|
+
|
|
73
101
|
/** The marker names `TargetOverlay` uses, to pass to `PointSet`'s `markers`. */
|
|
74
102
|
export const TARGET_MARKERS = {
|
|
75
103
|
/** Edge directions of a corner, from `angle` and `angle2`. */
|
|
@@ -78,4 +106,8 @@ export const TARGET_MARKERS = {
|
|
|
78
106
|
"circle-white": circleWhite,
|
|
79
107
|
/** A black matched circle. */
|
|
80
108
|
"circle-black": circleBlack,
|
|
109
|
+
/** The cross through an excluded feature. */
|
|
110
|
+
excluded,
|
|
111
|
+
/** The ring around a flagged feature. */
|
|
112
|
+
flagged,
|
|
81
113
|
} as const satisfies Readonly<Record<string, MarkerShape>>;
|
package/src/index.ts
CHANGED
package/src/layerItems.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
type TargetDetection,
|
|
18
18
|
type TargetEdgeBit,
|
|
19
19
|
type TargetEllipse,
|
|
20
|
+
type TargetId,
|
|
20
21
|
type TargetRing,
|
|
21
22
|
} from "./model";
|
|
22
23
|
|
|
@@ -203,3 +204,39 @@ export function uncertaintyEllipses(corners: readonly TargetCorner[], scale: num
|
|
|
203
204
|
}
|
|
204
205
|
return out;
|
|
205
206
|
}
|
|
207
|
+
|
|
208
|
+
/** The feature points of a detection (corners, circles, ring centres) that carry `flag`, as one point each of `kind`. */
|
|
209
|
+
function markedPoints(detection: TargetDetection, flag: "excluded" | "flagged", kind: string): PointSetItem[] {
|
|
210
|
+
const out: PointSetItem[] = [];
|
|
211
|
+
const add = (
|
|
212
|
+
items: readonly { id: TargetId; x: number; y: number; excluded?: boolean | undefined; flagged?: boolean | undefined }[] | undefined,
|
|
213
|
+
) => {
|
|
214
|
+
for (const item of items ?? []) if (item[flag] === true) out.push({ id: item.id, x: item.x, y: item.y, kind });
|
|
215
|
+
};
|
|
216
|
+
add(detection.corners);
|
|
217
|
+
add(detection.circles);
|
|
218
|
+
add(detection.rings);
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* The strike-through points of the excluded features: a corner, circle or ring with
|
|
224
|
+
* `excluded` set gets one `excluded` glyph at its position. Markers carry no flags.
|
|
225
|
+
*
|
|
226
|
+
* @param detection - The detection.
|
|
227
|
+
* @returns One point per excluded feature, corners first, then circles, then rings.
|
|
228
|
+
*/
|
|
229
|
+
export function excludedPoints(detection: TargetDetection): PointSetItem[] {
|
|
230
|
+
return markedPoints(detection, "excluded", "excluded");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* The ring points of the flagged features: a corner, circle or ring with `flagged` set gets one
|
|
235
|
+
* `flagged` glyph at its position.
|
|
236
|
+
*
|
|
237
|
+
* @param detection - The detection.
|
|
238
|
+
* @returns One point per flagged feature, corners first, then circles, then rings.
|
|
239
|
+
*/
|
|
240
|
+
export function flaggedPoints(detection: TargetDetection): PointSetItem[] {
|
|
241
|
+
return markedPoints(detection, "flagged", "flagged");
|
|
242
|
+
}
|
package/src/model.ts
CHANGED
|
@@ -75,6 +75,18 @@ export interface TargetCorner {
|
|
|
75
75
|
cov?: readonly [xx: number, xy: number, yy: number] | undefined;
|
|
76
76
|
/** Text beside it. Defaults to the lattice index `i,j` on a board, else the id. */
|
|
77
77
|
label?: string | undefined;
|
|
78
|
+
/**
|
|
79
|
+
* The feature is excluded from use (left out of a fit, switched off by the person): it is
|
|
80
|
+
* drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on
|
|
81
|
+
* it, so it is not drawn like a rejected point. It still takes hover and presses.
|
|
82
|
+
*/
|
|
83
|
+
excluded?: boolean | undefined;
|
|
84
|
+
/**
|
|
85
|
+
* The feature is flagged: a thin ring is drawn around it, for "this feature disagrees with
|
|
86
|
+
* what it should be" (a decoded id that differs from the master pattern, say). It composes
|
|
87
|
+
* with `excluded`, hover and selection.
|
|
88
|
+
*/
|
|
89
|
+
flagged?: boolean | undefined;
|
|
78
90
|
}
|
|
79
91
|
|
|
80
92
|
/** One decoded fiducial marker (ArUco, AprilTag): a quad. */
|
|
@@ -109,6 +121,18 @@ export interface TargetCircle {
|
|
|
109
121
|
j?: number | undefined;
|
|
110
122
|
/** Text beside it. Defaults to `(i, j)` when both are set. */
|
|
111
123
|
label?: string | undefined;
|
|
124
|
+
/**
|
|
125
|
+
* The feature is excluded from use (left out of a fit, switched off by the person): it is
|
|
126
|
+
* drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on
|
|
127
|
+
* it, so it is not drawn like a rejected point. It still takes hover and presses.
|
|
128
|
+
*/
|
|
129
|
+
excluded?: boolean | undefined;
|
|
130
|
+
/**
|
|
131
|
+
* The feature is flagged: a thin ring is drawn around it, for "this feature disagrees with
|
|
132
|
+
* what it should be" (a decoded id that differs from the master pattern, say). It composes
|
|
133
|
+
* with `excluded`, hover and selection.
|
|
134
|
+
*/
|
|
135
|
+
flagged?: boolean | undefined;
|
|
112
136
|
}
|
|
113
137
|
|
|
114
138
|
/** A fitted ellipse. */
|
|
@@ -135,6 +159,18 @@ export interface TargetRing {
|
|
|
135
159
|
inner?: TargetEllipse | undefined;
|
|
136
160
|
/** Text beside the centre. Defaults to the id. */
|
|
137
161
|
label?: string | undefined;
|
|
162
|
+
/**
|
|
163
|
+
* The ring is excluded from use (left out of a fit, switched off by the person): it is
|
|
164
|
+
* drawn dimmed with a small cross through it. It is a state of the feature, not a verdict on
|
|
165
|
+
* it, so it is not drawn like a rejected point. It still takes hover and presses.
|
|
166
|
+
*/
|
|
167
|
+
excluded?: boolean | undefined;
|
|
168
|
+
/**
|
|
169
|
+
* The ring is flagged: a thin ring is drawn around its centre, for "this feature disagrees with
|
|
170
|
+
* what it should be" (a decoded id that differs from the master pattern, say). It composes
|
|
171
|
+
* with `excluded`, hover and selection.
|
|
172
|
+
*/
|
|
173
|
+
flagged?: boolean | undefined;
|
|
138
174
|
}
|
|
139
175
|
|
|
140
176
|
/**
|