@vitavision/stage2d 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -1
- package/dist/index.d.ts +538 -14
- package/dist/index.js +1276 -50
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/components/MeasureOverlay.tsx +128 -32
- package/src/components/PolylineSet.tsx +308 -0
- package/src/components/RectRoiEditor.tsx +292 -0
- package/src/components/overlayRole.ts +53 -0
- package/src/components/polylineIndex.ts +288 -0
- package/src/components/roiEdit.ts +154 -0
- package/src/components/stage/ImageLayer.tsx +118 -0
- package/src/components/stage/ImageStage.tsx +49 -10
- package/src/components/stage/StageSurface.tsx +177 -0
- package/src/components/stage/StageToolbar.tsx +105 -6
- package/src/components/stage/useScreenPx.ts +16 -0
- package/src/components/stage/view.ts +7 -2
- package/src/index.ts +55 -0
- package/src/styles.css +27 -3
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A region of interest as an object rather than a gesture: drawn, moved and resized on the
|
|
3
|
+
* image, kept inside it.
|
|
4
|
+
*
|
|
5
|
+
* Its predecessors in the apps could only draw a *new* box: every press started again from a
|
|
6
|
+
* corner, so a box that was nearly right had to be redrawn, and one drawn at fit could not
|
|
7
|
+
* be refined by zooming in first. Here the box has eight handles and an interior, and it lives
|
|
8
|
+
* inside `ImageStage`'s transform, so it stays on the pixels it encloses at any zoom.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
|
|
12
|
+
|
|
13
|
+
import type { Point } from "./measureGeometry";
|
|
14
|
+
import {
|
|
15
|
+
ROI_HANDLES,
|
|
16
|
+
ROI_HANDLE_CURSOR,
|
|
17
|
+
clampRect,
|
|
18
|
+
moveRect,
|
|
19
|
+
rectFromCorners,
|
|
20
|
+
resizeRect,
|
|
21
|
+
roiHandlePoint,
|
|
22
|
+
type RoiHandle,
|
|
23
|
+
} from "./roiEdit";
|
|
24
|
+
import { overlayRole } from "./overlayRole";
|
|
25
|
+
import { useStage } from "./stage/ImageStage";
|
|
26
|
+
import { useScreenPx } from "./stage/useScreenPx";
|
|
27
|
+
import { imageViewBox, type Rect } from "./stage/view";
|
|
28
|
+
|
|
29
|
+
/** Handle square side, in screen pixels. */
|
|
30
|
+
const HANDLE_PX = 9;
|
|
31
|
+
/** Outline width, in screen pixels. */
|
|
32
|
+
const STROKE_PX = 1.5;
|
|
33
|
+
/** The halo under the outline (visual-language §5), in screen pixels on each side. */
|
|
34
|
+
const HALO_PX = 1;
|
|
35
|
+
const HALO = overlayRole("halo");
|
|
36
|
+
|
|
37
|
+
/** Props of `RectRoiEditor`. */
|
|
38
|
+
export interface RectRoiEditorProps {
|
|
39
|
+
/** The region in image coordinates, or `null` for none. */
|
|
40
|
+
value: Rect | null;
|
|
41
|
+
/** Called with the region as it changes: on every move of a drag, and on each key nudge. */
|
|
42
|
+
onValueChange: (value: Rect) => void;
|
|
43
|
+
/** Called once a gesture ends (a drag released, a nudge made): the moment to save or re-run. */
|
|
44
|
+
onCommit?: ((value: Rect) => void) | undefined;
|
|
45
|
+
/** Show handles and accept moves and resizes. Defaults to `true`. */
|
|
46
|
+
editable?: boolean | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* Draw a new region with a drag on the image, outside the current one. Only while the app's
|
|
49
|
+
* region tool is active: in draw mode the layer claims presses that would otherwise pan.
|
|
50
|
+
*/
|
|
51
|
+
draw?: boolean | undefined;
|
|
52
|
+
/**
|
|
53
|
+
* The area the region must stay in. Defaults to `{ x: 0, y: 0, width, height }` of the
|
|
54
|
+
* image: a region given as a start pixel and a size.
|
|
55
|
+
*/
|
|
56
|
+
bounds?: Rect | undefined;
|
|
57
|
+
/** The smallest side, in image pixels; a smaller drawn box is a click, not a region. Defaults to 4. */
|
|
58
|
+
minSize?: number | undefined;
|
|
59
|
+
/** The region's accessible name. Defaults to "Region". */
|
|
60
|
+
label?: string | undefined;
|
|
61
|
+
/** CSS colour of the outline and handles. Defaults to the overlay `selection` role. */
|
|
62
|
+
stroke?: string | undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
type Drag =
|
|
66
|
+
| { kind: "move"; from: Point; start: Rect; moved: boolean }
|
|
67
|
+
| { kind: "resize"; handle: RoiHandle; start: Rect; moved: boolean }
|
|
68
|
+
| { kind: "draw"; from: Point; moved: boolean };
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* An editable axis-aligned region inside an `ImageStage`.
|
|
72
|
+
*
|
|
73
|
+
* - **Handles.** The eight handles resize the region, and the interior moves it. A handle
|
|
74
|
+
* dragged through the opposite edge flips the box.
|
|
75
|
+
* - **Drawing.** With `draw`, a drag elsewhere on the image draws a new region.
|
|
76
|
+
* - **Keyboard.** The region is focusable: arrow keys move it by one image pixel (ten with
|
|
77
|
+
* Shift), and with Alt they grow or shrink it from the bottom-right corner.
|
|
78
|
+
* - **Limits.** The region stays inside `bounds` and never gets smaller than `minSize`.
|
|
79
|
+
* - **Rendering.** Handles and the outline are a constant size on screen at every zoom.
|
|
80
|
+
* - **Panning.** A press with the hand tool, or with space held, still pans.
|
|
81
|
+
*
|
|
82
|
+
* The SVG carries `data-editable` and `data-drawing` (while a draw is in progress).
|
|
83
|
+
*/
|
|
84
|
+
export function RectRoiEditor({
|
|
85
|
+
value,
|
|
86
|
+
onValueChange,
|
|
87
|
+
onCommit,
|
|
88
|
+
editable = true,
|
|
89
|
+
draw = false,
|
|
90
|
+
bounds,
|
|
91
|
+
minSize = 4,
|
|
92
|
+
label = "Region",
|
|
93
|
+
stroke = overlayRole("selection"),
|
|
94
|
+
}: RectRoiEditorProps) {
|
|
95
|
+
const stage = useStage();
|
|
96
|
+
const area = bounds ?? { x: 0, y: 0, width: stage.image.width, height: stage.image.height };
|
|
97
|
+
const dragRef = useRef<Drag | null>(null);
|
|
98
|
+
const lastRef = useRef<Rect | null>(null);
|
|
99
|
+
const [drawing, setDrawing] = useState<Rect | null>(null);
|
|
100
|
+
|
|
101
|
+
const px = useScreenPx();
|
|
102
|
+
const shown = drawing ?? value;
|
|
103
|
+
|
|
104
|
+
const report = (next: Rect) => {
|
|
105
|
+
lastRef.current = next;
|
|
106
|
+
onValueChange(next);
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const begin = (event: PointerEvent<SVGElement>, drag: Drag) => {
|
|
110
|
+
if (stage.panMode || event.button !== 0) return;
|
|
111
|
+
event.stopPropagation();
|
|
112
|
+
event.preventDefault();
|
|
113
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
114
|
+
dragRef.current = drag;
|
|
115
|
+
lastRef.current = null;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const onMove = (event: PointerEvent<SVGElement>) => {
|
|
119
|
+
const drag = dragRef.current;
|
|
120
|
+
if (!drag) return;
|
|
121
|
+
event.stopPropagation();
|
|
122
|
+
const p = stage.toImage({ x: event.clientX, y: event.clientY });
|
|
123
|
+
drag.moved = true;
|
|
124
|
+
if (drag.kind === "move") {
|
|
125
|
+
report(moveRect(drag.start, p.x - drag.from.x, p.y - drag.from.y, area));
|
|
126
|
+
} else if (drag.kind === "resize") {
|
|
127
|
+
report(resizeRect(drag.start, drag.handle, p, area, minSize));
|
|
128
|
+
} else {
|
|
129
|
+
const drawn = clampRect(rectFromCorners(clampPoint(drag.from, area), clampPoint(p, area)), area, 0);
|
|
130
|
+
// Kept in the ref too: a pointer-up can arrive before the move's render, and the end of
|
|
131
|
+
// the gesture must see the box the last move drew.
|
|
132
|
+
lastRef.current = drawn;
|
|
133
|
+
setDrawing(drawn);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const onEnd = (event: PointerEvent<SVGElement>) => {
|
|
138
|
+
const drag = dragRef.current;
|
|
139
|
+
if (!drag) return;
|
|
140
|
+
event.stopPropagation();
|
|
141
|
+
dragRef.current = null;
|
|
142
|
+
if (drag.kind === "draw") {
|
|
143
|
+
const drawn = lastRef.current;
|
|
144
|
+
setDrawing(null);
|
|
145
|
+
// A drawn box smaller than `minSize` is a click, not a region.
|
|
146
|
+
if (drawn && drawn.width >= minSize && drawn.height >= minSize) {
|
|
147
|
+
onValueChange(drawn);
|
|
148
|
+
onCommit?.(drawn);
|
|
149
|
+
}
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const onKeyDown = (event: KeyboardEvent<SVGElement>) => {
|
|
156
|
+
if (!editable || value === null) return;
|
|
157
|
+
const step = event.shiftKey ? 10 : 1;
|
|
158
|
+
const delta: Record<string, Point> = {
|
|
159
|
+
ArrowLeft: { x: -step, y: 0 },
|
|
160
|
+
ArrowRight: { x: step, y: 0 },
|
|
161
|
+
ArrowUp: { x: 0, y: -step },
|
|
162
|
+
ArrowDown: { x: 0, y: step },
|
|
163
|
+
};
|
|
164
|
+
const d = delta[event.key];
|
|
165
|
+
if (!d) return;
|
|
166
|
+
event.preventDefault();
|
|
167
|
+
event.stopPropagation();
|
|
168
|
+
const next = event.altKey
|
|
169
|
+
? clampRect({ ...value, width: value.width + d.x, height: value.height + d.y }, area, minSize)
|
|
170
|
+
: moveRect(value, d.x, d.y, area);
|
|
171
|
+
onValueChange(next);
|
|
172
|
+
onCommit?.(next);
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const outline = shown && (
|
|
176
|
+
<>
|
|
177
|
+
<rect
|
|
178
|
+
x={shown.x}
|
|
179
|
+
y={shown.y}
|
|
180
|
+
width={shown.width}
|
|
181
|
+
height={shown.height}
|
|
182
|
+
fill="none"
|
|
183
|
+
stroke={HALO}
|
|
184
|
+
strokeWidth={px(STROKE_PX + 2 * HALO_PX)}
|
|
185
|
+
/>
|
|
186
|
+
<rect
|
|
187
|
+
x={shown.x}
|
|
188
|
+
y={shown.y}
|
|
189
|
+
width={shown.width}
|
|
190
|
+
height={shown.height}
|
|
191
|
+
fill={stroke}
|
|
192
|
+
fillOpacity={0.06}
|
|
193
|
+
stroke={stroke}
|
|
194
|
+
strokeWidth={px(STROKE_PX)}
|
|
195
|
+
strokeDasharray={`${px(6)} ${px(4)}`}
|
|
196
|
+
/>
|
|
197
|
+
</>
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
return (
|
|
201
|
+
<svg
|
|
202
|
+
viewBox={imageViewBox(stage.image)}
|
|
203
|
+
className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
|
|
204
|
+
data-editable={editable ? "" : undefined}
|
|
205
|
+
data-drawing={drawing ? "" : undefined}
|
|
206
|
+
>
|
|
207
|
+
{draw && editable && (
|
|
208
|
+
<rect
|
|
209
|
+
data-draw-surface=""
|
|
210
|
+
x={area.x}
|
|
211
|
+
y={area.y}
|
|
212
|
+
width={area.width}
|
|
213
|
+
height={area.height}
|
|
214
|
+
fill="transparent"
|
|
215
|
+
className="pointer-events-auto cursor-crosshair"
|
|
216
|
+
onPointerDown={(event) =>
|
|
217
|
+
begin(event, { kind: "draw", from: stage.toImage({ x: event.clientX, y: event.clientY }), moved: false })
|
|
218
|
+
}
|
|
219
|
+
onPointerMove={onMove}
|
|
220
|
+
onPointerUp={onEnd}
|
|
221
|
+
onLostPointerCapture={onEnd}
|
|
222
|
+
/>
|
|
223
|
+
)}
|
|
224
|
+
{outline}
|
|
225
|
+
{editable && value && !drawing && (
|
|
226
|
+
<rect
|
|
227
|
+
x={value.x}
|
|
228
|
+
y={value.y}
|
|
229
|
+
width={value.width}
|
|
230
|
+
height={value.height}
|
|
231
|
+
fill="transparent"
|
|
232
|
+
role="button"
|
|
233
|
+
tabIndex={0}
|
|
234
|
+
aria-label={`${label}: ${fmt(value.x)}, ${fmt(value.y)}, ${fmt(value.width)} × ${fmt(value.height)} px`}
|
|
235
|
+
aria-roledescription="region"
|
|
236
|
+
className="pointer-events-auto cursor-move outline-none focus-visible:stroke-signal"
|
|
237
|
+
onPointerDown={(event) =>
|
|
238
|
+
begin(event, {
|
|
239
|
+
kind: "move",
|
|
240
|
+
from: stage.toImage({ x: event.clientX, y: event.clientY }),
|
|
241
|
+
start: value,
|
|
242
|
+
moved: false,
|
|
243
|
+
})
|
|
244
|
+
}
|
|
245
|
+
onPointerMove={onMove}
|
|
246
|
+
onPointerUp={onEnd}
|
|
247
|
+
onLostPointerCapture={onEnd}
|
|
248
|
+
onKeyDown={onKeyDown}
|
|
249
|
+
onDoubleClick={(event) => event.stopPropagation()}
|
|
250
|
+
/>
|
|
251
|
+
)}
|
|
252
|
+
{editable &&
|
|
253
|
+
value &&
|
|
254
|
+
!drawing &&
|
|
255
|
+
ROI_HANDLES.map((handle) => {
|
|
256
|
+
const centre = roiHandlePoint(value, handle);
|
|
257
|
+
const size = px(HANDLE_PX);
|
|
258
|
+
return (
|
|
259
|
+
<rect
|
|
260
|
+
key={handle}
|
|
261
|
+
data-handle={handle}
|
|
262
|
+
x={centre.x - size / 2}
|
|
263
|
+
y={centre.y - size / 2}
|
|
264
|
+
width={size}
|
|
265
|
+
height={size}
|
|
266
|
+
fill={stroke}
|
|
267
|
+
stroke={HALO}
|
|
268
|
+
strokeWidth={px(1)}
|
|
269
|
+
className="pointer-events-auto"
|
|
270
|
+
style={{ cursor: ROI_HANDLE_CURSOR[handle] }}
|
|
271
|
+
onPointerDown={(event) => begin(event, { kind: "resize", handle, start: value, moved: false })}
|
|
272
|
+
onPointerMove={onMove}
|
|
273
|
+
onPointerUp={onEnd}
|
|
274
|
+
onLostPointerCapture={onEnd}
|
|
275
|
+
onDoubleClick={(event) => event.stopPropagation()}
|
|
276
|
+
/>
|
|
277
|
+
);
|
|
278
|
+
})}
|
|
279
|
+
</svg>
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function clampPoint(p: Point, area: Rect): Point {
|
|
284
|
+
return {
|
|
285
|
+
x: Math.min(area.x + area.width, Math.max(area.x, p.x)),
|
|
286
|
+
y: Math.min(area.y + area.height, Math.max(area.y, p.y)),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function fmt(value: number): string {
|
|
291
|
+
return Number.isInteger(value) ? String(value) : value.toFixed(1);
|
|
292
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The overlay grammar's roles and states (docs/visual-language.md §5), for layers that paint
|
|
3
|
+
* through SVG attributes rather than class names.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* What an overlay mark is.
|
|
8
|
+
* - `feature`: detected or observed (corners, edges, contours).
|
|
9
|
+
* - `model`: predicted (reprojections, fitted geometry).
|
|
10
|
+
* - `structure`: context (a board outline, grid lines).
|
|
11
|
+
* - `selection`: the selected item.
|
|
12
|
+
* - `label`: ids and text.
|
|
13
|
+
* - `halo`: the dark band under every stroke and label, so a mark holds on any image.
|
|
14
|
+
*/
|
|
15
|
+
export type OverlayRole = "feature" | "model" | "structure" | "selection" | "label" | "halo";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A mark's interaction state.
|
|
19
|
+
* - `default` is drawn 1.5 screen px wide.
|
|
20
|
+
* - `hover` is 2 px, and nothing else changes.
|
|
21
|
+
* - `selected` is 2.5 px with a ring in the selection colour.
|
|
22
|
+
* - `dimmed` is 35 % opacity.
|
|
23
|
+
*/
|
|
24
|
+
export type OverlayState = "default" | "hover" | "selected" | "dimmed";
|
|
25
|
+
|
|
26
|
+
/** The roles, in the order the spec lists them. */
|
|
27
|
+
export const OVERLAY_ROLES: readonly OverlayRole[] = ["feature", "model", "structure", "selection", "label", "halo"];
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The CSS paint for a role: a `var(--stage-…)` reference defined by `@vitavision/stage2d/styles.css`.
|
|
31
|
+
*
|
|
32
|
+
* @param role - The role.
|
|
33
|
+
* @returns A CSS value usable as an SVG `stroke` or `fill`.
|
|
34
|
+
*/
|
|
35
|
+
export function overlayRole(role: OverlayRole): string {
|
|
36
|
+
return `var(--stage-${role})`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Screen-pixel stroke widths for each state, before the stage's scale is applied. */
|
|
40
|
+
export const OVERLAY_STATE_WIDTH: Readonly<Record<OverlayState, number>> = {
|
|
41
|
+
default: 1.5,
|
|
42
|
+
hover: 2,
|
|
43
|
+
selected: 2.5,
|
|
44
|
+
dimmed: 1.5,
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Opacity for each state. */
|
|
48
|
+
export const OVERLAY_STATE_OPACITY: Readonly<Record<OverlayState, number>> = {
|
|
49
|
+
default: 1,
|
|
50
|
+
hover: 1,
|
|
51
|
+
selected: 1,
|
|
52
|
+
dimmed: 0.35,
|
|
53
|
+
};
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A spatial index over many polylines: which one is under the pointer, and which ones a
|
|
3
|
+
* rubber band caught.
|
|
4
|
+
*
|
|
5
|
+
* Asking the DOM is too slow at scale. The L0-3 benchmark measured `elementFromPoint` over
|
|
6
|
+
* 20k elements at p95 ≈ 2.1 ms, over the 2 ms gate. A uniform grid of segments answers in
|
|
7
|
+
* microseconds whichever engine draws the lines (`docs/measurements/stage2d-bench-analysis.md`).
|
|
8
|
+
*
|
|
9
|
+
* Points are flat `[x0, y0, x1, y1, …]` arrays in image coordinates, the form a backend
|
|
10
|
+
* returns and the cheapest to keep.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Point } from "./measureGeometry";
|
|
14
|
+
import type { Rect } from "./stage/view";
|
|
15
|
+
|
|
16
|
+
/** A polyline's identity. */
|
|
17
|
+
export type PolylineId = string | number;
|
|
18
|
+
|
|
19
|
+
/** One polyline: an id, flat image-coordinate points, and whether its last point joins its first. */
|
|
20
|
+
export interface Polyline {
|
|
21
|
+
/** Its identity, unique in the set. */
|
|
22
|
+
id: PolylineId;
|
|
23
|
+
/** `[x0, y0, x1, y1, …]` in image coordinates. */
|
|
24
|
+
points: ArrayLike<number>;
|
|
25
|
+
/** Join the last point to the first. */
|
|
26
|
+
closed?: boolean | undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* An index built by `buildPolylineIndex`. Treat it as opaque and query it with
|
|
31
|
+
* `nearestPolyline` and `polylinesInRect`; its layout may change.
|
|
32
|
+
*/
|
|
33
|
+
export interface PolylineIndex {
|
|
34
|
+
/** The polylines, in the order given. */
|
|
35
|
+
readonly items: readonly Polyline[];
|
|
36
|
+
/** Grid cell side, in image pixels. */
|
|
37
|
+
readonly cell: number;
|
|
38
|
+
/** The grid's origin x. */
|
|
39
|
+
readonly x0: number;
|
|
40
|
+
/** The grid's origin y. */
|
|
41
|
+
readonly y0: number;
|
|
42
|
+
/** Grid columns. */
|
|
43
|
+
readonly cols: number;
|
|
44
|
+
/** Grid rows. */
|
|
45
|
+
readonly rows: number;
|
|
46
|
+
/** CSR layout: cell `c`'s entries are `starts[c] .. starts[c + 1]`. */
|
|
47
|
+
readonly starts: Uint32Array;
|
|
48
|
+
/** Per entry, two numbers: the polyline's index and the segment's start point index. */
|
|
49
|
+
readonly segs: Uint32Array;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The nearest polyline to a point. */
|
|
53
|
+
export interface PolylineHit {
|
|
54
|
+
/** Its id. */
|
|
55
|
+
id: PolylineId;
|
|
56
|
+
/** The closest point on it. */
|
|
57
|
+
point: Point;
|
|
58
|
+
/** The distance to that point. */
|
|
59
|
+
distance: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The number of segments of a polyline.
|
|
64
|
+
*
|
|
65
|
+
* @param points - Flat points.
|
|
66
|
+
* @param closed - Whether the last point joins the first.
|
|
67
|
+
* @returns The segment count.
|
|
68
|
+
*/
|
|
69
|
+
function segmentCount(points: ArrayLike<number>, closed: boolean): number {
|
|
70
|
+
const n = Math.floor(points.length / 2);
|
|
71
|
+
if (n < 2) return n === 1 ? 1 : 0; // a single point is a zero-length segment, still pickable
|
|
72
|
+
return closed ? n : n - 1;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The start and end of segment `s` (a single point is its own segment). */
|
|
76
|
+
function segment(points: ArrayLike<number>, s: number): [number, number, number, number] {
|
|
77
|
+
const n = Math.floor(points.length / 2);
|
|
78
|
+
// A single point is a zero-length segment; otherwise the next point, wrapping when closed.
|
|
79
|
+
const b = n === 1 ? 0 : (s + 1) % n;
|
|
80
|
+
return [points[2 * s]!, points[2 * s + 1]!, points[2 * b]!, points[2 * b + 1]!];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Index a set of polylines.
|
|
85
|
+
*
|
|
86
|
+
* @param items - The polylines.
|
|
87
|
+
* @param cell - The grid cell side in image pixels. Defaults to 32: a few segments per cell
|
|
88
|
+
* at contour densities, and a pointer's search radius spans one or two cells.
|
|
89
|
+
* @returns The index.
|
|
90
|
+
*/
|
|
91
|
+
export function buildPolylineIndex(items: readonly Polyline[], cell = 32): PolylineIndex {
|
|
92
|
+
let minX = Infinity;
|
|
93
|
+
let minY = Infinity;
|
|
94
|
+
let maxX = -Infinity;
|
|
95
|
+
let maxY = -Infinity;
|
|
96
|
+
for (const item of items) {
|
|
97
|
+
const p = item.points;
|
|
98
|
+
for (let i = 0; i + 1 < p.length; i += 2) {
|
|
99
|
+
const x = p[i]!;
|
|
100
|
+
const y = p[i + 1]!;
|
|
101
|
+
if (x < minX) minX = x;
|
|
102
|
+
if (x > maxX) maxX = x;
|
|
103
|
+
if (y < minY) minY = y;
|
|
104
|
+
if (y > maxY) maxY = y;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (!(maxX >= minX)) {
|
|
108
|
+
return { items, cell, x0: 0, y0: 0, cols: 1, rows: 1, starts: new Uint32Array(2), segs: new Uint32Array(0) };
|
|
109
|
+
}
|
|
110
|
+
const cols = Math.max(1, Math.ceil((maxX - minX) / cell) + 1);
|
|
111
|
+
const rows = Math.max(1, Math.ceil((maxY - minY) / cell) + 1);
|
|
112
|
+
const cellX = (x: number) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / cell)));
|
|
113
|
+
const cellY = (y: number) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / cell)));
|
|
114
|
+
|
|
115
|
+
// Two passes (count, then fill) into a CSR layout: no per-cell arrays.
|
|
116
|
+
const counts = new Uint32Array(cols * rows + 1);
|
|
117
|
+
const visit = (fn: (c: number, item: number, s: number) => void) => {
|
|
118
|
+
items.forEach((item, index) => {
|
|
119
|
+
const closed = item.closed === true;
|
|
120
|
+
const count = segmentCount(item.points, closed);
|
|
121
|
+
for (let s = 0; s < count; s++) {
|
|
122
|
+
const [ax, ay, bx, by] = segment(item.points, s);
|
|
123
|
+
const cx0 = cellX(Math.min(ax, bx));
|
|
124
|
+
const cx1 = cellX(Math.max(ax, bx));
|
|
125
|
+
const cy0 = cellY(Math.min(ay, by));
|
|
126
|
+
const cy1 = cellY(Math.max(ay, by));
|
|
127
|
+
for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) fn(cy * cols + cx, index, s);
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
};
|
|
131
|
+
visit((c) => counts[c + 1]!++);
|
|
132
|
+
for (let c = 0; c < cols * rows; c++) counts[c + 1]! += counts[c]!;
|
|
133
|
+
const starts = counts;
|
|
134
|
+
const fill = starts.slice(0, cols * rows);
|
|
135
|
+
const segs = new Uint32Array(starts[cols * rows]! * 2);
|
|
136
|
+
visit((c, item, s) => {
|
|
137
|
+
const k = fill[c]!++;
|
|
138
|
+
segs[2 * k] = item;
|
|
139
|
+
segs[2 * k + 1] = s;
|
|
140
|
+
});
|
|
141
|
+
return { items, cell, x0: minX, y0: minY, cols, rows, starts, segs };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The polyline nearest to `p` within `radius`, or `null`.
|
|
146
|
+
*
|
|
147
|
+
* @param index - The index.
|
|
148
|
+
* @param p - The point, in image coordinates.
|
|
149
|
+
* @param radius - The search radius, in image pixels.
|
|
150
|
+
* @returns The nearest polyline, the closest point on it and the distance; ties go to the
|
|
151
|
+
* earlier polyline, so the result does not depend on cell order.
|
|
152
|
+
*/
|
|
153
|
+
export function nearestPolyline(index: PolylineIndex, p: Point, radius: number): PolylineHit | null {
|
|
154
|
+
const { items, cell, x0, y0, cols, rows, starts, segs } = index;
|
|
155
|
+
const cx0 = Math.max(0, Math.floor((p.x - radius - x0) / cell));
|
|
156
|
+
const cx1 = Math.min(cols - 1, Math.floor((p.x + radius - x0) / cell));
|
|
157
|
+
const cy0 = Math.max(0, Math.floor((p.y - radius - y0) / cell));
|
|
158
|
+
const cy1 = Math.min(rows - 1, Math.floor((p.y + radius - y0) / cell));
|
|
159
|
+
let best: PolylineHit | null = null;
|
|
160
|
+
let bestItem = Infinity;
|
|
161
|
+
let bestD = radius * radius;
|
|
162
|
+
for (let cy = cy0; cy <= cy1; cy++) {
|
|
163
|
+
for (let cx = cx0; cx <= cx1; cx++) {
|
|
164
|
+
const c = cy * cols + cx;
|
|
165
|
+
for (let k = starts[c]!; k < starts[c + 1]!; k++) {
|
|
166
|
+
const itemIndex = segs[2 * k]!;
|
|
167
|
+
const item = items[itemIndex]!;
|
|
168
|
+
const [ax, ay, bx, by] = segment(item.points, segs[2 * k + 1]!);
|
|
169
|
+
const q = closestOnSegment(p, ax, ay, bx, by);
|
|
170
|
+
const d = (q.x - p.x) ** 2 + (q.y - p.y) ** 2;
|
|
171
|
+
if (d < bestD || (d === bestD && itemIndex < bestItem)) {
|
|
172
|
+
bestD = d;
|
|
173
|
+
bestItem = itemIndex;
|
|
174
|
+
best = { id: item.id, point: q, distance: Math.sqrt(d) };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return best;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The polylines with any part inside `rect`, in the order they were given.
|
|
184
|
+
*
|
|
185
|
+
* Any part, not any vertex: a long straight contour crossing a rubber band has no vertex
|
|
186
|
+
* inside it and is still what the band was aimed at.
|
|
187
|
+
*
|
|
188
|
+
* @param index - The index.
|
|
189
|
+
* @param rect - The band, in image coordinates.
|
|
190
|
+
* @returns Their ids.
|
|
191
|
+
*/
|
|
192
|
+
export function polylinesInRect(index: PolylineIndex, rect: Rect): PolylineId[] {
|
|
193
|
+
const { items, cell, x0, y0, cols, rows, starts, segs } = index;
|
|
194
|
+
const hit = new Uint8Array(items.length);
|
|
195
|
+
const cx0 = Math.max(0, Math.floor((rect.x - x0) / cell));
|
|
196
|
+
const cx1 = Math.min(cols - 1, Math.floor((rect.x + rect.width - x0) / cell));
|
|
197
|
+
const cy0 = Math.max(0, Math.floor((rect.y - y0) / cell));
|
|
198
|
+
const cy1 = Math.min(rows - 1, Math.floor((rect.y + rect.height - y0) / cell));
|
|
199
|
+
for (let cy = cy0; cy <= cy1; cy++) {
|
|
200
|
+
for (let cx = cx0; cx <= cx1; cx++) {
|
|
201
|
+
const c = cy * cols + cx;
|
|
202
|
+
for (let k = starts[c]!; k < starts[c + 1]!; k++) {
|
|
203
|
+
const itemIndex = segs[2 * k]!;
|
|
204
|
+
if (hit[itemIndex]) continue;
|
|
205
|
+
const item = items[itemIndex]!;
|
|
206
|
+
const [ax, ay, bx, by] = segment(item.points, segs[2 * k + 1]!);
|
|
207
|
+
if (segmentTouchesRect(ax, ay, bx, by, rect)) hit[itemIndex] = 1;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const ids: PolylineId[] = [];
|
|
212
|
+
items.forEach((item, i) => {
|
|
213
|
+
if (hit[i]) ids.push(item.id);
|
|
214
|
+
});
|
|
215
|
+
return ids;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* A polyline as an SVG path (`M … L … Z`).
|
|
220
|
+
*
|
|
221
|
+
* @param points - Flat points.
|
|
222
|
+
* @param closed - Whether to close it.
|
|
223
|
+
* @returns The path data; `""` with no points.
|
|
224
|
+
*/
|
|
225
|
+
export function polylinePath(points: ArrayLike<number>, closed = false): string {
|
|
226
|
+
if (points.length < 2) return "";
|
|
227
|
+
let d = `M${points[0]} ${points[1]}`;
|
|
228
|
+
// A single point draws as a zero-length segment, which round caps show as a dot.
|
|
229
|
+
if (points.length < 4) return `${d}L${points[0]} ${points[1]}`;
|
|
230
|
+
for (let i = 2; i + 1 < points.length; i += 2) d += `L${points[i]} ${points[i + 1]}`;
|
|
231
|
+
return closed ? `${d}Z` : d;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* The bounding box of flat points.
|
|
236
|
+
*
|
|
237
|
+
* @param points - Flat points.
|
|
238
|
+
* @returns The box, or `null` without points.
|
|
239
|
+
*/
|
|
240
|
+
export function polylineBounds(points: ArrayLike<number>): Rect | null {
|
|
241
|
+
if (points.length < 2) return null;
|
|
242
|
+
let minX = Infinity;
|
|
243
|
+
let minY = Infinity;
|
|
244
|
+
let maxX = -Infinity;
|
|
245
|
+
let maxY = -Infinity;
|
|
246
|
+
for (let i = 0; i + 1 < points.length; i += 2) {
|
|
247
|
+
const x = points[i]!;
|
|
248
|
+
const y = points[i + 1]!;
|
|
249
|
+
if (x < minX) minX = x;
|
|
250
|
+
if (x > maxX) maxX = x;
|
|
251
|
+
if (y < minY) minY = y;
|
|
252
|
+
if (y > maxY) maxY = y;
|
|
253
|
+
}
|
|
254
|
+
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: number): Point {
|
|
258
|
+
const dx = bx - ax;
|
|
259
|
+
const dy = by - ay;
|
|
260
|
+
const len2 = dx * dx + dy * dy;
|
|
261
|
+
const t = len2 > 0 ? Math.max(0, Math.min(1, ((p.x - ax) * dx + (p.y - ay) * dy) / len2)) : 0;
|
|
262
|
+
return { x: ax + t * dx, y: ay + t * dy };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). */
|
|
266
|
+
function segmentTouchesRect(ax: number, ay: number, bx: number, by: number, r: Rect): boolean {
|
|
267
|
+
const xmin = r.x;
|
|
268
|
+
const xmax = r.x + r.width;
|
|
269
|
+
const ymin = r.y;
|
|
270
|
+
const ymax = r.y + r.height;
|
|
271
|
+
let t0 = 0;
|
|
272
|
+
let t1 = 1;
|
|
273
|
+
const dx = bx - ax;
|
|
274
|
+
const dy = by - ay;
|
|
275
|
+
const clip = (p: number, q: number): boolean => {
|
|
276
|
+
if (p === 0) return q >= 0;
|
|
277
|
+
const t = q / p;
|
|
278
|
+
if (p < 0) {
|
|
279
|
+
if (t > t1) return false;
|
|
280
|
+
if (t > t0) t0 = t;
|
|
281
|
+
} else {
|
|
282
|
+
if (t < t0) return false;
|
|
283
|
+
if (t < t1) t1 = t;
|
|
284
|
+
}
|
|
285
|
+
return true;
|
|
286
|
+
};
|
|
287
|
+
return clip(-dx, ax - xmin) && clip(dx, xmax - ax) && clip(-dy, ay - ymin) && clip(dy, ymax - ay);
|
|
288
|
+
}
|