@vitavision/stage2d 0.9.0 → 0.11.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 +40 -4
- package/dist/index.d.ts +1001 -18
- package/dist/index.js +2643 -124
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/AreaSet.tsx +312 -0
- package/src/components/DraftShape.tsx +175 -0
- package/src/components/EllipseSet.tsx +292 -0
- package/src/components/GridLayer.tsx +209 -0
- package/src/components/HeatmapLayer.tsx +211 -0
- package/src/components/PointSet.tsx +16 -39
- package/src/components/PolylineSet.tsx +56 -15
- package/src/components/ShapeEditor.tsx +370 -0
- package/src/components/areaIndex.ts +364 -0
- package/src/components/ellipseIndex.ts +279 -0
- package/src/components/gridEdges.ts +70 -0
- package/src/components/heatmapRaster.ts +84 -0
- package/src/components/labelLod.ts +90 -0
- package/src/components/markerShapes.ts +3 -1
- package/src/components/polylineIndex.ts +4 -3
- package/src/components/shapeEdit.ts +298 -0
- package/src/components/stage/ImageStage.tsx +61 -20
- package/src/components/stage/StageSurface.tsx +80 -9
- package/src/components/stage/gesture.ts +15 -0
- package/src/components/stage/touchWatch.ts +85 -0
- package/src/components/stage/useCoarsePointer.ts +30 -0
- package/src/components/stage/view.ts +55 -14
- package/src/components/useShapeDrag.ts +104 -0
- package/src/index.ts +79 -0
|
@@ -0,0 +1,364 @@
|
|
|
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
|
+
/**
|
|
269
|
+
* The indices of the areas whose bounding box meets `[left, right] × [top, bottom]`, ascending.
|
|
270
|
+
* The first, cheap stage of every query; `ellipseIndex` reuses it over ellipse bounding boxes.
|
|
271
|
+
*/
|
|
272
|
+
export function areaCandidates(index: AreaIndex, left: number, top: number, right: number, bottom: number): number[] {
|
|
273
|
+
const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;
|
|
274
|
+
if (entries.length === 0) return [];
|
|
275
|
+
const cx0 = Math.max(0, Math.floor((left - x0) / cell));
|
|
276
|
+
const cx1 = Math.min(cols - 1, Math.floor((right - x0) / cell));
|
|
277
|
+
const cy0 = Math.max(0, Math.floor((top - y0) / cell));
|
|
278
|
+
const cy1 = Math.min(rows - 1, Math.floor((bottom - y0) / cell));
|
|
279
|
+
const seen = new Set<number>();
|
|
280
|
+
for (let cy = cy0; cy <= cy1; cy++) {
|
|
281
|
+
for (let cx = cx0; cx <= cx1; cx++) {
|
|
282
|
+
const c = cy * cols + cx;
|
|
283
|
+
for (let k = starts[c]!; k < starts[c + 1]!; k++) {
|
|
284
|
+
const a = entries[k]!;
|
|
285
|
+
if (seen.has(a)) continue;
|
|
286
|
+
if (bounds[4 * a]! <= right && bounds[4 * a + 2]! >= left && bounds[4 * a + 1]! <= bottom && bounds[4 * a + 3]! >= top) seen.add(a);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return [...seen].sort((a, b) => a - b);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* The area under a point: one whose outline passes within `radius`, or else one that contains it.
|
|
295
|
+
*
|
|
296
|
+
* An outline is the more precise gesture, so it wins: among areas whose outline is within
|
|
297
|
+
* `radius` the nearest is picked, and only without one the containing area. Ties (equal
|
|
298
|
+
* distance, or several containing areas) go to the smaller area, so a quad drawn inside a
|
|
299
|
+
* region is picked rather than the region, then to the earlier one. The result does not depend
|
|
300
|
+
* on cell order.
|
|
301
|
+
*
|
|
302
|
+
* @param index - The index.
|
|
303
|
+
* @param p - The query, in image coordinates.
|
|
304
|
+
* @param radius - How far from an outline the query still picks it, in image pixels.
|
|
305
|
+
* @returns The area, or `null`.
|
|
306
|
+
*/
|
|
307
|
+
export function nearestArea(index: AreaIndex, p: Point, radius: number): AreaHit | null {
|
|
308
|
+
if (!(radius >= 0)) return null;
|
|
309
|
+
const { items, size } = index;
|
|
310
|
+
let edge: AreaHit | null = null;
|
|
311
|
+
let inner: AreaHit | null = null;
|
|
312
|
+
for (const a of areaCandidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
|
|
313
|
+
const points = items[a]!.points;
|
|
314
|
+
const distance = distanceToOutline(points, p.x, p.y);
|
|
315
|
+
const inside = pointInPolygon(points, p.x, p.y);
|
|
316
|
+
const hit: AreaHit = { id: items[a]!.id, index: a, inside, distance };
|
|
317
|
+
if (distance <= radius) {
|
|
318
|
+
if (edge === null || distance < edge.distance || (distance === edge.distance && size[a]! < size[edge.index]!)) edge = hit;
|
|
319
|
+
} else if (inside && (inner === null || size[a]! < size[inner.index]!)) {
|
|
320
|
+
inner = hit;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return edge ?? inner;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The areas any part of which is inside `rect`: a vertex, an edge crossing it, or the whole
|
|
328
|
+
* rectangle lying inside the polygon.
|
|
329
|
+
*
|
|
330
|
+
* @param index - The index.
|
|
331
|
+
* @param rect - The band, in image coordinates. A negative extent is read as the box between
|
|
332
|
+
* its corners.
|
|
333
|
+
* @returns Their ids, in the order the areas were given.
|
|
334
|
+
*/
|
|
335
|
+
export function areasInRect(index: AreaIndex, rect: Rect): AreaId[] {
|
|
336
|
+
const box = {
|
|
337
|
+
x: Math.min(rect.x, rect.x + rect.width),
|
|
338
|
+
y: Math.min(rect.y, rect.y + rect.height),
|
|
339
|
+
width: Math.abs(rect.width),
|
|
340
|
+
height: Math.abs(rect.height),
|
|
341
|
+
};
|
|
342
|
+
const out: AreaId[] = [];
|
|
343
|
+
for (const a of areaCandidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) {
|
|
344
|
+
if (polygonTouchesRect(index.items[a]!.points, box)) out.push(index.items[a]!.id);
|
|
345
|
+
}
|
|
346
|
+
return out;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function polygonTouchesRect(points: ArrayLike<number>, rect: Rect): boolean {
|
|
350
|
+
const n = vertexCount(points);
|
|
351
|
+
const right = rect.x + rect.width;
|
|
352
|
+
const bottom = rect.y + rect.height;
|
|
353
|
+
for (let i = 0; i < n; i++) {
|
|
354
|
+
const x = points[2 * i]!;
|
|
355
|
+
const y = points[2 * i + 1]!;
|
|
356
|
+
if (x >= rect.x && x <= right && y >= rect.y && y <= bottom) return true;
|
|
357
|
+
}
|
|
358
|
+
const edges = n < 2 ? 0 : n === 2 ? 1 : n;
|
|
359
|
+
for (let i = 0; i < edges; i++) {
|
|
360
|
+
const j = (i + 1) % n;
|
|
361
|
+
if (segmentTouchesRect(points[2 * i]!, points[2 * i + 1]!, points[2 * j]!, points[2 * j + 1]!, rect)) return true;
|
|
362
|
+
}
|
|
363
|
+
return pointInPolygon(points, rect.x, rect.y);
|
|
364
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A spatial index over many ellipses: which one is under the pointer, and which ones a
|
|
3
|
+
* rubber band touched.
|
|
4
|
+
*
|
|
5
|
+
* The grid is `areaIndex.ts`'s (CSR layout over bounding boxes, built once per change of the
|
|
6
|
+
* items); a query runs the exact tests on the few ellipses whose box is near the pointer. The
|
|
7
|
+
* exact tests are in the ellipse's own frame: containment is one quadratic form, and the
|
|
8
|
+
* distance to the outline is the true Euclidean distance (a few Newton steps on the
|
|
9
|
+
* parametrisation), not a scaled approximation, so a thin ellipse is picked as precisely as a
|
|
10
|
+
* round one. It imports neither React nor the DOM.
|
|
11
|
+
*
|
|
12
|
+
* An ellipse with a non-finite value or a semi-axis not above zero is skipped: it has no
|
|
13
|
+
* outline to draw or to pick.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { areaCandidates, buildAreaIndex, type AreaIndex } from "./areaIndex";
|
|
17
|
+
import type { Point } from "./measureGeometry";
|
|
18
|
+
import type { Rect } from "./stage/view";
|
|
19
|
+
|
|
20
|
+
/** An ellipse's identity. */
|
|
21
|
+
export type EllipseId = string | number;
|
|
22
|
+
|
|
23
|
+
/** One ellipse. */
|
|
24
|
+
export interface Ellipse {
|
|
25
|
+
/** Its identity, unique in the set. */
|
|
26
|
+
id: EllipseId;
|
|
27
|
+
/** Centre x, image pixels. */
|
|
28
|
+
x: number;
|
|
29
|
+
/** Centre y, image pixels. */
|
|
30
|
+
y: number;
|
|
31
|
+
/** Semi-axis along the rotated x axis, image pixels. */
|
|
32
|
+
rx: number;
|
|
33
|
+
/** Semi-axis along the rotated y axis, image pixels. */
|
|
34
|
+
ry: number;
|
|
35
|
+
/** Rotation of the `rx` axis, radians clockwise on screen (y points down). Defaults to 0. */
|
|
36
|
+
angle?: number | undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* An index built by `buildEllipseIndex`. Treat it as opaque and query it with `nearestEllipse`
|
|
41
|
+
* and `ellipsesInRect`; its layout may change.
|
|
42
|
+
*/
|
|
43
|
+
export interface EllipseIndex {
|
|
44
|
+
/** The ellipses, in the order given. */
|
|
45
|
+
readonly items: readonly Ellipse[];
|
|
46
|
+
/** The grid over their bounding boxes (an `AreaIndex` of boxes, one per ellipse). */
|
|
47
|
+
readonly grid: AreaIndex;
|
|
48
|
+
/** Per ellipse, its area `π·rx·ry`, used to prefer the smaller of nested ellipses; `NaN` for a degenerate one. */
|
|
49
|
+
readonly size: Float64Array;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The ellipse `nearestEllipse` picked. */
|
|
53
|
+
export interface EllipseHit {
|
|
54
|
+
/** Its id. */
|
|
55
|
+
id: EllipseId;
|
|
56
|
+
/** Its position in the array the index was built from. */
|
|
57
|
+
index: number;
|
|
58
|
+
/** Whether the query is inside the ellipse. */
|
|
59
|
+
inside: boolean;
|
|
60
|
+
/** The distance from the query to the ellipse's outline, in image pixels (also when inside). */
|
|
61
|
+
distance: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function usable(e: Ellipse): boolean {
|
|
65
|
+
return e.rx > 0 && e.ry > 0 && Number.isFinite(e.x + e.y + e.rx + e.ry + (e.angle ?? 0));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The axis-aligned bounding box of an ellipse.
|
|
70
|
+
*
|
|
71
|
+
* @param e - The ellipse.
|
|
72
|
+
* @returns `[minX, minY, maxX, maxY]`, or `null` for a degenerate ellipse.
|
|
73
|
+
*/
|
|
74
|
+
export function ellipseBounds(e: Ellipse): [number, number, number, number] | null {
|
|
75
|
+
if (!usable(e)) return null;
|
|
76
|
+
const c = Math.cos(e.angle ?? 0);
|
|
77
|
+
const s = Math.sin(e.angle ?? 0);
|
|
78
|
+
const hx = Math.hypot(e.rx * c, e.ry * s);
|
|
79
|
+
const hy = Math.hypot(e.rx * s, e.ry * c);
|
|
80
|
+
return [e.x - hx, e.y - hy, e.x + hx, e.y + hy];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The query in the ellipse's frame: translated to its centre and rotated by `-angle`. */
|
|
84
|
+
function toFrame(e: Ellipse, x: number, y: number): Point {
|
|
85
|
+
const c = Math.cos(e.angle ?? 0);
|
|
86
|
+
const s = Math.sin(e.angle ?? 0);
|
|
87
|
+
const dx = x - e.x;
|
|
88
|
+
const dy = y - e.y;
|
|
89
|
+
return { x: c * dx + s * dy, y: -s * dx + c * dy };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Whether `(x, y)` is inside the ellipse (its outline counts as inside).
|
|
94
|
+
*
|
|
95
|
+
* @param e - The ellipse.
|
|
96
|
+
* @param x - The query's x.
|
|
97
|
+
* @param y - The query's y.
|
|
98
|
+
* @returns `false` for a degenerate ellipse.
|
|
99
|
+
*/
|
|
100
|
+
export function pointInEllipse(e: Ellipse, x: number, y: number): boolean {
|
|
101
|
+
if (!usable(e)) return false;
|
|
102
|
+
const p = toFrame(e, x, y);
|
|
103
|
+
return (p.x / e.rx) ** 2 + (p.y / e.ry) ** 2 <= 1;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Newton steps on the ellipse's parametrisation; enough to converge from the start below. */
|
|
107
|
+
const NEWTON_STEPS = 12;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The Euclidean distance from `(x, y)` to the outline of an ellipse.
|
|
111
|
+
*
|
|
112
|
+
* The query is folded into the first quadrant of the ellipse's frame and the nearest outline
|
|
113
|
+
* point found by Newton's method on the parameter `θ` of `(a·cos θ, b·sin θ)`, started from the
|
|
114
|
+
* better of a coarse scan so a thin ellipse and a query near its centre both converge.
|
|
115
|
+
*
|
|
116
|
+
* @param e - The ellipse.
|
|
117
|
+
* @param x - The query's x.
|
|
118
|
+
* @param y - The query's y.
|
|
119
|
+
* @returns The distance; `Infinity` for a degenerate ellipse.
|
|
120
|
+
*/
|
|
121
|
+
export function distanceToEllipse(e: Ellipse, x: number, y: number): number {
|
|
122
|
+
if (!usable(e)) return Infinity;
|
|
123
|
+
const p = toFrame(e, x, y);
|
|
124
|
+
const px = Math.abs(p.x);
|
|
125
|
+
const py = Math.abs(p.y);
|
|
126
|
+
const a = e.rx;
|
|
127
|
+
const b = e.ry;
|
|
128
|
+
const squared = (t: number) => (a * Math.cos(t) - px) ** 2 + (b * Math.sin(t) - py) ** 2;
|
|
129
|
+
// The squared distance can have two local minima in the quadrant (a query near the centre of
|
|
130
|
+
// a thin ellipse), so start from the best of a coarse scan, then polish.
|
|
131
|
+
let t = 0;
|
|
132
|
+
let best = Infinity;
|
|
133
|
+
const SCAN = 16;
|
|
134
|
+
for (let k = 0; k <= SCAN; k++) {
|
|
135
|
+
const candidate = (k / SCAN) * (Math.PI / 2);
|
|
136
|
+
const value = squared(candidate);
|
|
137
|
+
if (value < best) {
|
|
138
|
+
best = value;
|
|
139
|
+
t = candidate;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for (let i = 0; i < NEWTON_STEPS; i++) {
|
|
143
|
+
const c = Math.cos(t);
|
|
144
|
+
const s = Math.sin(t);
|
|
145
|
+
// f(θ) = d/dθ of half the squared distance; f' by differentiating again.
|
|
146
|
+
const f = (b * b - a * a) * s * c + a * px * s - b * py * c;
|
|
147
|
+
const df = (b * b - a * a) * (c * c - s * s) + a * px * c + b * py * s;
|
|
148
|
+
if (!(Math.abs(df) > 1e-12)) break;
|
|
149
|
+
const next = Math.min(Math.PI / 2, Math.max(0, t - f / df));
|
|
150
|
+
if (squared(next) > squared(t)) break; // a step that does not descend is noise
|
|
151
|
+
t = next;
|
|
152
|
+
}
|
|
153
|
+
return Math.sqrt(squared(t));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* An ellipse as an SVG path: two arcs, exactly, so it stays round at any zoom.
|
|
158
|
+
*
|
|
159
|
+
* @param cx - Centre x, image pixels.
|
|
160
|
+
* @param cy - Centre y, image pixels.
|
|
161
|
+
* @param rx - Semi-axis along the rotated x axis, image pixels.
|
|
162
|
+
* @param ry - Semi-axis along the rotated y axis, image pixels.
|
|
163
|
+
* @param angle - Rotation of the `rx` axis, radians clockwise on screen.
|
|
164
|
+
* @returns Path data, or `""` for a degenerate ellipse (a non-finite value, or a radius not above zero).
|
|
165
|
+
*/
|
|
166
|
+
export function ellipsePath(cx: number, cy: number, rx: number, ry: number, angle = 0): string {
|
|
167
|
+
if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return "";
|
|
168
|
+
const dx = rx * Math.cos(angle);
|
|
169
|
+
const dy = rx * Math.sin(angle);
|
|
170
|
+
const degrees = round((angle * 180) / Math.PI);
|
|
171
|
+
const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;
|
|
172
|
+
return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Round to 1/1000 of an image pixel. */
|
|
176
|
+
function round(value: number): number {
|
|
177
|
+
return Math.round(value * 1000) / 1000;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Index a set of ellipses.
|
|
182
|
+
*
|
|
183
|
+
* @param items - The ellipses.
|
|
184
|
+
* @param cell - The grid cell side in image pixels; see `buildAreaIndex` for the default.
|
|
185
|
+
* @returns The index.
|
|
186
|
+
*/
|
|
187
|
+
export function buildEllipseIndex(items: readonly Ellipse[], cell?: number): EllipseIndex {
|
|
188
|
+
const size = new Float64Array(items.length).fill(Number.NaN);
|
|
189
|
+
const boxes = items.map((item, i) => {
|
|
190
|
+
const box = ellipseBounds(item);
|
|
191
|
+
if (box === null) return { id: i, points: [] as number[] };
|
|
192
|
+
size[i] = Math.PI * item.rx * item.ry;
|
|
193
|
+
const [x0, y0, x1, y1] = box;
|
|
194
|
+
return { id: i, points: [x0, y0, x1, y0, x1, y1, x0, y1] };
|
|
195
|
+
});
|
|
196
|
+
return { items, grid: buildAreaIndex(boxes, cell), size };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The ellipse under a point: one whose outline passes within `radius`, or else one that
|
|
201
|
+
* contains it.
|
|
202
|
+
*
|
|
203
|
+
* An outline is the more precise gesture, so it wins: among ellipses whose outline is within
|
|
204
|
+
* `radius` the nearest is picked, and only without one the containing ellipse. Ties (equal
|
|
205
|
+
* distance, or several containing ellipses) go to the smaller ellipse, so a ring drawn inside
|
|
206
|
+
* another is picked rather than the outer one, then to the earlier one.
|
|
207
|
+
*
|
|
208
|
+
* @param index - The index.
|
|
209
|
+
* @param p - The query, in image coordinates.
|
|
210
|
+
* @param radius - How far from an outline the query still picks it, in image pixels.
|
|
211
|
+
* @returns The ellipse, or `null`.
|
|
212
|
+
*/
|
|
213
|
+
export function nearestEllipse(index: EllipseIndex, p: Point, radius: number): EllipseHit | null {
|
|
214
|
+
if (!(radius >= 0)) return null;
|
|
215
|
+
const { items, size } = index;
|
|
216
|
+
let edge: EllipseHit | null = null;
|
|
217
|
+
let inner: EllipseHit | null = null;
|
|
218
|
+
for (const a of areaCandidates(index.grid, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
|
|
219
|
+
const e = items[a]!;
|
|
220
|
+
const distance = distanceToEllipse(e, p.x, p.y);
|
|
221
|
+
const hit: EllipseHit = { id: e.id, index: a, inside: pointInEllipse(e, p.x, p.y), distance };
|
|
222
|
+
if (distance <= radius) {
|
|
223
|
+
if (edge === null || distance < edge.distance || (distance === edge.distance && size[a]! < size[edge.index]!)) edge = hit;
|
|
224
|
+
} else if (hit.inside && (inner === null || size[a]! < size[inner.index]!)) {
|
|
225
|
+
inner = hit;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return edge ?? inner;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The ellipses any part of which is inside `rect`: the rectangle meets the outline, or lies
|
|
233
|
+
* inside the ellipse, or contains it.
|
|
234
|
+
*
|
|
235
|
+
* @param index - The index.
|
|
236
|
+
* @param rect - The band, in image coordinates. A negative extent is read as the box between
|
|
237
|
+
* its corners.
|
|
238
|
+
* @returns Their ids, in the order the ellipses were given.
|
|
239
|
+
*/
|
|
240
|
+
export function ellipsesInRect(index: EllipseIndex, rect: Rect): EllipseId[] {
|
|
241
|
+
const x0 = Math.min(rect.x, rect.x + rect.width);
|
|
242
|
+
const y0 = Math.min(rect.y, rect.y + rect.height);
|
|
243
|
+
const x1 = Math.max(rect.x, rect.x + rect.width);
|
|
244
|
+
const y1 = Math.max(rect.y, rect.y + rect.height);
|
|
245
|
+
const out: EllipseId[] = [];
|
|
246
|
+
for (const a of areaCandidates(index.grid, x0, y0, x1, y1)) {
|
|
247
|
+
const e = index.items[a]!;
|
|
248
|
+
if (rectMeetsEllipse(e, x0, y0, x1, y1)) out.push(e.id);
|
|
249
|
+
}
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Whether the filled ellipse and the rectangle share a point (both convex). */
|
|
254
|
+
function rectMeetsEllipse(e: Ellipse, x0: number, y0: number, x1: number, y1: number): boolean {
|
|
255
|
+
// The rectangle contains the ellipse (its centre is inside), the ellipse contains a corner,
|
|
256
|
+
// or an edge crosses the ellipse with both end points outside it: the three ways two convex
|
|
257
|
+
// shapes meet.
|
|
258
|
+
if (e.x >= x0 && e.x <= x1 && e.y >= y0 && e.y <= y1) return true;
|
|
259
|
+
const corners: Point[] = [
|
|
260
|
+
{ x: x0, y: y0 },
|
|
261
|
+
{ x: x1, y: y0 },
|
|
262
|
+
{ x: x1, y: y1 },
|
|
263
|
+
{ x: x0, y: y1 },
|
|
264
|
+
];
|
|
265
|
+
if (corners.some((c) => pointInEllipse(e, c.x, c.y))) return true;
|
|
266
|
+
// Minimise the ellipse's quadratic form along each edge, in the ellipse's frame.
|
|
267
|
+
for (let k = 0; k < 4; k++) {
|
|
268
|
+
const a = toFrame(e, corners[k]!.x, corners[k]!.y);
|
|
269
|
+
const b = toFrame(e, corners[(k + 1) % 4]!.x, corners[(k + 1) % 4]!.y);
|
|
270
|
+
const ux = (b.x - a.x) / e.rx;
|
|
271
|
+
const uy = (b.y - a.y) / e.ry;
|
|
272
|
+
const vx = a.x / e.rx;
|
|
273
|
+
const vy = a.y / e.ry;
|
|
274
|
+
const len2 = ux * ux + uy * uy;
|
|
275
|
+
const t = len2 > 0 ? Math.min(1, Math.max(0, -(ux * vx + uy * vy) / len2)) : 0;
|
|
276
|
+
if ((vx + t * ux) ** 2 + (vy + t * uy) ** 2 <= 1) return true;
|
|
277
|
+
}
|
|
278
|
+
return false;
|
|
279
|
+
}
|