@vitavision/stage2d 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,290 @@
1
+ /**
2
+ * A rotated rectangle or ellipse as an object: moved, resized from eight handles in its own
3
+ * frame, and turned from a rotation handle, on the image.
4
+ *
5
+ * The axis-aligned `RectRoiEditor` cannot hold a rotated bounding box or an ellipse fit, which
6
+ * is what an annotation tool and a detector's fitted marker are. The arithmetic is `shapeEdit.ts`;
7
+ * this is the gestures, the handles and the keyboard.
8
+ */
9
+
10
+ import { useRef, type KeyboardEvent, type PointerEvent, type SVGProps } from "react";
11
+
12
+ import type { Point } from "./measureGeometry";
13
+ import { overlayRole } from "./overlayRole";
14
+ import { ROI_HANDLES, type RoiHandle } from "./roiEdit";
15
+ import {
16
+ fromShapeFrame,
17
+ moveShape,
18
+ resizeShape,
19
+ rotateShape,
20
+ rotationHandlePoint,
21
+ shapeHandleCursor,
22
+ shapeHandlePoint,
23
+ type RotatedShape,
24
+ } from "./shapeEdit";
25
+ import { useStage } from "./stage/ImageStage";
26
+ import { useScreenPx } from "./stage/useScreenPx";
27
+ import { imageViewBox } from "./stage/view";
28
+
29
+ /** Handle square side, in screen pixels. */
30
+ const HANDLE_PX = 9;
31
+ /** Rotation handle radius, and its distance past the top side, in screen pixels. */
32
+ const ROTATE_RADIUS_PX = 5;
33
+ const ROTATE_OFFSET_PX = 24;
34
+ /** Outline width, in screen pixels. */
35
+ const STROKE_PX = 1.5;
36
+ /** The halo under the outline (visual-language §5), in screen pixels on each side. */
37
+ const HALO_PX = 1;
38
+ /** Shift while rotating rounds to this step, and `[` / `]` turn by 1° (15° with Shift). */
39
+ const SNAP = Math.PI / 12;
40
+ const KEY_TURN = Math.PI / 180;
41
+ const HALO = overlayRole("halo");
42
+
43
+ /** Props of `ShapeEditor`. */
44
+ export interface ShapeEditorProps {
45
+ /** `"rect"` draws a rotated rectangle, `"ellipse"` the ellipse inscribed in it. */
46
+ kind: "rect" | "ellipse";
47
+ /**
48
+ * The shape in image coordinates, or `null` for none. `rotation` is in **radians, clockwise
49
+ * on screen**, so a value in degrees (Konva's, say) is `degrees * Math.PI / 180`. An
50
+ * ellipse's `width` and `height` are its full axes, `2 · radiusX` and `2 · radiusY`.
51
+ */
52
+ value: RotatedShape | null;
53
+ /** Called with the shape as it changes: on every move of a drag, and on each key nudge. */
54
+ onValueChange: (value: RotatedShape) => void;
55
+ /** Called once a gesture ends (a drag released, a nudge made): the moment to save or re-run. */
56
+ onCommit?: ((value: RotatedShape) => void) | undefined;
57
+ /** Show handles and accept moves, resizes and rotations. Defaults to `true`. */
58
+ editable?: boolean | undefined;
59
+ /** Show the rotation handle and accept `[` / `]`. Defaults to `true`; off for a shape that must stay level. */
60
+ rotatable?: boolean | undefined;
61
+ /** The smallest extent on either axis, in image pixels. Defaults to 5. */
62
+ minSize?: number | undefined;
63
+ /** The shape's accessible name. Defaults to "Shape". */
64
+ label?: string | undefined;
65
+ /** CSS colour of the outline and handles. Defaults to the overlay `selection` role. */
66
+ stroke?: string | undefined;
67
+ }
68
+
69
+ type Drag =
70
+ | { kind: "move"; from: Point; start: RotatedShape; moved: boolean }
71
+ | { kind: "resize"; handle: RoiHandle; start: RotatedShape; moved: boolean }
72
+ | { kind: "rotate"; start: RotatedShape; moved: boolean };
73
+
74
+ /**
75
+ * An editable rotated rectangle or ellipse inside an `ImageStage`.
76
+ *
77
+ * - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the
78
+ * pointer and the opposite side stays where it is, whatever the rotation. A shape stops at
79
+ * `minSize` rather than flipping. The interior moves it.
80
+ * - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to
81
+ * round to 15°.
82
+ * - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),
83
+ * with Alt they grow or shrink it along its own axes from its top-left corner, and `[` / `]`
84
+ * turn it by 1° (15° with Shift).
85
+ * - **Rendering.** Handles and the outline are a constant size on screen at every zoom; an
86
+ * ellipse also shows its bounding box, where the handles are.
87
+ * - **Panning.** A press with the hand tool, or with space held, still pans.
88
+ *
89
+ * It does not draw a new shape (`DraftShape` previews one while the app's tool does), and does
90
+ * not keep the shape inside the image.
91
+ *
92
+ * The SVG carries `data-editable`; the outline carries `data-shape`.
93
+ */
94
+ export function ShapeEditor({
95
+ kind,
96
+ value,
97
+ onValueChange,
98
+ onCommit,
99
+ editable = true,
100
+ rotatable = true,
101
+ minSize = 5,
102
+ label = "Shape",
103
+ stroke = overlayRole("selection"),
104
+ }: ShapeEditorProps) {
105
+ const stage = useStage();
106
+ const px = useScreenPx();
107
+ const dragRef = useRef<Drag | null>(null);
108
+ const lastRef = useRef<RotatedShape | null>(null);
109
+
110
+ const report = (next: RotatedShape) => {
111
+ lastRef.current = next;
112
+ onValueChange(next);
113
+ };
114
+
115
+ const begin = (event: PointerEvent<SVGElement>, drag: Drag) => {
116
+ if (stage.panMode || event.button !== 0) return;
117
+ event.stopPropagation();
118
+ event.preventDefault();
119
+ event.currentTarget.setPointerCapture(event.pointerId);
120
+ dragRef.current = drag;
121
+ lastRef.current = null;
122
+ };
123
+
124
+ const onMove = (event: PointerEvent<SVGElement>) => {
125
+ const drag = dragRef.current;
126
+ if (!drag) return;
127
+ event.stopPropagation();
128
+ const p = stage.toImage({ x: event.clientX, y: event.clientY });
129
+ drag.moved = true;
130
+ if (drag.kind === "move") report(moveShape(drag.start, p.x - drag.from.x, p.y - drag.from.y));
131
+ else if (drag.kind === "resize") report(resizeShape(drag.start, drag.handle, p, minSize));
132
+ else report(rotateShape(drag.start, p, event.shiftKey ? SNAP : 0));
133
+ };
134
+
135
+ const onEnd = (event: PointerEvent<SVGElement>) => {
136
+ const drag = dragRef.current;
137
+ if (!drag) return;
138
+ event.stopPropagation();
139
+ dragRef.current = null;
140
+ if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
141
+ };
142
+
143
+ const onKeyDown = (event: KeyboardEvent<SVGElement>) => {
144
+ if (!editable || value === null) return;
145
+ const turn = rotatable && (event.key === "[" || event.key === "]");
146
+ if (turn) {
147
+ event.preventDefault();
148
+ event.stopPropagation();
149
+ const angle = (event.key === "]" ? 1 : -1) * (event.shiftKey ? SNAP : KEY_TURN);
150
+ const next = { ...value, rotation: value.rotation + angle };
151
+ onValueChange(next);
152
+ onCommit?.(next);
153
+ return;
154
+ }
155
+ const step = event.shiftKey ? 10 : 1;
156
+ const delta: Record<string, Point> = {
157
+ ArrowLeft: { x: -step, y: 0 },
158
+ ArrowRight: { x: step, y: 0 },
159
+ ArrowUp: { x: 0, y: -step },
160
+ ArrowDown: { x: 0, y: step },
161
+ };
162
+ const d = delta[event.key];
163
+ if (!d) return;
164
+ event.preventDefault();
165
+ event.stopPropagation();
166
+ // Alt grows from the top-left corner, along the shape's own axes, as `RectRoiEditor` does.
167
+ const next = event.altKey
168
+ ? resizeShape(value, "se", fromShapeFrame(value, { x: value.width / 2 + d.x, y: value.height / 2 + d.y }), minSize)
169
+ : moveShape(value, d.x, d.y);
170
+ onValueChange(next);
171
+ onCommit?.(next);
172
+ };
173
+
174
+ const stem = value ? { from: shapeHandlePoint(value, "n"), to: rotationHandlePoint(value, px(ROTATE_OFFSET_PX)) } : null;
175
+ const handleSize = px(HANDLE_PX);
176
+
177
+ return (
178
+ <svg
179
+ viewBox={imageViewBox(stage.image)}
180
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
181
+ data-editable={editable ? "" : undefined}
182
+ >
183
+ {value && <Outline kind={kind} shape={value} fill="none" stroke={HALO} strokeWidth={px(STROKE_PX + 2 * HALO_PX)} />}
184
+ {value && <Outline kind={kind} shape={value} data-shape={kind} fill={stroke} fillOpacity={0.12} stroke={stroke} strokeWidth={px(STROKE_PX)} />}
185
+ {kind === "ellipse" && value && (
186
+ <rect
187
+ x={value.cx - value.width / 2}
188
+ y={value.cy - value.height / 2}
189
+ width={value.width}
190
+ height={value.height}
191
+ transform={turned(value)}
192
+ fill="none"
193
+ stroke={stroke}
194
+ strokeWidth={px(1)}
195
+ strokeDasharray={`${px(4)} ${px(3)}`}
196
+ opacity={0.6}
197
+ />
198
+ )}
199
+ {editable && value && (
200
+ <Outline
201
+ kind={kind}
202
+ shape={value}
203
+ fill="transparent"
204
+ role="button"
205
+ tabIndex={0}
206
+ aria-label={`${label}: centre ${fmt(value.cx)}, ${fmt(value.cy)}, ${fmt(value.width)} × ${fmt(value.height)} px, rotated ${fmt((value.rotation * 180) / Math.PI)}°`}
207
+ aria-roledescription={kind === "rect" ? "rotated rectangle" : "ellipse"}
208
+ className="pointer-events-auto cursor-move outline-none focus-visible:stroke-signal"
209
+ onPointerDown={(event) =>
210
+ begin(event, { kind: "move", from: stage.toImage({ x: event.clientX, y: event.clientY }), start: value, moved: false })
211
+ }
212
+ onPointerMove={onMove}
213
+ onPointerUp={onEnd}
214
+ onLostPointerCapture={onEnd}
215
+ onKeyDown={onKeyDown}
216
+ onDoubleClick={(event) => event.stopPropagation()}
217
+ />
218
+ )}
219
+ {editable && value && rotatable && stem && (
220
+ <>
221
+ <line x1={stem.from.x} y1={stem.from.y} x2={stem.to.x} y2={stem.to.y} stroke={HALO} strokeWidth={px(1 + 2 * HALO_PX)} />
222
+ <line x1={stem.from.x} y1={stem.from.y} x2={stem.to.x} y2={stem.to.y} stroke={stroke} strokeWidth={px(1)} />
223
+ <circle
224
+ data-handle="rotate"
225
+ cx={stem.to.x}
226
+ cy={stem.to.y}
227
+ r={px(ROTATE_RADIUS_PX)}
228
+ fill={stroke}
229
+ stroke={HALO}
230
+ strokeWidth={px(1)}
231
+ className="pointer-events-auto"
232
+ style={{ cursor: "grab" }}
233
+ onPointerDown={(event) => begin(event, { kind: "rotate", start: value, moved: false })}
234
+ onPointerMove={onMove}
235
+ onPointerUp={onEnd}
236
+ onLostPointerCapture={onEnd}
237
+ onDoubleClick={(event) => event.stopPropagation()}
238
+ />
239
+ </>
240
+ )}
241
+ {editable &&
242
+ value &&
243
+ ROI_HANDLES.map((handle) => {
244
+ const centre = shapeHandlePoint(value, handle);
245
+ return (
246
+ <rect
247
+ key={handle}
248
+ data-handle={handle}
249
+ x={centre.x - handleSize / 2}
250
+ y={centre.y - handleSize / 2}
251
+ width={handleSize}
252
+ height={handleSize}
253
+ fill={stroke}
254
+ stroke={HALO}
255
+ strokeWidth={px(1)}
256
+ className="pointer-events-auto"
257
+ style={{ cursor: shapeHandleCursor(handle, value.rotation) }}
258
+ onPointerDown={(event) => begin(event, { kind: "resize", handle, start: value, moved: false })}
259
+ onPointerMove={onMove}
260
+ onPointerUp={onEnd}
261
+ onLostPointerCapture={onEnd}
262
+ onDoubleClick={(event) => event.stopPropagation()}
263
+ />
264
+ );
265
+ })}
266
+ </svg>
267
+ );
268
+ }
269
+
270
+ /** What the outline element takes: any SVG attribute, and `data-*`. */
271
+ type OutlineProps = Omit<SVGProps<SVGElement>, "ref"> & Record<`data-${string}`, string>;
272
+
273
+ /** The shape drawn level about its centre and turned by its rotation: a rectangle, or the ellipse inscribed in it. */
274
+ function Outline({ kind, shape, ...rest }: OutlineProps & { kind: "rect" | "ellipse"; shape: RotatedShape }) {
275
+ const transform = turned(shape);
276
+ return kind === "rect" ? (
277
+ <rect x={shape.cx - shape.width / 2} y={shape.cy - shape.height / 2} width={shape.width} height={shape.height} transform={transform} {...rest} />
278
+ ) : (
279
+ <ellipse cx={shape.cx} cy={shape.cy} rx={shape.width / 2} ry={shape.height / 2} transform={transform} {...rest} />
280
+ );
281
+ }
282
+
283
+ /** The SVG transform that turns a shape drawn level about its centre. */
284
+ function turned(shape: RotatedShape): string {
285
+ return `rotate(${(shape.rotation * 180) / Math.PI} ${shape.cx} ${shape.cy})`;
286
+ }
287
+
288
+ function fmt(value: number): string {
289
+ return Number.isInteger(value) ? String(value) : value.toFixed(1);
290
+ }
@@ -0,0 +1,361 @@
1
+ /**
2
+ * A spatial index over many closed polygons: which one is under the pointer, and which ones a
3
+ * rubber band touched.
4
+ *
5
+ * The same uniform grid as `polylineIndex.ts` and `pointIndex.ts` (CSR layout, built once per
6
+ * change of the items), but over each polygon's bounding box: a query looks at the polygons
7
+ * whose box is near the pointer and runs the exact tests (even-odd containment, distance to
8
+ * the outline) on those few only. It imports neither React nor the DOM.
9
+ *
10
+ * Polygons are flat `[x0, y0, x1, y1, …]` rings in image coordinates, implicitly closed. A
11
+ * ring with fewer than three vertices has no interior: it is still pickable along its outline
12
+ * (a two-vertex ring is a segment, a one-vertex ring a point), but never "inside".
13
+ */
14
+
15
+ import type { Point } from "./measureGeometry";
16
+ import { closestOnSegment, segmentTouchesRect } from "./polylineIndex";
17
+ import type { Rect } from "./stage/view";
18
+
19
+ /** An area's identity. */
20
+ export type AreaId = string | number;
21
+
22
+ /** One closed polygon. */
23
+ export interface Area {
24
+ /** Its identity, unique in the set. */
25
+ id: AreaId;
26
+ /** `[x0, y0, x1, y1, …]` in image coordinates; the last vertex joins the first. */
27
+ points: ArrayLike<number>;
28
+ }
29
+
30
+ /**
31
+ * An index built by `buildAreaIndex`. Treat it as opaque and query it with `nearestArea` and
32
+ * `areasInRect`; its layout may change.
33
+ */
34
+ export interface AreaIndex {
35
+ /** The areas, in the order given. */
36
+ readonly items: readonly Area[];
37
+ /** Per area, `[minX, minY, maxX, maxY]`; `NaN`s for an area with no finite vertex. */
38
+ readonly bounds: Float64Array;
39
+ /** Per area, its unsigned area (shoelace), used to prefer the smaller of nested areas. */
40
+ readonly size: Float64Array;
41
+ /** Grid cell side, in image pixels. */
42
+ readonly cell: number;
43
+ /** The grid's origin x. */
44
+ readonly x0: number;
45
+ /** The grid's origin y. */
46
+ readonly y0: number;
47
+ /** Grid columns. */
48
+ readonly cols: number;
49
+ /** Grid rows. */
50
+ readonly rows: number;
51
+ /** CSR layout: cell `c`'s entries are `entries[starts[c] .. starts[c + 1]]`. */
52
+ readonly starts: Uint32Array;
53
+ /** Area indices by cell. */
54
+ readonly entries: Uint32Array;
55
+ }
56
+
57
+ /** The area `nearestArea` picked. */
58
+ export interface AreaHit {
59
+ /** Its id. */
60
+ id: AreaId;
61
+ /** Its position in the array the index was built from. */
62
+ index: number;
63
+ /** Whether the query is inside the polygon (even-odd rule). */
64
+ inside: boolean;
65
+ /** The distance from the query to the polygon's outline, in image pixels. */
66
+ distance: number;
67
+ }
68
+
69
+ /** The most grid cells an index allocates, and the most area-to-cell entries. */
70
+ const MAX_CELLS = 4_000_000;
71
+ const MAX_ENTRIES = 8_000_000;
72
+
73
+ function vertexCount(points: ArrayLike<number>): number {
74
+ return Math.floor(points.length / 2);
75
+ }
76
+
77
+ /**
78
+ * Whether `(x, y)` is inside the polygon, by the even-odd rule.
79
+ *
80
+ * @param points - Flat ring, implicitly closed.
81
+ * @param x - The query's x.
82
+ * @param y - The query's y.
83
+ * @returns `false` for a ring with fewer than three vertices. A point exactly on the outline
84
+ * may be either; `nearestArea` treats the outline separately.
85
+ */
86
+ export function pointInPolygon(points: ArrayLike<number>, x: number, y: number): boolean {
87
+ const n = vertexCount(points);
88
+ if (n < 3) return false;
89
+ let inside = false;
90
+ for (let i = 0, j = n - 1; i < n; j = i++) {
91
+ const xi = points[2 * i]!;
92
+ const yi = points[2 * i + 1]!;
93
+ const xj = points[2 * j]!;
94
+ const yj = points[2 * j + 1]!;
95
+ if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
96
+ }
97
+ return inside;
98
+ }
99
+
100
+ /**
101
+ * The distance from `(x, y)` to the outline of a polygon (its closing edge included).
102
+ *
103
+ * @param points - Flat ring, implicitly closed.
104
+ * @param x - The query's x.
105
+ * @param y - The query's y.
106
+ * @returns The distance; `Infinity` for an empty ring.
107
+ */
108
+ export function distanceToOutline(points: ArrayLike<number>, x: number, y: number): number {
109
+ const n = vertexCount(points);
110
+ if (n === 0) return Infinity;
111
+ const p = { x, y };
112
+ let best = Infinity;
113
+ const edges = n === 1 ? 1 : n === 2 ? 1 : n;
114
+ for (let i = 0; i < edges; i++) {
115
+ const j = n === 1 ? 0 : (i + 1) % n;
116
+ const q = closestOnSegment(p, points[2 * i]!, points[2 * i + 1]!, points[2 * j]!, points[2 * j + 1]!);
117
+ const d = Math.hypot(q.x - x, q.y - y);
118
+ if (d < best) best = d;
119
+ }
120
+ return best;
121
+ }
122
+
123
+ /**
124
+ * The unsigned area of a polygon (shoelace).
125
+ *
126
+ * @param points - Flat ring, implicitly closed.
127
+ * @returns The area; `0` for fewer than three vertices.
128
+ */
129
+ export function polygonArea(points: ArrayLike<number>): number {
130
+ const n = vertexCount(points);
131
+ if (n < 3) return 0;
132
+ let sum = 0;
133
+ for (let i = 0, j = n - 1; i < n; j = i++) {
134
+ sum += points[2 * j]! * points[2 * i + 1]! - points[2 * i]! * points[2 * j + 1]!;
135
+ }
136
+ return Math.abs(sum) / 2;
137
+ }
138
+
139
+ /**
140
+ * A polygon as an SVG path (`M … L … Z`) from its first vertex, wound the same way whatever the
141
+ * input's winding.
142
+ * A batched path of overlapping polygons filled with the nonzero rule would otherwise cut a
143
+ * hole where a clockwise ring overlaps an anticlockwise one.
144
+ *
145
+ * @param points - Flat ring.
146
+ * @returns Path data; `""` with no vertices.
147
+ */
148
+ export function areaPath(points: ArrayLike<number>): string {
149
+ const n = vertexCount(points);
150
+ if (n === 0) return "";
151
+ let signed = 0;
152
+ for (let i = 0, j = n - 1; i < n; j = i++) signed += points[2 * j]! * points[2 * i + 1]! - points[2 * i]! * points[2 * j + 1]!;
153
+ const reversed = signed < 0;
154
+ const at = (k: number) => (reversed ? (n - k) % n : k); // still starts at vertex 0
155
+ let d = `M${points[2 * at(0)]} ${points[2 * at(0) + 1]}`;
156
+ if (n === 1) return `${d}h0`;
157
+ for (let k = 1; k < n; k++) d += `L${points[2 * at(k)]} ${points[2 * at(k) + 1]}`;
158
+ return `${d}Z`;
159
+ }
160
+
161
+ /**
162
+ * The centre a label is drawn at: the mean of the vertices.
163
+ *
164
+ * @param points - Flat ring.
165
+ * @returns The mean, or `null` for an empty ring.
166
+ */
167
+ export function areaCentre(points: ArrayLike<number>): Point | null {
168
+ const n = vertexCount(points);
169
+ if (n === 0) return null;
170
+ let sx = 0;
171
+ let sy = 0;
172
+ for (let i = 0; i < n; i++) {
173
+ sx += points[2 * i]!;
174
+ sy += points[2 * i + 1]!;
175
+ }
176
+ return { x: sx / n, y: sy / n };
177
+ }
178
+
179
+ /**
180
+ * Index a set of polygons.
181
+ *
182
+ * @param items - The polygons.
183
+ * @param cell - The grid cell side in image pixels. Defaults to the median of the polygons'
184
+ * larger bounding-box sides, within `[8, 256]`, doubled if the grid would be huge.
185
+ * @returns The index.
186
+ */
187
+ export function buildAreaIndex(items: readonly Area[], cell?: number): AreaIndex {
188
+ const count = items.length;
189
+ const bounds = new Float64Array(count * 4).fill(Number.NaN);
190
+ const size = new Float64Array(count);
191
+ let minX = Infinity;
192
+ let minY = Infinity;
193
+ let maxX = -Infinity;
194
+ let maxY = -Infinity;
195
+ const sides: number[] = [];
196
+ items.forEach((item, a) => {
197
+ const p = item.points;
198
+ let x0 = Infinity;
199
+ let y0 = Infinity;
200
+ let x1 = -Infinity;
201
+ let y1 = -Infinity;
202
+ for (let i = 0; i + 1 < p.length; i += 2) {
203
+ const x = p[i]!;
204
+ const y = p[i + 1]!;
205
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
206
+ if (x < x0) x0 = x;
207
+ if (x > x1) x1 = x;
208
+ if (y < y0) y0 = y;
209
+ if (y > y1) y1 = y;
210
+ }
211
+ if (!(x1 >= x0)) return;
212
+ bounds[4 * a] = x0;
213
+ bounds[4 * a + 1] = y0;
214
+ bounds[4 * a + 2] = x1;
215
+ bounds[4 * a + 3] = y1;
216
+ size[a] = polygonArea(p);
217
+ minX = Math.min(minX, x0);
218
+ minY = Math.min(minY, y0);
219
+ maxX = Math.max(maxX, x1);
220
+ maxY = Math.max(maxY, y1);
221
+ sides.push(Math.max(x1 - x0, y1 - y0));
222
+ });
223
+ if (sides.length === 0) {
224
+ return { items, bounds, size, cell: 1, x0: 0, y0: 0, cols: 1, rows: 1, starts: new Uint32Array(2), entries: new Uint32Array(0) };
225
+ }
226
+ sides.sort((a, b) => a - b);
227
+ let side = cell ?? Math.min(256, Math.max(8, sides[sides.length >> 1]!));
228
+ const width = maxX - minX;
229
+ const height = maxY - minY;
230
+ const cellsAt = (s: number) => (Math.floor(width / s) + 1) * (Math.floor(height / s) + 1);
231
+ const entriesAt = (s: number) => {
232
+ let total = 0;
233
+ for (let a = 0; a < count; a++) {
234
+ if (Number.isNaN(bounds[4 * a]!)) continue;
235
+ total += (Math.floor((bounds[4 * a + 2]! - bounds[4 * a]!) / s) + 1) * (Math.floor((bounds[4 * a + 3]! - bounds[4 * a + 1]!) / s) + 1);
236
+ }
237
+ return total;
238
+ };
239
+ // A pathological extent (one far outlier, a tiny `cell`) must not allocate a huge grid.
240
+ while (cellsAt(side) > MAX_CELLS || entriesAt(side) > MAX_ENTRIES) side *= 2;
241
+ const cols = Math.floor(width / side) + 1;
242
+ const rows = Math.floor(height / side) + 1;
243
+ const cellX = (x: number) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / side)));
244
+ const cellY = (y: number) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / side)));
245
+
246
+ // Two passes (count, then fill) into a CSR layout: no per-cell arrays.
247
+ const starts = new Uint32Array(cols * rows + 1);
248
+ const visit = (fn: (c: number, a: number) => void) => {
249
+ for (let a = 0; a < count; a++) {
250
+ if (Number.isNaN(bounds[4 * a]!)) continue;
251
+ const cx0 = cellX(bounds[4 * a]!);
252
+ const cx1 = cellX(bounds[4 * a + 2]!);
253
+ const cy0 = cellY(bounds[4 * a + 1]!);
254
+ const cy1 = cellY(bounds[4 * a + 3]!);
255
+ for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) fn(cy * cols + cx, a);
256
+ }
257
+ };
258
+ visit((c) => starts[c + 1]!++);
259
+ for (let c = 0; c < cols * rows; c++) starts[c + 1]! += starts[c]!;
260
+ const fill = starts.slice(0, cols * rows);
261
+ const entries = new Uint32Array(starts[cols * rows]!);
262
+ visit((c, a) => {
263
+ entries[fill[c]!++] = a;
264
+ });
265
+ return { items, bounds, size, cell: side, x0: minX, y0: minY, cols, rows, starts, entries };
266
+ }
267
+
268
+ /** Visit each distinct area whose bounding box meets `[left, right] × [top, bottom]`, ascending by index. */
269
+ function candidates(index: AreaIndex, left: number, top: number, right: number, bottom: number): number[] {
270
+ const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;
271
+ if (entries.length === 0) return [];
272
+ const cx0 = Math.max(0, Math.floor((left - x0) / cell));
273
+ const cx1 = Math.min(cols - 1, Math.floor((right - x0) / cell));
274
+ const cy0 = Math.max(0, Math.floor((top - y0) / cell));
275
+ const cy1 = Math.min(rows - 1, Math.floor((bottom - y0) / cell));
276
+ const seen = new Set<number>();
277
+ for (let cy = cy0; cy <= cy1; cy++) {
278
+ for (let cx = cx0; cx <= cx1; cx++) {
279
+ const c = cy * cols + cx;
280
+ for (let k = starts[c]!; k < starts[c + 1]!; k++) {
281
+ const a = entries[k]!;
282
+ if (seen.has(a)) continue;
283
+ if (bounds[4 * a]! <= right && bounds[4 * a + 2]! >= left && bounds[4 * a + 1]! <= bottom && bounds[4 * a + 3]! >= top) seen.add(a);
284
+ }
285
+ }
286
+ }
287
+ return [...seen].sort((a, b) => a - b);
288
+ }
289
+
290
+ /**
291
+ * The area under a point: one whose outline passes within `radius`, or else one that contains it.
292
+ *
293
+ * An outline is the more precise gesture, so it wins: among areas whose outline is within
294
+ * `radius` the nearest is picked, and only without one the containing area. Ties (equal
295
+ * distance, or several containing areas) go to the smaller area, so a quad drawn inside a
296
+ * region is picked rather than the region, then to the earlier one. The result does not depend
297
+ * on cell order.
298
+ *
299
+ * @param index - The index.
300
+ * @param p - The query, in image coordinates.
301
+ * @param radius - How far from an outline the query still picks it, in image pixels.
302
+ * @returns The area, or `null`.
303
+ */
304
+ export function nearestArea(index: AreaIndex, p: Point, radius: number): AreaHit | null {
305
+ if (!(radius >= 0)) return null;
306
+ const { items, size } = index;
307
+ let edge: AreaHit | null = null;
308
+ let inner: AreaHit | null = null;
309
+ for (const a of candidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
310
+ const points = items[a]!.points;
311
+ const distance = distanceToOutline(points, p.x, p.y);
312
+ const inside = pointInPolygon(points, p.x, p.y);
313
+ const hit: AreaHit = { id: items[a]!.id, index: a, inside, distance };
314
+ if (distance <= radius) {
315
+ if (edge === null || distance < edge.distance || (distance === edge.distance && size[a]! < size[edge.index]!)) edge = hit;
316
+ } else if (inside && (inner === null || size[a]! < size[inner.index]!)) {
317
+ inner = hit;
318
+ }
319
+ }
320
+ return edge ?? inner;
321
+ }
322
+
323
+ /**
324
+ * The areas any part of which is inside `rect`: a vertex, an edge crossing it, or the whole
325
+ * rectangle lying inside the polygon.
326
+ *
327
+ * @param index - The index.
328
+ * @param rect - The band, in image coordinates. A negative extent is read as the box between
329
+ * its corners.
330
+ * @returns Their ids, in the order the areas were given.
331
+ */
332
+ export function areasInRect(index: AreaIndex, rect: Rect): AreaId[] {
333
+ const box = {
334
+ x: Math.min(rect.x, rect.x + rect.width),
335
+ y: Math.min(rect.y, rect.y + rect.height),
336
+ width: Math.abs(rect.width),
337
+ height: Math.abs(rect.height),
338
+ };
339
+ const out: AreaId[] = [];
340
+ for (const a of candidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) {
341
+ if (polygonTouchesRect(index.items[a]!.points, box)) out.push(index.items[a]!.id);
342
+ }
343
+ return out;
344
+ }
345
+
346
+ function polygonTouchesRect(points: ArrayLike<number>, rect: Rect): boolean {
347
+ const n = vertexCount(points);
348
+ const right = rect.x + rect.width;
349
+ const bottom = rect.y + rect.height;
350
+ for (let i = 0; i < n; i++) {
351
+ const x = points[2 * i]!;
352
+ const y = points[2 * i + 1]!;
353
+ if (x >= rect.x && x <= right && y >= rect.y && y <= bottom) return true;
354
+ }
355
+ const edges = n < 2 ? 0 : n === 2 ? 1 : n;
356
+ for (let i = 0; i < edges; i++) {
357
+ const j = (i + 1) % n;
358
+ if (segmentTouchesRect(points[2 * i]!, points[2 * i + 1]!, points[2 * j]!, points[2 * j + 1]!, rect)) return true;
359
+ }
360
+ return pointInPolygon(points, rect.x, rect.y);
361
+ }