@vitavision/stage2d 0.14.0 → 0.15.1
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 +18 -1
- package/dist/index.d.ts +333 -2
- package/dist/index.js +875 -34
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/components/ContourLayer.tsx +211 -0
- package/src/components/VectorField.tsx +302 -0
- package/src/components/VectorFieldKey.tsx +91 -0
- package/src/components/contour.ts +270 -0
- package/src/components/stage/ImageLayer.tsx +63 -4
- package/src/components/vectorGeometry.ts +159 -0
- package/src/index.ts +16 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Iso-lines of a scalar field: marching squares over a `ValuePlane` channel.
|
|
3
|
+
*
|
|
4
|
+
* Pure and deterministic. The plane's samples are nodes (at pixel centres); a cell is the four nodes
|
|
5
|
+
* of a 2×2 block. A node is *above* a level when its value is `>=` the level. Each cell that mixes
|
|
6
|
+
* above and below nodes holds one segment (two in a saddle), its ends at the linear crossings of the
|
|
7
|
+
* cell's edges. A cell with a `NaN` (or infinite) node holds none, so a line stops at a hole and
|
|
8
|
+
* never bridges it. Segments are chained into polylines through the edge they share.
|
|
9
|
+
*
|
|
10
|
+
* Coordinates are in nodes: `(i, j)` is the centre of the plane's pixel `(i, j)`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { ValuePlane } from "../api/mapValues";
|
|
14
|
+
|
|
15
|
+
/** One iso-line: a polyline at a level. */
|
|
16
|
+
export interface ContourLine {
|
|
17
|
+
/** The level it lies on. */
|
|
18
|
+
level: number;
|
|
19
|
+
/** Flat `[x0, y0, x1, y1, …]` in nodes. For a closed line the first point is not repeated. */
|
|
20
|
+
points: number[];
|
|
21
|
+
/** Whether it returns to its start. */
|
|
22
|
+
closed: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The most levels a `step` is allowed to produce; a finer step is widened by whole multiples. */
|
|
26
|
+
export const MAX_LEVELS = 64;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The levels to draw.
|
|
30
|
+
*
|
|
31
|
+
* @param spec - Explicit levels (non-finite ones are dropped, duplicates merged), or `{ step }`:
|
|
32
|
+
* every multiple of `step` (offset by `origin`) inside `[min, max]`. If that gives more than
|
|
33
|
+
* `MAX_LEVELS` levels the step is multiplied by a whole number until it does not.
|
|
34
|
+
* @param min - The field's smallest finite value, for a step.
|
|
35
|
+
* @param max - The field's largest finite value.
|
|
36
|
+
* @returns Ascending, distinct levels.
|
|
37
|
+
*/
|
|
38
|
+
export function resolveLevels(spec: readonly number[] | { step: number; origin?: number | undefined }, min: number, max: number): number[] {
|
|
39
|
+
if (Array.isArray(spec) || ArrayBuffer.isView(spec)) {
|
|
40
|
+
return [...new Set((spec as readonly number[]).filter(Number.isFinite))].sort((a, b) => a - b);
|
|
41
|
+
}
|
|
42
|
+
const { step, origin = 0 } = spec as { step: number; origin?: number | undefined };
|
|
43
|
+
if (!(step > 0) || !Number.isFinite(step) || !Number.isFinite(min) || !Number.isFinite(max) || max < min) return [];
|
|
44
|
+
let use = step;
|
|
45
|
+
while ((max - min) / use > MAX_LEVELS) use += step;
|
|
46
|
+
const first = Math.ceil((min - origin) / use - 1e-9);
|
|
47
|
+
const last = Math.floor((max - origin) / use + 1e-9);
|
|
48
|
+
const levels: number[] = [];
|
|
49
|
+
for (let k = first; k <= last; k++) levels.push(origin + k * use);
|
|
50
|
+
return levels;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The finite extent of one channel of a plane, `null` when it has no finite value. */
|
|
54
|
+
export function channelExtent(plane: ValuePlane, channel = 0): [number, number] | null {
|
|
55
|
+
const size = plane.width * plane.height;
|
|
56
|
+
const base = channel * size;
|
|
57
|
+
let min = Infinity;
|
|
58
|
+
let max = -Infinity;
|
|
59
|
+
for (let k = 0; k < size; k++) {
|
|
60
|
+
const v = plane.values[base + k]!;
|
|
61
|
+
if (v < min) min = v;
|
|
62
|
+
if (v > max) max = v;
|
|
63
|
+
}
|
|
64
|
+
return min <= max && Number.isFinite(min) && Number.isFinite(max) ? [min, max] : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Edge ids: a horizontal edge from node (i, j) to (i + 1, j) is `2 (j w + i)`, a vertical edge from
|
|
68
|
+
// (i, j) to (i, j + 1) is `2 (j w + i) + 1`. One crossing lies on each edge, so segments of
|
|
69
|
+
// neighbouring cells meet at equal ids.
|
|
70
|
+
|
|
71
|
+
/** Segment endpoints (as edges `T`op, `R`ight, `B`ottom, `L`eft) for each case; corners a b c d clockwise from top-left, a = 8. */
|
|
72
|
+
const T = 0;
|
|
73
|
+
const R = 1;
|
|
74
|
+
const B = 2;
|
|
75
|
+
const L = 3;
|
|
76
|
+
const CASES: readonly (readonly (readonly [number, number])[])[] = [
|
|
77
|
+
[],
|
|
78
|
+
[[L, B]],
|
|
79
|
+
[[B, R]],
|
|
80
|
+
[[L, R]],
|
|
81
|
+
[[T, R]],
|
|
82
|
+
[], // saddle, below
|
|
83
|
+
[[T, B]],
|
|
84
|
+
[[T, L]],
|
|
85
|
+
[[T, L]],
|
|
86
|
+
[[T, B]],
|
|
87
|
+
[], // saddle, below
|
|
88
|
+
[[T, R]],
|
|
89
|
+
[[L, R]],
|
|
90
|
+
[[B, R]],
|
|
91
|
+
[[L, B]],
|
|
92
|
+
[],
|
|
93
|
+
];
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The iso-lines of one channel at one level.
|
|
97
|
+
*
|
|
98
|
+
* @param values - The samples, row-major within the channel (`plane.values`).
|
|
99
|
+
* @param width - Columns (nodes).
|
|
100
|
+
* @param height - Rows.
|
|
101
|
+
* @param level - The level.
|
|
102
|
+
* @param offset - Index of the channel's first sample. Default 0.
|
|
103
|
+
* @returns The lines, in a deterministic order (by the first cell, row-major, each line starting
|
|
104
|
+
* at its first segment). Empty for a plane under 2×2 nodes.
|
|
105
|
+
*/
|
|
106
|
+
export function contourAtLevel(values: ArrayLike<number>, width: number, height: number, level: number, offset = 0): ContourLine[] {
|
|
107
|
+
if (!(width >= 2 && height >= 2) || !Number.isFinite(level)) return [];
|
|
108
|
+
const edgeId = (i: number, j: number, edge: number): number => {
|
|
109
|
+
switch (edge) {
|
|
110
|
+
case T:
|
|
111
|
+
return 2 * (j * width + i);
|
|
112
|
+
case B:
|
|
113
|
+
return 2 * ((j + 1) * width + i);
|
|
114
|
+
case L:
|
|
115
|
+
return 2 * (j * width + i) + 1;
|
|
116
|
+
default:
|
|
117
|
+
return 2 * (j * width + i + 1) + 1;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const segments: [number, number][] = [];
|
|
122
|
+
for (let j = 0; j < height - 1; j++) {
|
|
123
|
+
for (let i = 0; i < width - 1; i++) {
|
|
124
|
+
const a = values[offset + j * width + i]!;
|
|
125
|
+
const b = values[offset + j * width + i + 1]!;
|
|
126
|
+
const c = values[offset + (j + 1) * width + i + 1]!;
|
|
127
|
+
const d = values[offset + (j + 1) * width + i]!;
|
|
128
|
+
// `NaN` fails every comparison; an infinity has no finite crossing. Either leaves the cell empty.
|
|
129
|
+
if (!(Number.isFinite(a) && Number.isFinite(b) && Number.isFinite(c) && Number.isFinite(d))) continue;
|
|
130
|
+
const index = (a >= level ? 8 : 0) | (b >= level ? 4 : 0) | (c >= level ? 2 : 0) | (d >= level ? 1 : 0);
|
|
131
|
+
let pairs = CASES[index]!;
|
|
132
|
+
if (index === 5 || index === 10) {
|
|
133
|
+
// A saddle. The cell's mean decides whether the above corners are joined through the middle.
|
|
134
|
+
const joined = (a + b + c + d) / 4 >= level;
|
|
135
|
+
pairs =
|
|
136
|
+
index === 5
|
|
137
|
+
? joined
|
|
138
|
+
? [
|
|
139
|
+
[T, L],
|
|
140
|
+
[B, R],
|
|
141
|
+
]
|
|
142
|
+
: [
|
|
143
|
+
[T, R],
|
|
144
|
+
[L, B],
|
|
145
|
+
]
|
|
146
|
+
: joined
|
|
147
|
+
? [
|
|
148
|
+
[T, R],
|
|
149
|
+
[L, B],
|
|
150
|
+
]
|
|
151
|
+
: [
|
|
152
|
+
[T, L],
|
|
153
|
+
[B, R],
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
for (const [e0, e1] of pairs) segments.push([edgeId(i, j, e0), edgeId(i, j, e1)]);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (segments.length === 0) return [];
|
|
160
|
+
|
|
161
|
+
// Each edge id has at most two segments.
|
|
162
|
+
const at = new Map<number, number[]>();
|
|
163
|
+
segments.forEach(([p, q], s) => {
|
|
164
|
+
for (const id of [p, q]) {
|
|
165
|
+
const list = at.get(id);
|
|
166
|
+
if (list) list.push(s);
|
|
167
|
+
else at.set(id, [s]);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const crossing = (id: number): [number, number] => {
|
|
172
|
+
const vertical = id % 2 === 1;
|
|
173
|
+
const node = (id - (vertical ? 1 : 0)) / 2;
|
|
174
|
+
const i = node % width;
|
|
175
|
+
const j = (node - i) / width;
|
|
176
|
+
const v0 = values[offset + node]!;
|
|
177
|
+
const v1 = values[offset + node + (vertical ? width : 1)]!;
|
|
178
|
+
const t = Math.min(1, Math.max(0, (level - v0) / (v1 - v0)));
|
|
179
|
+
return vertical ? [i, j + t] : [i + t, j];
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const used = new Uint8Array(segments.length);
|
|
183
|
+
const lines: ContourLine[] = [];
|
|
184
|
+
for (let s = 0; s < segments.length; s++) {
|
|
185
|
+
if (used[s]) continue;
|
|
186
|
+
used[s] = 1;
|
|
187
|
+
const ids = [segments[s]![0], segments[s]![1]];
|
|
188
|
+
// Forward from the tail, then backward from the head, until a loop closes or the line ends.
|
|
189
|
+
walk(ids, at, segments, used, true);
|
|
190
|
+
walk(ids, at, segments, used, false);
|
|
191
|
+
const closed = ids.length > 2 && ids[0] === ids[ids.length - 1];
|
|
192
|
+
if (closed) ids.pop();
|
|
193
|
+
const points: number[] = [];
|
|
194
|
+
for (const id of ids) points.push(...crossing(id));
|
|
195
|
+
lines.push({ level, points, closed });
|
|
196
|
+
}
|
|
197
|
+
return lines;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Extends a chain of edge ids at its tail (`forward`) or head by the unused segments meeting there. */
|
|
201
|
+
function walk(ids: number[], at: Map<number, number[]>, segments: readonly [number, number][], used: Uint8Array, forward: boolean): void {
|
|
202
|
+
for (;;) {
|
|
203
|
+
const end = forward ? ids[ids.length - 1]! : ids[0]!;
|
|
204
|
+
if (ids.length > 2 && ids[0] === ids[ids.length - 1]) return;
|
|
205
|
+
const next = at.get(end)!.find((other) => !used[other]);
|
|
206
|
+
if (next === undefined) return;
|
|
207
|
+
used[next] = 1;
|
|
208
|
+
const [p, q] = segments[next]!;
|
|
209
|
+
const far = p === end ? q : p;
|
|
210
|
+
if (forward) ids.push(far);
|
|
211
|
+
else ids.unshift(far);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* The iso-lines of a plane's channel at every level, lowest level first.
|
|
217
|
+
*
|
|
218
|
+
* @param plane - The field; `NaN` is "no data".
|
|
219
|
+
* @param channel - Which channel. Default 0; out of range gives no lines.
|
|
220
|
+
* @param levels - See `resolveLevels`; the lines of each level, in turn.
|
|
221
|
+
*/
|
|
222
|
+
export function contourPaths(plane: ValuePlane, channel: number, levels: readonly number[]): ContourLine[] {
|
|
223
|
+
if (!Number.isInteger(channel) || channel < 0 || channel >= plane.channels) return [];
|
|
224
|
+
const offset = channel * plane.width * plane.height;
|
|
225
|
+
return levels.flatMap((level) => contourAtLevel(plane.values, plane.width, plane.height, level, offset));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Total length of a polyline (closing segment included for a closed line), in nodes. */
|
|
229
|
+
export function lineLength(line: ContourLine): number {
|
|
230
|
+
const p = line.points;
|
|
231
|
+
let length = 0;
|
|
232
|
+
for (let k = 2; k < p.length; k += 2) length += Math.hypot(p[k]! - p[k - 2]!, p[k + 1]! - p[k - 1]!);
|
|
233
|
+
if (line.closed && p.length >= 4) length += Math.hypot(p[0]! - p[p.length - 2]!, p[1]! - p[p.length - 1]!);
|
|
234
|
+
return length;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Points along a line at fractions of its length, for placing labels.
|
|
239
|
+
*
|
|
240
|
+
* @param line - The line.
|
|
241
|
+
* @param count - How many labels; they sit at `(k + 0.5) / count` of the arc length.
|
|
242
|
+
* @returns `[x, y]` per label, in nodes.
|
|
243
|
+
*/
|
|
244
|
+
export function pointsAlong(line: ContourLine, count: number): [number, number][] {
|
|
245
|
+
const p = line.points;
|
|
246
|
+
const n = p.length / 2;
|
|
247
|
+
if (n === 0 || count < 1) return [];
|
|
248
|
+
const total = lineLength(line);
|
|
249
|
+
if (n === 1 || total === 0) return [[p[0]!, p[1]!]];
|
|
250
|
+
const out: [number, number][] = [];
|
|
251
|
+
const segs = line.closed ? n : n - 1;
|
|
252
|
+
for (let k = 0; k < count; k++) {
|
|
253
|
+
let target = ((k + 0.5) / count) * total;
|
|
254
|
+
for (let s = 0; s < segs; s++) {
|
|
255
|
+
const x0 = p[2 * s]!;
|
|
256
|
+
const y0 = p[2 * s + 1]!;
|
|
257
|
+
const t = (s + 1) % n;
|
|
258
|
+
const x1 = p[2 * t]!;
|
|
259
|
+
const y1 = p[2 * t + 1]!;
|
|
260
|
+
const len = Math.hypot(x1 - x0, y1 - y0);
|
|
261
|
+
if (target <= len || s === segs - 1) {
|
|
262
|
+
const f = len === 0 ? 0 : Math.min(1, target / len);
|
|
263
|
+
out.push([x0 + f * (x1 - x0), y0 + f * (y1 - y0)]);
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
target -= len;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return out;
|
|
270
|
+
}
|
|
@@ -15,9 +15,11 @@
|
|
|
15
15
|
* - **Pixelated past a zoom.** Above about 4× the browser's smoothing paints detail the
|
|
16
16
|
* sensor never recorded; on a metrology bench the sensor's own samples are what is worth
|
|
17
17
|
* looking at.
|
|
18
|
+
* - **A display tone curve.** A dark or low-contrast frame is read with a gain and a gamma
|
|
19
|
+
* applied on screen only (`gain`, `gamma`): the pixels the app measures are untouched.
|
|
18
20
|
*/
|
|
19
21
|
|
|
20
|
-
import { useEffect, useRef, useState } from "react";
|
|
22
|
+
import { useEffect, useId, useRef, useState } from "react";
|
|
21
23
|
|
|
22
24
|
import { cn } from "@vitavision/ui";
|
|
23
25
|
import { useStage } from "./ImageStage";
|
|
@@ -47,6 +49,20 @@ export interface ImageLayerBaseProps {
|
|
|
47
49
|
onLoad?: (() => void) | undefined;
|
|
48
50
|
/** Called when the full image fails to load. */
|
|
49
51
|
onError?: (() => void) | undefined;
|
|
52
|
+
/**
|
|
53
|
+
* Display gain: each channel is multiplied by it and clipped at white, after `gamma`.
|
|
54
|
+
* Defaults to 1. A negative value counts as 0, one that is not finite as 1.
|
|
55
|
+
*
|
|
56
|
+
* Like `gamma`, it changes what is drawn, never the image data: a way to read a dark or
|
|
57
|
+
* low-contrast frame, not a correction to measure on.
|
|
58
|
+
*/
|
|
59
|
+
gain?: number | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Display gamma, as an image editor's levels control: each channel `v` (0 to 1, as encoded in
|
|
62
|
+
* the file) is drawn as `gain × v^(1 / gamma)`. Above 1 it lifts the shadows and mid-tones,
|
|
63
|
+
* below 1 it darkens them. Defaults to 1; a value that is not positive counts as 1.
|
|
64
|
+
*/
|
|
65
|
+
gamma?: number | undefined;
|
|
50
66
|
/** Merged onto both images with `cn`. */
|
|
51
67
|
className?: string | undefined;
|
|
52
68
|
}
|
|
@@ -79,12 +95,29 @@ export type ImageLayerProps = ImageLayerBaseProps &
|
|
|
79
95
|
* With a `preview`, the full image is wanted once the stage would magnify the preview, and
|
|
80
96
|
* `onFullNeeded` says so; `src` can be supplied then rather than up front.
|
|
81
97
|
*
|
|
98
|
+
* With a `gain` or `gamma` other than 1, both images are drawn through one SVG tone-curve filter
|
|
99
|
+
* (sRGB values, per channel) and carry `data-adjusted`.
|
|
100
|
+
*
|
|
82
101
|
* Each image carries `data-tier` (`preview` or `full`); the full image carries `data-loaded`
|
|
83
102
|
* once it has loaded, the preview carries `data-wants-full` from the moment the full image is
|
|
84
103
|
* wanted until it has loaded, and both carry `data-pixelated` while pixelated.
|
|
85
104
|
*/
|
|
86
|
-
export function ImageLayer({
|
|
105
|
+
export function ImageLayer({
|
|
106
|
+
src,
|
|
107
|
+
preview,
|
|
108
|
+
alt,
|
|
109
|
+
pixelatedAbove = 4,
|
|
110
|
+
onFullNeeded,
|
|
111
|
+
onLoad,
|
|
112
|
+
onError,
|
|
113
|
+
gain,
|
|
114
|
+
gamma,
|
|
115
|
+
className,
|
|
116
|
+
}: ImageLayerProps) {
|
|
87
117
|
const stage = useStage();
|
|
118
|
+
const curve = toneCurve(gain, gamma);
|
|
119
|
+
// `useId` may contain characters that are not valid in a CSS `url(#…)` reference.
|
|
120
|
+
const filterId = `stage-image-tone-${useId().replace(/[^A-Za-z0-9_-]/g, "")}`;
|
|
88
121
|
const scale = stage.view.scale;
|
|
89
122
|
// The full image is wanted once the preview would be magnified on screen: its own pixels
|
|
90
123
|
// per image pixel are `preview.width / image.width`. Not before the viewport is measured:
|
|
@@ -112,9 +145,22 @@ export function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onFullNeeded
|
|
|
112
145
|
const pixelated = scale >= pixelatedAbove;
|
|
113
146
|
const shared = cn("pointer-events-none absolute inset-0 h-full w-full select-none", className);
|
|
114
147
|
const rendering = pixelated ? ("pixelated" as const) : undefined;
|
|
148
|
+
const style = { imageRendering: rendering, filter: curve ? `url(#${filterId})` : undefined };
|
|
149
|
+
const adjusted = curve ? "" : undefined;
|
|
115
150
|
|
|
116
151
|
return (
|
|
117
152
|
<>
|
|
153
|
+
{curve && (
|
|
154
|
+
<svg aria-hidden="true" width="0" height="0" className="pointer-events-none absolute" focusable="false">
|
|
155
|
+
<filter id={filterId} colorInterpolationFilters="sRGB" data-tone-curve="">
|
|
156
|
+
<feComponentTransfer>
|
|
157
|
+
<feFuncR type="gamma" amplitude={curve.amplitude} exponent={curve.exponent} offset={0} />
|
|
158
|
+
<feFuncG type="gamma" amplitude={curve.amplitude} exponent={curve.exponent} offset={0} />
|
|
159
|
+
<feFuncB type="gamma" amplitude={curve.amplitude} exponent={curve.exponent} offset={0} />
|
|
160
|
+
</feComponentTransfer>
|
|
161
|
+
</filter>
|
|
162
|
+
</svg>
|
|
163
|
+
)}
|
|
118
164
|
{preview && !fullReady && (
|
|
119
165
|
<img
|
|
120
166
|
src={preview.src}
|
|
@@ -124,8 +170,9 @@ export function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onFullNeeded
|
|
|
124
170
|
data-tier="preview"
|
|
125
171
|
data-wants-full={wanted ? "" : undefined}
|
|
126
172
|
data-pixelated={pixelated ? "" : undefined}
|
|
173
|
+
data-adjusted={adjusted}
|
|
127
174
|
className={shared}
|
|
128
|
-
style={
|
|
175
|
+
style={style}
|
|
129
176
|
/>
|
|
130
177
|
)}
|
|
131
178
|
{showFull && (
|
|
@@ -136,15 +183,27 @@ export function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onFullNeeded
|
|
|
136
183
|
data-tier="full"
|
|
137
184
|
data-loaded={fullReady ? "" : undefined}
|
|
138
185
|
data-pixelated={pixelated ? "" : undefined}
|
|
186
|
+
data-adjusted={adjusted}
|
|
139
187
|
onLoad={() => {
|
|
140
188
|
setLoaded(src);
|
|
141
189
|
onLoad?.();
|
|
142
190
|
}}
|
|
143
191
|
onError={() => onError?.()}
|
|
144
192
|
className={cn(shared, preview && !fullReady && "opacity-0")}
|
|
145
|
-
style={
|
|
193
|
+
style={style}
|
|
146
194
|
/>
|
|
147
195
|
)}
|
|
148
196
|
</>
|
|
149
197
|
);
|
|
150
198
|
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The `feFuncX type="gamma"` parameters (`amplitude × v^exponent`) for a gain and a gamma, or
|
|
202
|
+
* `null` when the curve is the identity and no filter is needed.
|
|
203
|
+
*/
|
|
204
|
+
function toneCurve(gain: number | undefined, gamma: number | undefined): { amplitude: number; exponent: number } | null {
|
|
205
|
+
const amplitude = gain === undefined || !Number.isFinite(gain) ? 1 : Math.max(0, gain);
|
|
206
|
+
const g = gamma === undefined || !(gamma > 0) || !Number.isFinite(gamma) ? 1 : gamma;
|
|
207
|
+
if (amplitude === 1 && g === 1) return null;
|
|
208
|
+
return { amplitude, exponent: 1 / g };
|
|
209
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The arithmetic of a vector field overlay: magnitudes, the scale that turns data units into
|
|
3
|
+
* image pixels, the path of an arrow, and the bins a colour map is quantised into.
|
|
4
|
+
*
|
|
5
|
+
* Everything here is pure. Vectors are a flat `[dx0, dy0, dx1, dy1, …]` array in data units
|
|
6
|
+
* (a displacement in pixels, a velocity, a gradient); a vector with a non-finite component is
|
|
7
|
+
* absent.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* How data units become image pixels.
|
|
12
|
+
* - A number is image pixels per data unit: the arrows are geometry, so they grow with the zoom
|
|
13
|
+
* like the image does.
|
|
14
|
+
* - `{ length }` sizes the arrows so the `percentile` vector spans `length` screen pixels at
|
|
15
|
+
* every zoom: the field stays readable whatever the magnification.
|
|
16
|
+
*/
|
|
17
|
+
export type VectorScale =
|
|
18
|
+
| number
|
|
19
|
+
| {
|
|
20
|
+
/** The screen length, in CSS pixels, the reference vector spans. */
|
|
21
|
+
length: number;
|
|
22
|
+
/** Which magnitude is the reference, in `[0, 1]`. Defaults to `1`, the longest vector. */
|
|
23
|
+
percentile?: number | undefined;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The length of vector `i`, or `NaN` when it is absent.
|
|
28
|
+
*
|
|
29
|
+
* @param vectors - Flat `[dx0, dy0, …]`.
|
|
30
|
+
* @param i - The vector's index.
|
|
31
|
+
* @returns `hypot(dx, dy)`, or `NaN` for a non-finite component.
|
|
32
|
+
*/
|
|
33
|
+
export function vectorMagnitude(vectors: ArrayLike<number>, i: number): number {
|
|
34
|
+
const dx = vectors[2 * i];
|
|
35
|
+
const dy = vectors[2 * i + 1];
|
|
36
|
+
if (dx === undefined || dy === undefined || !Number.isFinite(dx) || !Number.isFinite(dy)) return Number.NaN;
|
|
37
|
+
return Math.hypot(dx, dy);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The magnitudes of every vector, `NaN` for an absent one.
|
|
42
|
+
*
|
|
43
|
+
* @param vectors - Flat `[dx0, dy0, …]`.
|
|
44
|
+
* @returns One magnitude per vector.
|
|
45
|
+
*/
|
|
46
|
+
export function vectorMagnitudes(vectors: ArrayLike<number>): Float64Array {
|
|
47
|
+
const count = Math.floor(vectors.length / 2);
|
|
48
|
+
const out = new Float64Array(count);
|
|
49
|
+
for (let i = 0; i < count; i++) out[i] = vectorMagnitude(vectors, i);
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A magnitude's rank statistic over the present vectors.
|
|
55
|
+
*
|
|
56
|
+
* @param magnitudes - As `vectorMagnitudes` returns them; `NaN` entries are ignored.
|
|
57
|
+
* @param p - The fraction in `[0, 1]` (clamped): `1` is the longest, `0.5` the median.
|
|
58
|
+
* @returns The nearest-rank value, or `0` when no vector is present.
|
|
59
|
+
*/
|
|
60
|
+
export function magnitudePercentile(magnitudes: ArrayLike<number>, p: number): number {
|
|
61
|
+
const live: number[] = [];
|
|
62
|
+
for (let i = 0; i < magnitudes.length; i++) {
|
|
63
|
+
const m = magnitudes[i]!;
|
|
64
|
+
if (Number.isFinite(m)) live.push(m);
|
|
65
|
+
}
|
|
66
|
+
if (live.length === 0) return 0;
|
|
67
|
+
live.sort((a, b) => a - b);
|
|
68
|
+
const q = Number.isFinite(p) ? Math.min(1, Math.max(0, p)) : 1;
|
|
69
|
+
return live[Math.max(0, Math.ceil(q * live.length) - 1)]!;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The scale in image pixels per data unit.
|
|
74
|
+
*
|
|
75
|
+
* @param scale - See `VectorScale`.
|
|
76
|
+
* @param referenceMagnitude - The reference vector's length in data units, for an automatic scale.
|
|
77
|
+
* @param imagePerScreenPx - Image pixels covered by one screen pixel at the current zoom.
|
|
78
|
+
* @returns Image pixels per data unit; `0` when an automatic scale has no vector to measure.
|
|
79
|
+
*/
|
|
80
|
+
export function imagePerUnit(scale: VectorScale, referenceMagnitude: number, imagePerScreenPx: number): number {
|
|
81
|
+
if (typeof scale === "number") return Number.isFinite(scale) && scale > 0 ? scale : 0;
|
|
82
|
+
if (!(referenceMagnitude > 0) || !(scale.length > 0)) return 0;
|
|
83
|
+
return (scale.length * imagePerScreenPx) / referenceMagnitude;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* A round length for a key: the largest of 1, 2 and 5 times a power of ten that is at most `max`.
|
|
88
|
+
*
|
|
89
|
+
* @param max - The upper bound, in data units.
|
|
90
|
+
* @returns The round length, or `0` for a non-positive `max`.
|
|
91
|
+
*/
|
|
92
|
+
export function niceLength(max: number): number {
|
|
93
|
+
if (!(max > 0) || !Number.isFinite(max)) return 0;
|
|
94
|
+
const power = 10 ** Math.floor(Math.log10(max));
|
|
95
|
+
for (const m of [5, 2, 1]) if (m * power <= max * (1 + 1e-12)) return m * power;
|
|
96
|
+
return power;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The shape of an arrow, in screen pixels. */
|
|
100
|
+
export interface ArrowStyle {
|
|
101
|
+
/** The arrowhead's length. */
|
|
102
|
+
head: number;
|
|
103
|
+
/** The arrowhead's full width, as a fraction of its length. */
|
|
104
|
+
headWidth: number;
|
|
105
|
+
/** A vector shorter than this is not drawn. */
|
|
106
|
+
minLength: number;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const r = (v: number): string => String(Math.round(v * 1000) / 1000);
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The path data of one arrow: a shaft and a filled head.
|
|
113
|
+
*
|
|
114
|
+
* The head is capped at 45 % of the arrow's length, so a short arrow is a small wedge rather
|
|
115
|
+
* than a head on no shaft. Lengths are in the units of `(x, y)` (image pixels); `unit` converts
|
|
116
|
+
* the style's screen pixels to them.
|
|
117
|
+
*
|
|
118
|
+
* @param x - The anchor's x.
|
|
119
|
+
* @param y - The anchor's y.
|
|
120
|
+
* @param dx - The displacement's x, already scaled to image pixels.
|
|
121
|
+
* @param dy - The displacement's y, already scaled to image pixels.
|
|
122
|
+
* @param unit - Image pixels per screen pixel.
|
|
123
|
+
* @param style - The arrow's shape.
|
|
124
|
+
* @returns Path data, or `""` when the arrow is absent or shorter than `style.minLength`.
|
|
125
|
+
*/
|
|
126
|
+
export function arrowPath(x: number, y: number, dx: number, dy: number, unit: number, style: ArrowStyle): string {
|
|
127
|
+
const len = Math.hypot(dx, dy);
|
|
128
|
+
if (!(len > 0) || len < style.minLength * unit) return "";
|
|
129
|
+
const ux = dx / len;
|
|
130
|
+
const uy = dy / len;
|
|
131
|
+
const head = Math.min(style.head * unit, 0.45 * len);
|
|
132
|
+
const half = (head * style.headWidth) / 2;
|
|
133
|
+
const tx = x + dx;
|
|
134
|
+
const ty = y + dy;
|
|
135
|
+
const bx = tx - ux * head;
|
|
136
|
+
const by = ty - uy * head;
|
|
137
|
+
return (
|
|
138
|
+
`M${r(x)} ${r(y)}L${r(bx)} ${r(by)}` +
|
|
139
|
+
`M${r(tx)} ${r(ty)}L${r(bx - uy * half)} ${r(by + ux * half)}L${r(bx + uy * half)} ${r(by - ux * half)}Z`
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The number of colour steps a magnitude-coloured field is quantised into: one path each. */
|
|
144
|
+
export const VECTOR_COLOR_BINS = 24;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The colour bin of a magnitude.
|
|
148
|
+
*
|
|
149
|
+
* @param magnitude - The vector's length.
|
|
150
|
+
* @param low - The magnitude drawn in the map's first colour.
|
|
151
|
+
* @param high - The magnitude drawn in the map's last colour.
|
|
152
|
+
* @param bins - The number of bins. Defaults to `VECTOR_COLOR_BINS`.
|
|
153
|
+
* @returns An integer in `[0, bins - 1]`; a degenerate range puts everything in bin `0`.
|
|
154
|
+
*/
|
|
155
|
+
export function colorBin(magnitude: number, low: number, high: number, bins = VECTOR_COLOR_BINS): number {
|
|
156
|
+
if (!(high > low)) return 0;
|
|
157
|
+
const t = (magnitude - low) / (high - low);
|
|
158
|
+
return Math.min(bins - 1, Math.max(0, Math.floor(t * bins)));
|
|
159
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -178,6 +178,22 @@ export {
|
|
|
178
178
|
type HeatmapRgbaProps,
|
|
179
179
|
} from "./components/HeatmapLayer";
|
|
180
180
|
export { planeRange, rasterizePlane, type Colormap, type ValueRange } from "./components/heatmapRaster";
|
|
181
|
+
export { ContourLayer, type ContourLayerProps } from "./components/ContourLayer";
|
|
182
|
+
export { contourPaths, resolveLevels, type ContourLine } from "./components/contour";
|
|
183
|
+
export { VectorField, useVectorScale, type VectorFieldProps } from "./components/VectorField";
|
|
184
|
+
export { VectorFieldKey, type VectorFieldKeyProps } from "./components/VectorFieldKey";
|
|
185
|
+
export {
|
|
186
|
+
VECTOR_COLOR_BINS,
|
|
187
|
+
arrowPath,
|
|
188
|
+
colorBin,
|
|
189
|
+
imagePerUnit,
|
|
190
|
+
magnitudePercentile,
|
|
191
|
+
niceLength,
|
|
192
|
+
vectorMagnitude,
|
|
193
|
+
vectorMagnitudes,
|
|
194
|
+
type ArrowStyle,
|
|
195
|
+
type VectorScale,
|
|
196
|
+
} from "./components/vectorGeometry";
|
|
181
197
|
export { ShapeEditor, type ShapeEditorProps } from "./components/ShapeEditor";
|
|
182
198
|
export {
|
|
183
199
|
fromShapeFrame,
|