@vitavision/stage2d 0.8.1 → 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.
- package/README.md +41 -0
- package/dist/index.d.ts +1083 -3
- package/dist/index.js +2815 -68
- 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/GridLayer.tsx +209 -0
- package/src/components/HeatmapLayer.tsx +211 -0
- package/src/components/PointSet.tsx +366 -0
- package/src/components/PolylineSet.tsx +39 -0
- package/src/components/ShapeEditor.tsx +290 -0
- package/src/components/areaIndex.ts +361 -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 +119 -0
- package/src/components/pointIndex.ts +320 -0
- package/src/components/polylineIndex.ts +4 -3
- package/src/components/shapeEdit.ts +232 -0
- package/src/components/stage/ImageStage.tsx +264 -59
- package/src/components/stage/gesture.ts +81 -0
- package/src/components/stage/hitContext.ts +16 -0
- package/src/components/stage/hitTest.ts +181 -0
- package/src/components/stage/useStageHitTest.ts +127 -0
- package/src/components/useShapeDrag.ts +104 -0
- package/src/index.ts +96 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The edges of a detected lattice: which nodes are neighbours.
|
|
3
|
+
*
|
|
4
|
+
* A calibration detector returns its corners with integer lattice indices `(i, j)` and gaps
|
|
5
|
+
* where a corner was not found. The edges are not data: node `(i, j)` is joined to
|
|
6
|
+
* `(i + 1, j)` and to `(i, j + 1)` when both exist. This module computes them in O(n) with a
|
|
7
|
+
* hash of the indices. It imports neither React nor the DOM.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** What `latticeEdges` reads from each node. */
|
|
11
|
+
export interface LatticeNode {
|
|
12
|
+
/** The lattice index along the first axis. A non-integer index is not part of the lattice. */
|
|
13
|
+
i: number;
|
|
14
|
+
/** The lattice index along the second axis. A non-integer index is not part of the lattice. */
|
|
15
|
+
j: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The lattice axis an edge runs along: `"i"` joins `(i, j)` to `(i + 1, j)`, `"j"` joins `(i, j)` to `(i, j + 1)`. */
|
|
19
|
+
export type LatticeAxis = "i" | "j";
|
|
20
|
+
|
|
21
|
+
/** An edge between two neighbouring nodes. */
|
|
22
|
+
export interface LatticeEdge {
|
|
23
|
+
/** Position in the node array of the end with the lower index along `axis`. */
|
|
24
|
+
a: number;
|
|
25
|
+
/** Position in the node array of the end with the higher index along `axis`. */
|
|
26
|
+
b: number;
|
|
27
|
+
/** The axis it runs along. */
|
|
28
|
+
axis: LatticeAxis;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Indices past this magnitude are not hashed (the key must stay an exact integer). */
|
|
32
|
+
const LIMIT = 2 ** 25;
|
|
33
|
+
|
|
34
|
+
function key(i: number, j: number): number {
|
|
35
|
+
return (i + LIMIT) * (2 * LIMIT) + (j + LIMIT);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The edges of a lattice: every pair of nodes whose indices differ by one along exactly one
|
|
40
|
+
* axis.
|
|
41
|
+
*
|
|
42
|
+
* @param nodes - The nodes, in any order, with gaps allowed. A node whose index is not an
|
|
43
|
+
* integer of magnitude below 2²⁵ takes no edges, and when two nodes share an index the
|
|
44
|
+
* first one is the lattice's node there.
|
|
45
|
+
* @returns The edges, ordered by the position of `a`, then `"i"` before `"j"`.
|
|
46
|
+
*/
|
|
47
|
+
export function latticeEdges(nodes: ArrayLike<LatticeNode>): LatticeEdge[] {
|
|
48
|
+
const at = new Map<number, number>();
|
|
49
|
+
const valid = (n: LatticeNode) => Number.isInteger(n.i) && Number.isInteger(n.j) && Math.abs(n.i) < LIMIT && Math.abs(n.j) < LIMIT;
|
|
50
|
+
for (let p = 0; p < nodes.length; p++) {
|
|
51
|
+
const node = nodes[p]!;
|
|
52
|
+
if (!valid(node)) continue;
|
|
53
|
+
const k = key(node.i, node.j);
|
|
54
|
+
if (!at.has(k)) at.set(k, p);
|
|
55
|
+
}
|
|
56
|
+
const edges: LatticeEdge[] = [];
|
|
57
|
+
for (let p = 0; p < nodes.length; p++) {
|
|
58
|
+
const node = nodes[p]!;
|
|
59
|
+
if (!valid(node) || at.get(key(node.i, node.j)) !== p) continue;
|
|
60
|
+
if (node.i + 1 < LIMIT) {
|
|
61
|
+
const q = at.get(key(node.i + 1, node.j));
|
|
62
|
+
if (q !== undefined) edges.push({ a: p, b: q, axis: "i" });
|
|
63
|
+
}
|
|
64
|
+
if (node.j + 1 < LIMIT) {
|
|
65
|
+
const q = at.get(key(node.i, node.j + 1));
|
|
66
|
+
if (q !== undefined) edges.push({ a: p, b: q, axis: "j" });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return edges;
|
|
70
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scalar field to pixels: the colourising step of `HeatmapLayer`, pure so the cases that bite
|
|
3
|
+
* (NaN holes, a flat field, a value outside the range) are tested without a canvas.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { ValuePlane } from "../api/mapValues";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A sequential colour map: a position in `[0, 1]` to an `[r, g, b]` colour, each channel
|
|
10
|
+
* 0 to 255. `@vitavision/charts`' `colormapRgb(name, t)` is one: `(t) => colormapRgb("viridis", t)`.
|
|
11
|
+
*/
|
|
12
|
+
export type Colormap = (t: number) => readonly [number, number, number];
|
|
13
|
+
|
|
14
|
+
/** A range of values mapped onto the colour map: `low` to its start, `high` to its end. */
|
|
15
|
+
export interface ValueRange {
|
|
16
|
+
/** The value drawn in the map's first colour. */
|
|
17
|
+
low: number;
|
|
18
|
+
/** The value drawn in the map's last colour. */
|
|
19
|
+
high: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** How many steps the colour map is sampled at: one per 8-bit level, so no pixel is off by a visible amount. */
|
|
23
|
+
const STEPS = 256;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The extent of a plane's finite values.
|
|
27
|
+
*
|
|
28
|
+
* @param plane - The plane.
|
|
29
|
+
* @param channel - Which of its channels. Defaults to the first.
|
|
30
|
+
* @returns `{ low, high }`, or `null` when the channel is missing or has no finite value.
|
|
31
|
+
*/
|
|
32
|
+
export function planeRange(plane: ValuePlane, channel = 0): ValueRange | null {
|
|
33
|
+
if (!(channel >= 0 && channel < plane.channels)) return null;
|
|
34
|
+
const size = plane.width * plane.height;
|
|
35
|
+
const offset = channel * size;
|
|
36
|
+
let low = Infinity;
|
|
37
|
+
let high = -Infinity;
|
|
38
|
+
for (let k = 0; k < size; k++) {
|
|
39
|
+
const v = plane.values[offset + k]!;
|
|
40
|
+
if (!Number.isFinite(v)) continue;
|
|
41
|
+
if (v < low) low = v;
|
|
42
|
+
if (v > high) high = v;
|
|
43
|
+
}
|
|
44
|
+
return low <= high ? { low, high } : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Colour a plane through a colour map.
|
|
49
|
+
*
|
|
50
|
+
* Opaque where the value is finite; transparent where it is `NaN` or infinite (an uncovered
|
|
51
|
+
* pixel, as in `valueAt`). Values outside `range` take the map's end colours. A flat range
|
|
52
|
+
* (`high <= low`) draws every pixel in the map's first colour.
|
|
53
|
+
*
|
|
54
|
+
* @param plane - The plane.
|
|
55
|
+
* @param colormap - The colour map; sampled at 256 positions.
|
|
56
|
+
* @param range - What the map spans. Defaults to the extent of the channel's finite values.
|
|
57
|
+
* @param channel - Which channel to draw. Defaults to the first.
|
|
58
|
+
* @returns `width · height` RGBA pixels, row-major; all transparent for a missing channel.
|
|
59
|
+
*/
|
|
60
|
+
export function rasterizePlane(plane: ValuePlane, colormap: Colormap, range?: ValueRange, channel = 0): Uint8ClampedArray {
|
|
61
|
+
const size = plane.width * plane.height;
|
|
62
|
+
const out = new Uint8ClampedArray(size * 4);
|
|
63
|
+
if (!(channel >= 0 && channel < plane.channels)) return out;
|
|
64
|
+
const { low, high } = range ?? planeRange(plane, channel) ?? { low: 0, high: 0 };
|
|
65
|
+
const lut = new Uint8ClampedArray(STEPS * 3);
|
|
66
|
+
for (let s = 0; s < STEPS; s++) {
|
|
67
|
+
const [r, g, b] = colormap(s / (STEPS - 1));
|
|
68
|
+
lut[3 * s] = r;
|
|
69
|
+
lut[3 * s + 1] = g;
|
|
70
|
+
lut[3 * s + 2] = b;
|
|
71
|
+
}
|
|
72
|
+
const scale = high > low ? (STEPS - 1) / (high - low) : 0;
|
|
73
|
+
const offset = channel * size;
|
|
74
|
+
for (let k = 0; k < size; k++) {
|
|
75
|
+
const v = plane.values[offset + k]!;
|
|
76
|
+
if (!Number.isFinite(v)) continue;
|
|
77
|
+
const s = Math.min(STEPS - 1, Math.max(0, Math.round((v - low) * scale)));
|
|
78
|
+
out[4 * k] = lut[3 * s]!;
|
|
79
|
+
out[4 * k + 1] = lut[3 * s + 1]!;
|
|
80
|
+
out[4 * k + 2] = lut[3 * s + 2]!;
|
|
81
|
+
out[4 * k + 3] = 255;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which labels a layer draws: the level-of-detail rule of the overlay grammar
|
|
3
|
+
* (`docs/visual-language.md` §5), shared by `PointSet`, `AreaSet` and `GridLayer`.
|
|
4
|
+
*
|
|
5
|
+
* Labels are 11 px mono. They are shown only where their anchors are at least 24 screen
|
|
6
|
+
* pixels apart (so a zoomed-out scene shows none and a zoomed-in one shows all), at most 200 at
|
|
7
|
+
* a time, and only inside the viewport. The hovered and selected items always carry theirs.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { useMemo } from "react";
|
|
11
|
+
|
|
12
|
+
import { thinPoints } from "./pointIndex";
|
|
13
|
+
import { useStage } from "./stage/ImageStage";
|
|
14
|
+
import { useScreenPx } from "./stage/useScreenPx";
|
|
15
|
+
import type { Rect } from "./stage/view";
|
|
16
|
+
|
|
17
|
+
/** Labels need this much room between anchors, in screen pixels (overlay grammar §5). */
|
|
18
|
+
export const LABEL_SPACING = 24;
|
|
19
|
+
/** The most label elements drawn at once. */
|
|
20
|
+
export const MAX_LABELS = 200;
|
|
21
|
+
/** The most hovered-or-selected labels forced on regardless of spacing. */
|
|
22
|
+
export const MAX_FORCED_LABELS = 50;
|
|
23
|
+
|
|
24
|
+
/** The image-space rectangle on screen, or `null` before the viewport is measured. */
|
|
25
|
+
export function visibleRect(view: { scale: number; tx: number; ty: number }, box: { width: number; height: number }): Rect | null {
|
|
26
|
+
if (!(box.width > 0) || !(view.scale > 0)) return null;
|
|
27
|
+
return { x: -view.tx / view.scale, y: -view.ty / view.scale, width: box.width / view.scale, height: box.height / view.scale };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Choose the labels to draw.
|
|
32
|
+
*
|
|
33
|
+
* @param spaced - Anchors that are far enough apart, in priority order (`thinPoints`).
|
|
34
|
+
* @param forced - Anchors that always carry a label: the hovered and the selected.
|
|
35
|
+
* @param inView - Whether an anchor is inside the viewport.
|
|
36
|
+
* @returns The anchor indices to label: the forced ones first (at most 50), then the spaced
|
|
37
|
+
* ones, 200 in all.
|
|
38
|
+
*/
|
|
39
|
+
export function pickLabelIndices(spaced: readonly number[], forced: readonly number[], inView: (index: number) => boolean): number[] {
|
|
40
|
+
const shown = new Set<number>();
|
|
41
|
+
for (const i of forced) {
|
|
42
|
+
if (shown.size >= MAX_FORCED_LABELS) break;
|
|
43
|
+
if (i >= 0 && inView(i)) shown.add(i);
|
|
44
|
+
}
|
|
45
|
+
for (const i of spaced) {
|
|
46
|
+
if (shown.size >= MAX_LABELS) break;
|
|
47
|
+
if (inView(i)) shown.add(i);
|
|
48
|
+
}
|
|
49
|
+
return [...shown];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What `useLabelIndices` reads. */
|
|
53
|
+
export interface LabelAnchors {
|
|
54
|
+
/** Whether labels are shown at all. */
|
|
55
|
+
enabled: boolean;
|
|
56
|
+
/** Flat `[x0, y0, x1, y1, …]` anchors, in image coordinates. */
|
|
57
|
+
xy: ArrayLike<number>;
|
|
58
|
+
/** The anchors that have a label, in priority order. Pass a stable array. */
|
|
59
|
+
labelled: readonly number[];
|
|
60
|
+
/** The anchors that must carry theirs (hovered, selected) and have one. Pass a stable array. */
|
|
61
|
+
forced: readonly number[];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The anchors to label at the stage's current zoom and viewport. The spacing depends on the
|
|
66
|
+
* zoom only, so panning does not reshuffle which anchors carry a label.
|
|
67
|
+
*
|
|
68
|
+
* @param anchors - See `LabelAnchors`.
|
|
69
|
+
* @returns Anchor indices.
|
|
70
|
+
*/
|
|
71
|
+
export function useLabelIndices({ enabled, xy, labelled, forced }: LabelAnchors): number[] {
|
|
72
|
+
const stage = useStage();
|
|
73
|
+
const unit = useScreenPx()(1);
|
|
74
|
+
const spacing = LABEL_SPACING * unit;
|
|
75
|
+
const spaced = useMemo(
|
|
76
|
+
() => (enabled && labelled.length > 0 ? thinPoints(xy, spacing, labelled) : []),
|
|
77
|
+
[enabled, labelled, xy, spacing],
|
|
78
|
+
);
|
|
79
|
+
return useMemo(() => {
|
|
80
|
+
if (!enabled || (spaced.length === 0 && forced.length === 0)) return [];
|
|
81
|
+
const view = visibleRect(stage.view, stage.box);
|
|
82
|
+
const inView = (i: number) => {
|
|
83
|
+
if (view === null) return true;
|
|
84
|
+
const x = xy[2 * i]!;
|
|
85
|
+
const y = xy[2 * i + 1]!;
|
|
86
|
+
return x >= view.x && x <= view.x + view.width && y >= view.y && y <= view.y + view.height;
|
|
87
|
+
};
|
|
88
|
+
return pickLabelIndices(spaced, forced, inView);
|
|
89
|
+
}, [enabled, spaced, forced, xy, stage.view, stage.box]);
|
|
90
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Marker glyphs for `PointSet`: one path generator per feature kind (overlay grammar,
|
|
3
|
+
* `docs/visual-language.md` §5).
|
|
4
|
+
*
|
|
5
|
+
* A glyph is a function from a position to SVG path data, so a layer can append thousands of
|
|
6
|
+
* them into one `<path>` per state and style. Sizes are screen pixels: a generator receives
|
|
7
|
+
* `unit`, the image pixels per screen pixel (`useScreenPx()(1)`), and scales its constants by
|
|
8
|
+
* it. A glyph whose `paint` is `"disc"` needs no `unit` at all (it is a zero-length segment
|
|
9
|
+
* drawn with round caps, its size the stroke width), so it is not rebuilt when the zoom
|
|
10
|
+
* changes.
|
|
11
|
+
*
|
|
12
|
+
* Pure: no React, no DOM.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { OverlayRole } from "./overlayRole";
|
|
16
|
+
|
|
17
|
+
/** One kind of marker. */
|
|
18
|
+
export interface MarkerShape {
|
|
19
|
+
/**
|
|
20
|
+
* How the path is painted:
|
|
21
|
+
* - `"disc"`: `path` returns a zero-length segment per marker; the stroke width is the
|
|
22
|
+
* disc's diameter. Independent of `unit`, so a batched path survives a zoom unchanged.
|
|
23
|
+
* - `"line"`: `path` returns an outline, stroked at the state's width.
|
|
24
|
+
*/
|
|
25
|
+
readonly paint: "disc" | "line";
|
|
26
|
+
/** Half the glyph's extent in screen pixels at rest: a disc's radius, a plus's arm. */
|
|
27
|
+
readonly size: number;
|
|
28
|
+
/** The role a marker of this kind has unless the item says otherwise. Defaults to `feature`. */
|
|
29
|
+
readonly role?: OverlayRole | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* The path data for one marker.
|
|
32
|
+
*
|
|
33
|
+
* @param x - Centre x, in image coordinates.
|
|
34
|
+
* @param y - Centre y, in image coordinates.
|
|
35
|
+
* @param unit - Image pixels per screen pixel.
|
|
36
|
+
* @param angle - The item's orientation in radians, `0` when it has none.
|
|
37
|
+
* @returns Path commands, absolute at the start (`M x y …`) and self-contained.
|
|
38
|
+
*/
|
|
39
|
+
path: (x: number, y: number, unit: number, angle: number) => string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Round to 1/1000 of an image pixel: enough for any zoom, and half the characters. */
|
|
43
|
+
function n(value: number): number {
|
|
44
|
+
return Math.round(value * 1000) / 1000;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A circle as two arcs, centred at `(x, y)`.
|
|
49
|
+
*
|
|
50
|
+
* @param x - Centre x.
|
|
51
|
+
* @param y - Centre y.
|
|
52
|
+
* @param r - Radius, in the units of `x` and `y`.
|
|
53
|
+
* @returns Path data.
|
|
54
|
+
*/
|
|
55
|
+
export function circlePath(x: number, y: number, r: number): string {
|
|
56
|
+
return `M${n(x + r)} ${n(y)}a${n(r)} ${n(r)} 0 1 0 ${n(-2 * r)} 0a${n(r)} ${n(r)} 0 1 0 ${n(2 * r)} 0`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The names of the built-in marker kinds. */
|
|
60
|
+
export type BuiltinMarkerKind = "dot" | "plus" | "cross" | "square" | "hollow" | "directed";
|
|
61
|
+
|
|
62
|
+
/** The built-in kinds, with the overlay grammar's glyph for each. */
|
|
63
|
+
export const MARKER_SHAPES: Readonly<Record<BuiltinMarkerKind, MarkerShape>> = {
|
|
64
|
+
/** A blob, circle centre or keypoint: a dot of radius 2.5 px. */
|
|
65
|
+
dot: {
|
|
66
|
+
paint: "disc",
|
|
67
|
+
size: 2.5,
|
|
68
|
+
path: (x, y) => `M${n(x)} ${n(y)}h0`,
|
|
69
|
+
},
|
|
70
|
+
/** A corner or X-junction: a plus with 5 px arms, so the centre stays visible. */
|
|
71
|
+
plus: {
|
|
72
|
+
paint: "line",
|
|
73
|
+
size: 5,
|
|
74
|
+
path: (x, y, u) => {
|
|
75
|
+
const a = 5 * u;
|
|
76
|
+
return `M${n(x - a)} ${n(y)}h${n(2 * a)}M${n(x)} ${n(y - a)}v${n(2 * a)}`;
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
/** A diagonal cross with 4 px arms: a second corner style, or "rejected". */
|
|
80
|
+
cross: {
|
|
81
|
+
paint: "line",
|
|
82
|
+
size: 4,
|
|
83
|
+
path: (x, y, u) => {
|
|
84
|
+
const a = 4 * u;
|
|
85
|
+
return `M${n(x - a)} ${n(y - a)}l${n(2 * a)} ${n(2 * a)}M${n(x - a)} ${n(y + a)}l${n(2 * a)} ${n(-2 * a)}`;
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
/** A hollow square of half-side 3.5 px. */
|
|
89
|
+
square: {
|
|
90
|
+
paint: "line",
|
|
91
|
+
size: 3.5,
|
|
92
|
+
path: (x, y, u) => {
|
|
93
|
+
const a = 3.5 * u;
|
|
94
|
+
return `M${n(x - a)} ${n(y - a)}h${n(2 * a)}v${n(2 * a)}h${n(-2 * a)}Z`;
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
/** A reprojected or predicted point: a hollow circle of radius 4 px, in the model colour. */
|
|
98
|
+
hollow: {
|
|
99
|
+
paint: "line",
|
|
100
|
+
size: 4,
|
|
101
|
+
role: "model",
|
|
102
|
+
path: (x, y, u) => circlePath(x, y, 4 * u),
|
|
103
|
+
},
|
|
104
|
+
/**
|
|
105
|
+
* A point with an orientation: a small ring and a tick of length 8 px from it along
|
|
106
|
+
* `angle`, measured clockwise from +x in image coordinates (y points down).
|
|
107
|
+
*/
|
|
108
|
+
directed: {
|
|
109
|
+
paint: "line",
|
|
110
|
+
size: 6,
|
|
111
|
+
path: (x, y, u, angle) => {
|
|
112
|
+
const c = Math.cos(angle);
|
|
113
|
+
const s = Math.sin(angle);
|
|
114
|
+
return (
|
|
115
|
+
`${circlePath(x, y, 2 * u)}M${n(x + 2 * u * c)} ${n(y + 2 * u * s)}L${n(x + 8 * u * c)} ${n(y + 8 * u * s)}`
|
|
116
|
+
);
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
};
|
|
@@ -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
|
+
}
|