@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,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
|
+
}
|
|
@@ -34,9 +34,11 @@ export interface MarkerShape {
|
|
|
34
34
|
* @param y - Centre y, in image coordinates.
|
|
35
35
|
* @param unit - Image pixels per screen pixel.
|
|
36
36
|
* @param angle - The item's orientation in radians, `0` when it has none.
|
|
37
|
+
* @param angle2 - The item's second angle in radians, `undefined` when it has none. Most
|
|
38
|
+
* shapes ignore it; a glyph with two axes (a corner's two edge directions) reads it.
|
|
37
39
|
* @returns Path commands, absolute at the start (`M x y …`) and self-contained.
|
|
38
40
|
*/
|
|
39
|
-
path: (x: number, y: number, unit: number, angle: number) => string;
|
|
41
|
+
path: (x: number, y: number, unit: number, angle: number, angle2?: number) => string;
|
|
40
42
|
}
|
|
41
43
|
|
|
42
44
|
/** Round to 1/1000 of an image pixel: enough for any zoom, and half the characters. */
|
|
@@ -254,7 +254,8 @@ export function polylineBounds(points: ArrayLike<number>): Rect | null {
|
|
|
254
254
|
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
|
|
255
255
|
}
|
|
256
256
|
|
|
257
|
-
|
|
257
|
+
/** The point of segment ab nearest to `p`. Shared with `areaIndex.ts`. */
|
|
258
|
+
export function closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: number): Point {
|
|
258
259
|
const dx = bx - ax;
|
|
259
260
|
const dy = by - ay;
|
|
260
261
|
const len2 = dx * dx + dy * dy;
|
|
@@ -262,8 +263,8 @@ function closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: numb
|
|
|
262
263
|
return { x: ax + t * dx, y: ay + t * dy };
|
|
263
264
|
}
|
|
264
265
|
|
|
265
|
-
/** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). */
|
|
266
|
-
function segmentTouchesRect(ax: number, ay: number, bx: number, by: number, r: Rect): boolean {
|
|
266
|
+
/** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). Shared with `areaIndex.ts`. */
|
|
267
|
+
export function segmentTouchesRect(ax: number, ay: number, bx: number, by: number, r: Rect): boolean {
|
|
267
268
|
const xmin = r.x;
|
|
268
269
|
const xmax = r.x + r.width;
|
|
269
270
|
const ymin = r.y;
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The arithmetic of editing a rotated rectangle or ellipse: eight handles, a rotation handle
|
|
3
|
+
* and an interior.
|
|
4
|
+
*
|
|
5
|
+
* A shape is its centre, its size and a rotation, so a resize can be done in the shape's own
|
|
6
|
+
* frame (where its sides are axis-aligned) and the opposite edge stays put whatever the
|
|
7
|
+
* rotation. Kept pure, so the cases that bite are tested without a pointer:
|
|
8
|
+
* - a handle dragged across the shape, or to a point far away;
|
|
9
|
+
* - a shape collapsed below the minimum size;
|
|
10
|
+
* - a rotation about the centre and not about a corner.
|
|
11
|
+
*
|
|
12
|
+
* Everything is in the stage's image coordinates. **Rotation is in radians, positive
|
|
13
|
+
* clockwise on screen** (image `y` points down), zero when the shape's width runs along `x`.
|
|
14
|
+
* A degrees-clockwise value, such as Konva's `rotation`, is `degrees * Math.PI / 180`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { Point } from "./measureGeometry";
|
|
18
|
+
import { ROI_HANDLES, type RoiHandle } from "./roiEdit";
|
|
19
|
+
|
|
20
|
+
/** Handle square side, in screen pixels. */
|
|
21
|
+
export const SHAPE_HANDLE_PX = 9;
|
|
22
|
+
/** Rotation handle radius, and its distance past the top side, in screen pixels. */
|
|
23
|
+
export const SHAPE_ROTATE_RADIUS_PX = 5;
|
|
24
|
+
export const SHAPE_ROTATE_OFFSET_PX = 24;
|
|
25
|
+
|
|
26
|
+
/** A rotated rectangle, or the ellipse inscribed in one. */
|
|
27
|
+
export interface RotatedShape {
|
|
28
|
+
/** Centre x, in image coordinates. */
|
|
29
|
+
cx: number;
|
|
30
|
+
/** Centre y, in image coordinates. */
|
|
31
|
+
cy: number;
|
|
32
|
+
/** Extent along the shape's own x axis: a rectangle's width, an ellipse's full axis `2·rx`. */
|
|
33
|
+
width: number;
|
|
34
|
+
/** Extent along the shape's own y axis: a rectangle's height, an ellipse's full axis `2·ry`. */
|
|
35
|
+
height: number;
|
|
36
|
+
/** Radians, clockwise on screen: the turn from the image's x axis to the shape's own. */
|
|
37
|
+
rotation: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A point of image space in the shape's own frame: origin at its centre, axes along its sides.
|
|
42
|
+
*
|
|
43
|
+
* @param shape - The shape.
|
|
44
|
+
* @param p - A point in image coordinates.
|
|
45
|
+
* @returns The point relative to the shape.
|
|
46
|
+
*/
|
|
47
|
+
export function toShapeFrame(shape: RotatedShape, p: Point): Point {
|
|
48
|
+
const c = Math.cos(shape.rotation);
|
|
49
|
+
const s = Math.sin(shape.rotation);
|
|
50
|
+
const dx = p.x - shape.cx;
|
|
51
|
+
const dy = p.y - shape.cy;
|
|
52
|
+
return { x: c * dx + s * dy, y: -s * dx + c * dy };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* A point of the shape's own frame in image space; the inverse of `toShapeFrame`.
|
|
57
|
+
*
|
|
58
|
+
* @param shape - The shape.
|
|
59
|
+
* @param p - A point relative to the shape.
|
|
60
|
+
* @returns The point in image coordinates.
|
|
61
|
+
*/
|
|
62
|
+
export function fromShapeFrame(shape: RotatedShape, p: Point): Point {
|
|
63
|
+
const c = Math.cos(shape.rotation);
|
|
64
|
+
const s = Math.sin(shape.rotation);
|
|
65
|
+
return { x: shape.cx + c * p.x - s * p.y, y: shape.cy + s * p.x + c * p.y };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The sign of a handle along the shape's own x and y axes: `e` and `s` are `+1`. */
|
|
69
|
+
function handleDirection(handle: RoiHandle): Point {
|
|
70
|
+
return { x: handle.includes("e") ? 1 : handle.includes("w") ? -1 : 0, y: handle.includes("s") ? 1 : handle.includes("n") ? -1 : 0 };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Where a handle sits: a corner or the middle of a side, turned with the shape.
|
|
75
|
+
*
|
|
76
|
+
* @param shape - The shape.
|
|
77
|
+
* @param handle - The handle, by compass direction in the shape's own frame.
|
|
78
|
+
* @returns The handle's centre, in image coordinates.
|
|
79
|
+
*/
|
|
80
|
+
export function shapeHandlePoint(shape: RotatedShape, handle: RoiHandle): Point {
|
|
81
|
+
const d = handleDirection(handle);
|
|
82
|
+
return fromShapeFrame(shape, { x: (d.x * shape.width) / 2, y: (d.y * shape.height) / 2 });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Where the rotation handle sits: beyond the middle of the top side, along the shape's own
|
|
87
|
+
* up direction.
|
|
88
|
+
*
|
|
89
|
+
* @param shape - The shape.
|
|
90
|
+
* @param distance - How far past the top side, in image pixels. For a screen-constant handle,
|
|
91
|
+
* pass `useScreenPx()(css)`.
|
|
92
|
+
* @returns The handle's centre, in image coordinates.
|
|
93
|
+
*/
|
|
94
|
+
export function rotationHandlePoint(shape: RotatedShape, distance: number): Point {
|
|
95
|
+
return fromShapeFrame(shape, { x: 0, y: -shape.height / 2 - distance });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Drag a handle to `to`.
|
|
100
|
+
*
|
|
101
|
+
* The dragged side or corner follows the pointer in the shape's own frame and the opposite
|
|
102
|
+
* side or corner stays where it is in the image, which is what makes a handle feel attached.
|
|
103
|
+
* The shape does not flip when dragged through the opposite side: it stops at `minSize`.
|
|
104
|
+
*
|
|
105
|
+
* @param shape - The shape before the drag.
|
|
106
|
+
* @param handle - The handle being dragged.
|
|
107
|
+
* @param to - The pointer, in image coordinates.
|
|
108
|
+
* @param minSize - The smallest extent on either axis, in image pixels.
|
|
109
|
+
* @returns The resized shape: the same rotation, and the opposite side or corner unmoved.
|
|
110
|
+
*/
|
|
111
|
+
export function resizeShape(shape: RotatedShape, handle: RoiHandle, to: Point, minSize: number): RotatedShape {
|
|
112
|
+
const d = handleDirection(handle);
|
|
113
|
+
const u = toShapeFrame(shape, to);
|
|
114
|
+
let width = shape.width;
|
|
115
|
+
let height = shape.height;
|
|
116
|
+
let x = 0;
|
|
117
|
+
let y = 0;
|
|
118
|
+
if (d.x !== 0) {
|
|
119
|
+
// The fixed side is at `-d.x · width / 2`; the new extent runs from it to the pointer.
|
|
120
|
+
width = Math.max(minSize, d.x * u.x + shape.width / 2);
|
|
121
|
+
x = -d.x * (shape.width / 2) + (d.x * width) / 2;
|
|
122
|
+
}
|
|
123
|
+
if (d.y !== 0) {
|
|
124
|
+
height = Math.max(minSize, d.y * u.y + shape.height / 2);
|
|
125
|
+
y = -d.y * (shape.height / 2) + (d.y * height) / 2;
|
|
126
|
+
}
|
|
127
|
+
const centre = fromShapeFrame(shape, { x, y });
|
|
128
|
+
return { cx: centre.x, cy: centre.y, width, height, rotation: shape.rotation };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Turn the shape about its centre so that its rotation handle points at `to`.
|
|
133
|
+
*
|
|
134
|
+
* @param shape - The shape before the drag.
|
|
135
|
+
* @param to - The pointer, in image coordinates.
|
|
136
|
+
* @param snap - Round the rotation to a multiple of this many radians (Shift while dragging
|
|
137
|
+
* rounds to 15°). Defaults to no rounding.
|
|
138
|
+
* @returns The rotated shape: the same centre and size, `rotation` in `(-π, π]`.
|
|
139
|
+
*/
|
|
140
|
+
export function rotateShape(shape: RotatedShape, to: Point, snap = 0): RotatedShape {
|
|
141
|
+
// The handle sits along the shape's own up direction, which is at angle `rotation - π/2`.
|
|
142
|
+
let rotation = Math.atan2(to.y - shape.cy, to.x - shape.cx) + Math.PI / 2;
|
|
143
|
+
if (snap > 0) rotation = Math.round(rotation / snap) * snap;
|
|
144
|
+
return { ...shape, rotation: normalizeAngle(rotation) };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Move the shape.
|
|
149
|
+
*
|
|
150
|
+
* @param shape - The shape.
|
|
151
|
+
* @param dx - Horizontal shift, in image pixels.
|
|
152
|
+
* @param dy - Vertical shift, in image pixels.
|
|
153
|
+
* @returns The moved shape.
|
|
154
|
+
*/
|
|
155
|
+
export function moveShape(shape: RotatedShape, dx: number, dy: number): RotatedShape {
|
|
156
|
+
return { ...shape, cx: shape.cx + dx, cy: shape.cy + dy };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* An angle as the equivalent one in `(-π, π]`.
|
|
161
|
+
*
|
|
162
|
+
* @param angle - Radians.
|
|
163
|
+
* @returns The angle in `(-π, π]`.
|
|
164
|
+
*/
|
|
165
|
+
export function normalizeAngle(angle: number): number {
|
|
166
|
+
const turn = 2 * Math.PI;
|
|
167
|
+
let a = angle % turn;
|
|
168
|
+
if (a > Math.PI) a -= turn;
|
|
169
|
+
else if (a <= -Math.PI) a += turn;
|
|
170
|
+
return a;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The resize cursor for a handle of a rotated shape: the nearest of the four CSS resize
|
|
175
|
+
* cursors to the handle's direction on screen.
|
|
176
|
+
*
|
|
177
|
+
* @param handle - The handle.
|
|
178
|
+
* @param rotation - The shape's rotation, in radians.
|
|
179
|
+
* @returns A CSS `cursor` value.
|
|
180
|
+
*/
|
|
181
|
+
export function shapeHandleCursor(handle: RoiHandle, rotation: number): string {
|
|
182
|
+
const d = handleDirection(handle);
|
|
183
|
+
const angle = Math.atan2(d.y, d.x) + rotation;
|
|
184
|
+
const half = ((angle % Math.PI) + Math.PI) % Math.PI;
|
|
185
|
+
return ["ew-resize", "nwse-resize", "ns-resize", "nesw-resize"][Math.round(half / (Math.PI / 4)) % 4]!;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The shape for a rectangle given as an origin corner, a size and a rotation about that
|
|
190
|
+
* corner: Konva's `Rect` (`x`, `y`, `width`, `height`, `rotation` in degrees), for one.
|
|
191
|
+
*
|
|
192
|
+
* @param corner - The corner the rotation is about, in image coordinates.
|
|
193
|
+
* @param width - Extent along the rotated x axis.
|
|
194
|
+
* @param height - Extent along the rotated y axis.
|
|
195
|
+
* @param rotation - Radians, clockwise on screen.
|
|
196
|
+
* @returns The same rectangle as a `RotatedShape`.
|
|
197
|
+
*/
|
|
198
|
+
export function shapeFromCorner(corner: Point, width: number, height: number, rotation: number): RotatedShape {
|
|
199
|
+
const c = Math.cos(rotation);
|
|
200
|
+
const s = Math.sin(rotation);
|
|
201
|
+
return {
|
|
202
|
+
cx: corner.x + (c * width - s * height) / 2,
|
|
203
|
+
cy: corner.y + (s * width + c * height) / 2,
|
|
204
|
+
width,
|
|
205
|
+
height,
|
|
206
|
+
rotation,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The top-left corner of a shape in its own frame, the origin Konva rotates a `Rect` about;
|
|
212
|
+
* the inverse of `shapeFromCorner`.
|
|
213
|
+
*
|
|
214
|
+
* @param shape - The shape.
|
|
215
|
+
* @returns The corner, in image coordinates.
|
|
216
|
+
*/
|
|
217
|
+
export function shapeCorner(shape: RotatedShape): Point {
|
|
218
|
+
return fromShapeFrame(shape, { x: -shape.width / 2, y: -shape.height / 2 });
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Whether two shapes are the same, to within `epsilon` on every field (rotations compared modulo a turn).
|
|
223
|
+
*
|
|
224
|
+
* @param a - A shape, or `null`.
|
|
225
|
+
* @param b - A shape, or `null`.
|
|
226
|
+
* @param epsilon - The tolerance. Defaults to 1e-6.
|
|
227
|
+
* @returns `true` for two equal shapes, or two `null`s.
|
|
228
|
+
*/
|
|
229
|
+
export function sameShape(a: RotatedShape | null, b: RotatedShape | null, epsilon = 1e-6): boolean {
|
|
230
|
+
if (a === null || b === null) return a === b;
|
|
231
|
+
return (
|
|
232
|
+
Math.abs(a.cx - b.cx) < epsilon &&
|
|
233
|
+
Math.abs(a.cy - b.cy) < epsilon &&
|
|
234
|
+
Math.abs(a.width - b.width) < epsilon &&
|
|
235
|
+
Math.abs(a.height - b.height) < epsilon &&
|
|
236
|
+
Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** What a press on an editable shape does. */
|
|
241
|
+
export type ShapePress = { kind: "resize"; handle: RoiHandle } | { kind: "rotate" } | { kind: "move" };
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* How far a point is outside a shape, in image pixels; zero inside it. For an ellipse this is
|
|
245
|
+
* a first-order estimate, which is exact on the axes and good to a few percent elsewhere.
|
|
246
|
+
*/
|
|
247
|
+
function distanceOutside(shape: RotatedShape, kind: "rect" | "ellipse", p: Point): number {
|
|
248
|
+
const u = toShapeFrame(shape, p);
|
|
249
|
+
const a = Math.max(shape.width / 2, 1e-9);
|
|
250
|
+
const b = Math.max(shape.height / 2, 1e-9);
|
|
251
|
+
if (kind === "rect") return Math.hypot(Math.max(Math.abs(u.x) - a, 0), Math.max(Math.abs(u.y) - b, 0));
|
|
252
|
+
const f = (u.x / a) ** 2 + (u.y / b) ** 2;
|
|
253
|
+
if (f <= 1) return 0;
|
|
254
|
+
const g = Math.hypot(u.x / (a * a), u.y / (b * b));
|
|
255
|
+
return (f - Math.sqrt(f)) / g;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* What a press on an editable shape means, decided once for the whole editor so that a small
|
|
260
|
+
* shape's interior never steals a press meant for its handle.
|
|
261
|
+
*
|
|
262
|
+
* In order:
|
|
263
|
+
* 1. The nearest handle (the eight, and the rotation handle when `rotatable`) whose screen
|
|
264
|
+
* distance from the press is within `radius` plus the handle's half size: resize or rotate.
|
|
265
|
+
* 2. Inside the shape, or within `radius` screen pixels of its outline: move.
|
|
266
|
+
* 3. Otherwise `null`: the press is declined and belongs to whatever is below.
|
|
267
|
+
*
|
|
268
|
+
* @param shape - The shape.
|
|
269
|
+
* @param kind - `"rect"` or `"ellipse"` (the outline differs).
|
|
270
|
+
* @param scale - The view scale: screen pixels per image pixel.
|
|
271
|
+
* @param point - The press, in image coordinates.
|
|
272
|
+
* @param radius - The pointer's tolerance in screen pixels: 12 for a touch, 6 for a mouse.
|
|
273
|
+
* @param rotatable - Whether the rotation handle exists. Defaults to `true`.
|
|
274
|
+
* @returns The decision, or `null`.
|
|
275
|
+
*/
|
|
276
|
+
export function shapePress(
|
|
277
|
+
shape: RotatedShape,
|
|
278
|
+
kind: "rect" | "ellipse",
|
|
279
|
+
scale: number,
|
|
280
|
+
point: Point,
|
|
281
|
+
radius: number,
|
|
282
|
+
rotatable = true,
|
|
283
|
+
): ShapePress | null {
|
|
284
|
+
const best: { press: ShapePress | null; distance: number } = { press: null, distance: Infinity };
|
|
285
|
+
const consider = (candidate: ShapePress, at: Point, half: number) => {
|
|
286
|
+
const d = Math.hypot(at.x - point.x, at.y - point.y) * scale;
|
|
287
|
+
if (d <= radius + half && d < best.distance) {
|
|
288
|
+
best.press = candidate;
|
|
289
|
+
best.distance = d;
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
for (const handle of ROI_HANDLES) consider({ kind: "resize", handle }, shapeHandlePoint(shape, handle), SHAPE_HANDLE_PX / 2);
|
|
293
|
+
if (rotatable) {
|
|
294
|
+
consider({ kind: "rotate" }, rotationHandlePoint(shape, SHAPE_ROTATE_OFFSET_PX / scale), SHAPE_ROTATE_RADIUS_PX);
|
|
295
|
+
}
|
|
296
|
+
if (best.press) return best.press;
|
|
297
|
+
return distanceOutside(shape, kind, point) * scale <= radius ? { kind: "move" } : null;
|
|
298
|
+
}
|