@vitavision/stage2d 0.8.0 → 0.9.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,320 @@
1
+ /**
2
+ * A spatial index over many points: which one is under the pointer, which ones a rubber band
3
+ * caught, and which ones are far enough apart to carry a label.
4
+ *
5
+ * The same uniform grid as `polylineIndex.ts`, in CSR layout (cell `c`'s entries are
6
+ * `starts[c] .. starts[c + 1]`, no per-cell arrays), generalised from the L0-3 benchmark's
7
+ * `grid.ts`. It answers in microseconds whichever engine draws the markers
8
+ * (`docs/measurements/stage2d-bench-analysis.md`), and it imports neither React nor the DOM.
9
+ *
10
+ * Points are flat `[x0, y0, x1, y1, …]` arrays in image coordinates, the form a detector
11
+ * returns and the cheapest to keep. A point with a non-finite coordinate is not indexed.
12
+ */
13
+
14
+ import type { Rect } from "./stage/view";
15
+
16
+ /** A point's identity. */
17
+ export type PointId = string | number;
18
+
19
+ /** The shape `buildPointIndexFrom` reads from each item. */
20
+ export interface PointItem {
21
+ /** Its identity, unique in the set. */
22
+ id: PointId;
23
+ /** Horizontal position, in image coordinates. */
24
+ x: number;
25
+ /** Vertical position, in image coordinates. */
26
+ y: number;
27
+ /** How far from the point a query still picks it, in image pixels. Defaults to `0`. */
28
+ pickRadius?: number | undefined;
29
+ }
30
+
31
+ /** Options of `buildPointIndex`. */
32
+ export interface PointIndexOptions {
33
+ /** Ids by point index. Defaults to the index itself. */
34
+ ids?: ArrayLike<PointId> | undefined;
35
+ /**
36
+ * Per-point pick radius, in image pixels. A query at distance `d` from point `i` picks it
37
+ * when `d ≤ radius + radii[i]`, so a ring marker whose circle is data (it scales with the
38
+ * image) can be picked anywhere on it. Defaults to `0` for every point.
39
+ */
40
+ radii?: ArrayLike<number> | undefined;
41
+ /**
42
+ * The grid cell side, in image pixels. Defaults to a side that puts about two points in
43
+ * each cell, bounded to `[4, 256]`.
44
+ */
45
+ cell?: number | undefined;
46
+ }
47
+
48
+ /**
49
+ * An index built by `buildPointIndex`. Treat it as opaque and query it with `nearestPoint`,
50
+ * `pointsInRect` and `thinPoints`; its layout may change.
51
+ */
52
+ export interface PointIndex {
53
+ /** The number of points given, indexed or not. */
54
+ readonly count: number;
55
+ /** The points, flat `[x0, y0, …]`. Not copied: do not change it after building. */
56
+ readonly xy: ArrayLike<number>;
57
+ /** Ids by point index, or `null` when a point's id is its index. */
58
+ readonly ids: ArrayLike<PointId> | null;
59
+ /** Per-point pick radii, or `null` when every point has none. */
60
+ readonly radii: ArrayLike<number> | null;
61
+ /** The largest pick radius, widening every query window. */
62
+ readonly maxRadius: number;
63
+ /** Grid cell side, in image pixels. */
64
+ readonly cell: number;
65
+ /** The grid's origin x. */
66
+ readonly x0: number;
67
+ /** The grid's origin y. */
68
+ readonly y0: number;
69
+ /** Grid columns. */
70
+ readonly cols: number;
71
+ /** Grid rows. */
72
+ readonly rows: number;
73
+ /** CSR layout: cell `c`'s entries are `items[starts[c] .. starts[c + 1]]`. */
74
+ readonly starts: Uint32Array;
75
+ /** Point indices by cell, ascending within a cell. */
76
+ readonly items: Uint32Array;
77
+ }
78
+
79
+ /** The nearest point to a query. */
80
+ export interface PointHit {
81
+ /** Its index in the array the index was built from. */
82
+ index: number;
83
+ /** Its id. */
84
+ id: PointId;
85
+ /** The distance from the query to the point's centre, in image pixels. */
86
+ dist: number;
87
+ }
88
+
89
+ /** The most grid cells an index allocates, whatever the cell side asks for. */
90
+ const MAX_CELLS = 4_000_000;
91
+
92
+ /**
93
+ * Index a set of points.
94
+ *
95
+ * @param xy - Flat `[x0, y0, x1, y1, …]` in image coordinates; a `Float32Array` or
96
+ * `Float64Array` avoids a copy at the call site.
97
+ * @param options - Ids, per-point pick radii and the cell side.
98
+ * @returns The index.
99
+ */
100
+ export function buildPointIndex(xy: ArrayLike<number>, options: PointIndexOptions = {}): PointIndex {
101
+ const count = Math.floor(xy.length / 2);
102
+ const ids = options.ids ?? null;
103
+ const radii = options.radii ?? null;
104
+ let minX = Infinity;
105
+ let minY = Infinity;
106
+ let maxX = -Infinity;
107
+ let maxY = -Infinity;
108
+ let maxRadius = 0;
109
+ let live = 0;
110
+ for (let i = 0; i < count; i++) {
111
+ const x = xy[2 * i]!;
112
+ const y = xy[2 * i + 1]!;
113
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
114
+ live++;
115
+ if (x < minX) minX = x;
116
+ if (x > maxX) maxX = x;
117
+ if (y < minY) minY = y;
118
+ if (y > maxY) maxY = y;
119
+ if (radii) {
120
+ const r = radii[i]!;
121
+ if (r > maxRadius) maxRadius = r;
122
+ }
123
+ }
124
+ if (live === 0) {
125
+ return {
126
+ count, xy, ids: ids, radii, maxRadius, cell: 1, x0: 0, y0: 0, cols: 1, rows: 1,
127
+ starts: new Uint32Array(2), items: new Uint32Array(0),
128
+ };
129
+ }
130
+
131
+ const width = maxX - minX;
132
+ const height = maxY - minY;
133
+ let cell = options.cell ?? Math.min(256, Math.max(4, Math.sqrt((Math.max(width, 1) * Math.max(height, 1) * 2) / live)));
134
+ // A pathological extent (one far outlier, a tiny `cell`) must not allocate a huge grid.
135
+ while ((Math.floor(width / cell) + 1) * (Math.floor(height / cell) + 1) > MAX_CELLS) cell *= 2;
136
+ const cols = Math.floor(width / cell) + 1;
137
+ const rows = Math.floor(height / cell) + 1;
138
+ const cellOf = new Int32Array(count).fill(-1);
139
+ const starts = new Uint32Array(cols * rows + 1);
140
+ for (let i = 0; i < count; i++) {
141
+ const x = xy[2 * i]!;
142
+ const y = xy[2 * i + 1]!;
143
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
144
+ const c = Math.min(rows - 1, Math.floor((y - minY) / cell)) * cols + Math.min(cols - 1, Math.floor((x - minX) / cell));
145
+ cellOf[i] = c;
146
+ starts[c + 1]!++;
147
+ }
148
+ for (let c = 0; c < cols * rows; c++) starts[c + 1]! += starts[c]!;
149
+ const fill = starts.slice(0, cols * rows);
150
+ const items = new Uint32Array(live);
151
+ for (let i = 0; i < count; i++) {
152
+ const c = cellOf[i]!;
153
+ if (c >= 0) items[fill[c]!++] = i;
154
+ }
155
+ return { count, xy, ids: ids, radii, maxRadius, cell, x0: minX, y0: minY, cols, rows, starts, items };
156
+ }
157
+
158
+ /**
159
+ * Index items that carry their own position.
160
+ *
161
+ * @param items - The points, in order.
162
+ * @param cell - The grid cell side; see `PointIndexOptions`.
163
+ * @returns The index; its point indices are positions in `items`.
164
+ */
165
+ export function buildPointIndexFrom(items: readonly PointItem[], cell?: number): PointIndex {
166
+ const xy = new Float64Array(items.length * 2);
167
+ const ids: PointId[] = new Array<PointId>(items.length);
168
+ let radii: Float64Array | undefined;
169
+ items.forEach((item, i) => {
170
+ xy[2 * i] = item.x;
171
+ xy[2 * i + 1] = item.y;
172
+ ids[i] = item.id;
173
+ if (item.pickRadius !== undefined && item.pickRadius > 0) {
174
+ radii ??= new Float64Array(items.length);
175
+ radii[i] = item.pickRadius;
176
+ }
177
+ });
178
+ return buildPointIndex(xy, { ids, radii, cell });
179
+ }
180
+
181
+ /**
182
+ * The point nearest to `(x, y)` whose pick disc reaches it, or `null`.
183
+ *
184
+ * @param index - The index.
185
+ * @param x - The query's x, in image coordinates.
186
+ * @param y - The query's y, in image coordinates.
187
+ * @param radius - How far from a point's centre the query still picks it, in image pixels.
188
+ * For a screen-constant tolerance, pass `useScreenPx()(css)`. A point's own `radii` entry
189
+ * adds to it.
190
+ * @returns The point nearest by centre distance; ties go to the lower index, so the result
191
+ * does not depend on cell order.
192
+ */
193
+ export function nearestPoint(index: PointIndex, x: number, y: number, radius: number): PointHit | null {
194
+ if (!(radius >= 0) || index.items.length === 0) return null;
195
+ const { cell, x0, y0, cols, rows, starts, items, xy, radii, maxRadius } = index;
196
+ const reach = radius + maxRadius;
197
+ const cx0 = Math.max(0, Math.floor((x - reach - x0) / cell));
198
+ const cx1 = Math.min(cols - 1, Math.floor((x + reach - x0) / cell));
199
+ const cy0 = Math.max(0, Math.floor((y - reach - y0) / cell));
200
+ const cy1 = Math.min(rows - 1, Math.floor((y + reach - y0) / cell));
201
+ let best = -1;
202
+ let bestD = Infinity;
203
+ for (let cy = cy0; cy <= cy1; cy++) {
204
+ for (let cx = cx0; cx <= cx1; cx++) {
205
+ const c = cy * cols + cx;
206
+ for (let k = starts[c]!; k < starts[c + 1]!; k++) {
207
+ const i = items[k]!;
208
+ const dx = xy[2 * i]! - x;
209
+ const dy = xy[2 * i + 1]! - y;
210
+ const d = dx * dx + dy * dy;
211
+ const reachI = radii ? radius + radii[i]! : radius;
212
+ if (d <= reachI * reachI && (d < bestD || (d === bestD && i < best))) {
213
+ bestD = d;
214
+ best = i;
215
+ }
216
+ }
217
+ }
218
+ }
219
+ return best < 0 ? null : { index: best, id: index.ids ? index.ids[best]! : best, dist: Math.sqrt(bestD) };
220
+ }
221
+
222
+ /**
223
+ * The points whose centre is inside `rect`, edges included.
224
+ *
225
+ * @param index - The index.
226
+ * @param rect - The band, in image coordinates. A negative extent is read as the box
227
+ * between its corners.
228
+ * @returns Their indices, ascending.
229
+ */
230
+ export function pointsInRect(index: PointIndex, rect: Rect): number[] {
231
+ if (index.items.length === 0) return [];
232
+ const { cell, x0, y0, cols, rows, starts, items, xy } = index;
233
+ const left = Math.min(rect.x, rect.x + rect.width);
234
+ const right = Math.max(rect.x, rect.x + rect.width);
235
+ const top = Math.min(rect.y, rect.y + rect.height);
236
+ const bottom = Math.max(rect.y, rect.y + rect.height);
237
+ const cx0 = Math.max(0, Math.floor((left - x0) / cell));
238
+ const cx1 = Math.min(cols - 1, Math.floor((right - x0) / cell));
239
+ const cy0 = Math.max(0, Math.floor((top - y0) / cell));
240
+ const cy1 = Math.min(rows - 1, Math.floor((bottom - y0) / cell));
241
+ const found: number[] = [];
242
+ for (let cy = cy0; cy <= cy1; cy++) {
243
+ for (let cx = cx0; cx <= cx1; cx++) {
244
+ const c = cy * cols + cx;
245
+ for (let k = starts[c]!; k < starts[c + 1]!; k++) {
246
+ const i = items[k]!;
247
+ const px = xy[2 * i]!;
248
+ const py = xy[2 * i + 1]!;
249
+ if (px >= left && px <= right && py >= top && py <= bottom) found.push(i);
250
+ }
251
+ }
252
+ }
253
+ return found.sort((a, b) => a - b);
254
+ }
255
+
256
+ /**
257
+ * A greedy thinning: walk the points in `order` and keep each one that is at least `minDist`
258
+ * from every point kept so far. This is how a label layer decides which labels the zoom has
259
+ * room for.
260
+ *
261
+ * The result is *maximal*: every point left out is within `minDist` of one kept before it,
262
+ * and every pair kept is at least `minDist` apart.
263
+ *
264
+ * @param xy - Flat points, in the units `minDist` is in (image pixels for a screen-px spacing
265
+ * converted with `useScreenPx`).
266
+ * @param minDist - The least distance between two kept points.
267
+ * @param order - Point indices in priority order. Defaults to every point, in order.
268
+ * Indices of non-finite points are skipped.
269
+ * @returns The kept indices, in the order they were kept.
270
+ */
271
+ export function thinPoints(xy: ArrayLike<number>, minDist: number, order?: Iterable<number>): number[] {
272
+ const kept: number[] = [];
273
+ if (!(minDist > 0)) {
274
+ for (const i of order ?? range(Math.floor(xy.length / 2))) if (isLive(xy, i)) kept.push(i);
275
+ return kept;
276
+ }
277
+ // Cells of side `minDist`: any kept point closer than `minDist` is in the 3×3 block around
278
+ // the candidate's cell. The cell only bounds the search; the check compares true distances.
279
+ // A key can alias for coordinates beyond ±2²¹ cells, which only adds candidates to a scan.
280
+ const cells = new Map<number, number[]>();
281
+ const key = (cx: number, cy: number) => cy * 4_194_304 + cx;
282
+ const limit = minDist * minDist;
283
+ for (const i of order ?? range(Math.floor(xy.length / 2))) {
284
+ if (!isLive(xy, i)) continue;
285
+ const x = xy[2 * i]!;
286
+ const y = xy[2 * i + 1]!;
287
+ const cx = Math.floor(x / minDist);
288
+ const cy = Math.floor(y / minDist);
289
+ let clear = true;
290
+ scan: for (let dy = -1; dy <= 1; dy++) {
291
+ for (let dx = -1; dx <= 1; dx++) {
292
+ const bucket = cells.get(key(cx + dx, cy + dy));
293
+ if (!bucket) continue;
294
+ for (const j of bucket) {
295
+ const ex = xy[2 * j]! - x;
296
+ const ey = xy[2 * j + 1]! - y;
297
+ if (ex * ex + ey * ey < limit) {
298
+ clear = false;
299
+ break scan;
300
+ }
301
+ }
302
+ }
303
+ }
304
+ if (!clear) continue;
305
+ kept.push(i);
306
+ const k = key(cx, cy);
307
+ const bucket = cells.get(k);
308
+ if (bucket) bucket.push(i);
309
+ else cells.set(k, [i]);
310
+ }
311
+ return kept;
312
+ }
313
+
314
+ function isLive(xy: ArrayLike<number>, i: number): boolean {
315
+ return Number.isFinite(xy[2 * i]) && Number.isFinite(xy[2 * i + 1]);
316
+ }
317
+
318
+ function* range(n: number): Generator<number> {
319
+ for (let i = 0; i < n; i++) yield i;
320
+ }