@motionscript/math 0.0.0-stage → 0.1.0-alpha.4
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/CHANGELOG.md +92 -0
- package/LICENSE +201 -0
- package/NOTICE +48 -0
- package/README.md +385 -3
- package/dist/annotate/angle-mark.d.ts +46 -0
- package/dist/annotate/angle-mark.d.ts.map +1 -0
- package/dist/annotate/angle-mark.js +132 -0
- package/dist/annotate/angle-mark.js.map +1 -0
- package/dist/annotate/curly-brace.d.ts +46 -0
- package/dist/annotate/curly-brace.d.ts.map +1 -0
- package/dist/annotate/curly-brace.js +114 -0
- package/dist/annotate/curly-brace.js.map +1 -0
- package/dist/annotate/emphasis-mark.d.ts +20 -0
- package/dist/annotate/emphasis-mark.d.ts.map +1 -0
- package/dist/annotate/emphasis-mark.js +81 -0
- package/dist/annotate/emphasis-mark.js.map +1 -0
- package/dist/browser/THIRD_PARTY_LICENSES.txt +420 -0
- package/dist/browser/chunks/chunk-3GJB6AVO.js +2 -0
- package/dist/browser/chunks/chunk-3GJB6AVO.js.map +7 -0
- package/dist/browser/chunks/chunk-D5WHCVBC.js +2 -0
- package/dist/browser/chunks/chunk-D5WHCVBC.js.map +7 -0
- package/dist/browser/chunks/chunk-WL4KEX7Y.js +2 -0
- package/dist/browser/chunks/chunk-WL4KEX7Y.js.map +7 -0
- package/dist/browser/chunks/mathjax-DNP3YRES.js +61 -0
- package/dist/browser/chunks/mathjax-DNP3YRES.js.map +7 -0
- package/dist/browser/index.js +2 -0
- package/dist/browser/index.js.map +7 -0
- package/dist/browser/kit.js +2 -0
- package/dist/browser/kit.js.map +7 -0
- package/dist/browser/manifest.json +30 -0
- package/dist/browser/tex.js +2 -0
- package/dist/browser/tex.js.map +7 -0
- package/dist/engine.d.ts +64 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +42 -0
- package/dist/engine.js.map +1 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +30 -0
- package/dist/index.js.map +1 -0
- package/dist/kit/brace.d.ts +8 -0
- package/dist/kit/brace.d.ts.map +1 -0
- package/dist/kit/brace.js +36 -0
- package/dist/kit/brace.js.map +1 -0
- package/dist/kit/cache.d.ts +30 -0
- package/dist/kit/cache.d.ts.map +1 -0
- package/dist/kit/cache.js +53 -0
- package/dist/kit/cache.js.map +1 -0
- package/dist/kit/contour.d.ts +8 -0
- package/dist/kit/contour.d.ts.map +1 -0
- package/dist/kit/contour.js +93 -0
- package/dist/kit/contour.js.map +1 -0
- package/dist/kit/coords.d.ts +69 -0
- package/dist/kit/coords.d.ts.map +1 -0
- package/dist/kit/coords.js +224 -0
- package/dist/kit/coords.js.map +1 -0
- package/dist/kit/curve.d.ts +17 -0
- package/dist/kit/curve.d.ts.map +1 -0
- package/dist/kit/curve.js +22 -0
- package/dist/kit/curve.js.map +1 -0
- package/dist/kit/equation.d.ts +61 -0
- package/dist/kit/equation.d.ts.map +1 -0
- package/dist/kit/equation.js +168 -0
- package/dist/kit/equation.js.map +1 -0
- package/dist/kit/equation3d.d.ts +50 -0
- package/dist/kit/equation3d.d.ts.map +1 -0
- package/dist/kit/equation3d.js +103 -0
- package/dist/kit/equation3d.js.map +1 -0
- package/dist/kit/expression.d.ts +35 -0
- package/dist/kit/expression.d.ts.map +1 -0
- package/dist/kit/expression.js +124 -0
- package/dist/kit/expression.js.map +1 -0
- package/dist/kit/field-mark.d.ts +58 -0
- package/dist/kit/field-mark.d.ts.map +1 -0
- package/dist/kit/field-mark.js +129 -0
- package/dist/kit/field-mark.js.map +1 -0
- package/dist/kit/field.d.ts +14 -0
- package/dist/kit/field.d.ts.map +1 -0
- package/dist/kit/field.js +46 -0
- package/dist/kit/field.js.map +1 -0
- package/dist/kit/follow.d.ts +71 -0
- package/dist/kit/follow.d.ts.map +1 -0
- package/dist/kit/follow.js +159 -0
- package/dist/kit/follow.js.map +1 -0
- package/dist/kit/furniture.d.ts +30 -0
- package/dist/kit/furniture.d.ts.map +1 -0
- package/dist/kit/furniture.js +87 -0
- package/dist/kit/furniture.js.map +1 -0
- package/dist/kit/geometry.d.ts +13 -0
- package/dist/kit/geometry.d.ts.map +1 -0
- package/dist/kit/geometry.js +54 -0
- package/dist/kit/geometry.js.map +1 -0
- package/dist/kit/mark.d.ts +47 -0
- package/dist/kit/mark.d.ts.map +1 -0
- package/dist/kit/mark.js +103 -0
- package/dist/kit/mark.js.map +1 -0
- package/dist/kit/part-fills.d.ts +23 -0
- package/dist/kit/part-fills.d.ts.map +1 -0
- package/dist/kit/part-fills.js +46 -0
- package/dist/kit/part-fills.js.map +1 -0
- package/dist/kit/place.d.ts +18 -0
- package/dist/kit/place.d.ts.map +1 -0
- package/dist/kit/place.js +68 -0
- package/dist/kit/place.js.map +1 -0
- package/dist/kit/placement.d.ts +8 -0
- package/dist/kit/placement.d.ts.map +1 -0
- package/dist/kit/placement.js +8 -0
- package/dist/kit/placement.js.map +1 -0
- package/dist/kit/sampler.d.ts +17 -0
- package/dist/kit/sampler.d.ts.map +1 -0
- package/dist/kit/sampler.js +250 -0
- package/dist/kit/sampler.js.map +1 -0
- package/dist/kit/scale.d.ts +12 -0
- package/dist/kit/scale.d.ts.map +1 -0
- package/dist/kit/scale.js +37 -0
- package/dist/kit/scale.js.map +1 -0
- package/dist/kit/source.d.ts +22 -0
- package/dist/kit/source.d.ts.map +1 -0
- package/dist/kit/source.js +45 -0
- package/dist/kit/source.js.map +1 -0
- package/dist/kit/system.d.ts +33 -0
- package/dist/kit/system.d.ts.map +1 -0
- package/dist/kit/system.js +67 -0
- package/dist/kit/system.js.map +1 -0
- package/dist/kit/ticks.d.ts +19 -0
- package/dist/kit/ticks.d.ts.map +1 -0
- package/dist/kit/ticks.js +78 -0
- package/dist/kit/ticks.js.map +1 -0
- package/dist/kit/withdrawn.d.ts +9 -0
- package/dist/kit/withdrawn.d.ts.map +1 -0
- package/dist/kit/withdrawn.js +9 -0
- package/dist/kit/withdrawn.js.map +1 -0
- package/dist/marks/curve-area.d.ts +32 -0
- package/dist/marks/curve-area.d.ts.map +1 -0
- package/dist/marks/curve-area.js +82 -0
- package/dist/marks/curve-area.js.map +1 -0
- package/dist/marks/drop-lines.d.ts +22 -0
- package/dist/marks/drop-lines.d.ts.map +1 -0
- package/dist/marks/drop-lines.js +58 -0
- package/dist/marks/drop-lines.js.map +1 -0
- package/dist/marks/plot-point.d.ts +35 -0
- package/dist/marks/plot-point.d.ts.map +1 -0
- package/dist/marks/plot-point.js +97 -0
- package/dist/marks/plot-point.js.map +1 -0
- package/dist/marks/riemann-sum.d.ts +37 -0
- package/dist/marks/riemann-sum.d.ts.map +1 -0
- package/dist/marks/riemann-sum.js +91 -0
- package/dist/marks/riemann-sum.js.map +1 -0
- package/dist/marks/tangent-line.d.ts +27 -0
- package/dist/marks/tangent-line.d.ts.map +1 -0
- package/dist/marks/tangent-line.js +103 -0
- package/dist/marks/tangent-line.js.map +1 -0
- package/dist/marks/vector-arrow.d.ts +32 -0
- package/dist/marks/vector-arrow.d.ts.map +1 -0
- package/dist/marks/vector-arrow.js +87 -0
- package/dist/marks/vector-arrow.js.map +1 -0
- package/dist/nodes.d.ts +35 -0
- package/dist/nodes.d.ts.map +1 -0
- package/dist/nodes.js +63 -0
- package/dist/nodes.js.map +1 -0
- package/dist/plots/function-plot.d.ts +67 -0
- package/dist/plots/function-plot.d.ts.map +1 -0
- package/dist/plots/function-plot.js +215 -0
- package/dist/plots/function-plot.js.map +1 -0
- package/dist/plots/points-plot.d.ts +28 -0
- package/dist/plots/points-plot.d.ts.map +1 -0
- package/dist/plots/points-plot.js +99 -0
- package/dist/plots/points-plot.js.map +1 -0
- package/dist/plots/stream-lines.d.ts +35 -0
- package/dist/plots/stream-lines.d.ts.map +1 -0
- package/dist/plots/stream-lines.js +141 -0
- package/dist/plots/stream-lines.js.map +1 -0
- package/dist/plots/traced-path.d.ts +31 -0
- package/dist/plots/traced-path.d.ts.map +1 -0
- package/dist/plots/traced-path.js +56 -0
- package/dist/plots/traced-path.js.map +1 -0
- package/dist/plots/vector-field.d.ts +23 -0
- package/dist/plots/vector-field.d.ts.map +1 -0
- package/dist/plots/vector-field.js +91 -0
- package/dist/plots/vector-field.js.map +1 -0
- package/dist/structures/graph-layout.d.ts +11 -0
- package/dist/structures/graph-layout.d.ts.map +1 -0
- package/dist/structures/graph-layout.js +135 -0
- package/dist/structures/graph-layout.js.map +1 -0
- package/dist/structures/network-graph.d.ts +83 -0
- package/dist/structures/network-graph.d.ts.map +1 -0
- package/dist/structures/network-graph.js +289 -0
- package/dist/structures/network-graph.js.map +1 -0
- package/dist/structures/sample-space.d.ts +62 -0
- package/dist/structures/sample-space.d.ts.map +1 -0
- package/dist/structures/sample-space.js +199 -0
- package/dist/structures/sample-space.js.map +1 -0
- package/dist/systems/axes2d.d.ts +75 -0
- package/dist/systems/axes2d.d.ts.map +1 -0
- package/dist/systems/axes2d.js +193 -0
- package/dist/systems/axes2d.js.map +1 -0
- package/dist/systems/number-line.d.ts +49 -0
- package/dist/systems/number-line.d.ts.map +1 -0
- package/dist/systems/number-line.js +127 -0
- package/dist/systems/number-line.js.map +1 -0
- package/dist/systems/number-plane.d.ts +59 -0
- package/dist/systems/number-plane.d.ts.map +1 -0
- package/dist/systems/number-plane.js +193 -0
- package/dist/systems/number-plane.js.map +1 -0
- package/dist/systems/polar-plane.d.ts +48 -0
- package/dist/systems/polar-plane.d.ts.map +1 -0
- package/dist/systems/polar-plane.js +165 -0
- package/dist/systems/polar-plane.js.map +1 -0
- package/dist/tex/geometry.d.ts +85 -0
- package/dist/tex/geometry.d.ts.map +1 -0
- package/dist/tex/geometry.js +632 -0
- package/dist/tex/geometry.js.map +1 -0
- package/dist/tex/index.d.ts +11 -0
- package/dist/tex/index.d.ts.map +1 -0
- package/dist/tex/index.js +9 -0
- package/dist/tex/index.js.map +1 -0
- package/dist/tex/mathjax.d.ts +33 -0
- package/dist/tex/mathjax.d.ts.map +1 -0
- package/dist/tex/mathjax.js +74 -0
- package/dist/tex/mathjax.js.map +1 -0
- package/dist/tex/matrix.d.ts +31 -0
- package/dist/tex/matrix.d.ts.map +1 -0
- package/dist/tex/matrix.js +73 -0
- package/dist/tex/matrix.js.map +1 -0
- package/dist/tex/node.d.ts +215 -0
- package/dist/tex/node.d.ts.map +1 -0
- package/dist/tex/node.js +595 -0
- package/dist/tex/node.js.map +1 -0
- package/dist/tex/tween.d.ts +50 -0
- package/dist/tex/tween.d.ts.map +1 -0
- package/dist/tex/tween.js +253 -0
- package/dist/tex/tween.js.map +1 -0
- package/dist/three/axes3d.d.ts +87 -0
- package/dist/three/axes3d.d.ts.map +1 -0
- package/dist/three/axes3d.js +228 -0
- package/dist/three/axes3d.js.map +1 -0
- package/dist/three/curve-plot3d.d.ts +60 -0
- package/dist/three/curve-plot3d.d.ts.map +1 -0
- package/dist/three/curve-plot3d.js +143 -0
- package/dist/three/curve-plot3d.js.map +1 -0
- package/dist/three/label3d.d.ts +11 -0
- package/dist/three/label3d.d.ts.map +1 -0
- package/dist/three/label3d.js +40 -0
- package/dist/three/label3d.js.map +1 -0
- package/dist/three/plot-point3d.d.ts +26 -0
- package/dist/three/plot-point3d.d.ts.map +1 -0
- package/dist/three/plot-point3d.js +60 -0
- package/dist/three/plot-point3d.js.map +1 -0
- package/dist/three/space.d.ts +28 -0
- package/dist/three/space.d.ts.map +1 -0
- package/dist/three/space.js +47 -0
- package/dist/three/space.js.map +1 -0
- package/dist/three/surface-plot3d.d.ts +80 -0
- package/dist/three/surface-plot3d.d.ts.map +1 -0
- package/dist/three/surface-plot3d.js +290 -0
- package/dist/three/surface-plot3d.js.map +1 -0
- package/dist/three/vector-arrow3d.d.ts +25 -0
- package/dist/three/vector-arrow3d.d.ts.map +1 -0
- package/dist/three/vector-arrow3d.js +72 -0
- package/dist/three/vector-arrow3d.js.map +1 -0
- package/package.json +79 -3
- package/registry.json +251 -0
- package/src/annotate/angle-mark.ts +147 -0
- package/src/annotate/curly-brace.ts +126 -0
- package/src/annotate/emphasis-mark.ts +89 -0
- package/src/engine.ts +72 -0
- package/src/index.ts +29 -0
- package/src/kit/brace.ts +37 -0
- package/src/kit/cache.ts +61 -0
- package/src/kit/contour.ts +94 -0
- package/src/kit/coords.ts +278 -0
- package/src/kit/curve.ts +29 -0
- package/src/kit/equation.ts +181 -0
- package/src/kit/equation3d.ts +137 -0
- package/src/kit/expression.ts +159 -0
- package/src/kit/field-mark.ts +155 -0
- package/src/kit/field.ts +50 -0
- package/src/kit/follow.ts +203 -0
- package/src/kit/furniture.ts +108 -0
- package/src/kit/geometry.ts +49 -0
- package/src/kit/mark.ts +131 -0
- package/src/kit/part-fills.ts +61 -0
- package/src/kit/place.ts +101 -0
- package/src/kit/placement.ts +8 -0
- package/src/kit/sampler.ts +281 -0
- package/src/kit/scale.ts +39 -0
- package/src/kit/source.ts +57 -0
- package/src/kit/system.ts +99 -0
- package/src/kit/ticks.ts +85 -0
- package/src/kit/withdrawn.ts +8 -0
- package/src/marks/curve-area.ts +89 -0
- package/src/marks/drop-lines.ts +63 -0
- package/src/marks/plot-point.ts +107 -0
- package/src/marks/riemann-sum.ts +98 -0
- package/src/marks/tangent-line.ts +103 -0
- package/src/marks/vector-arrow.ts +98 -0
- package/src/nodes.ts +63 -0
- package/src/plots/function-plot.ts +236 -0
- package/src/plots/points-plot.ts +107 -0
- package/src/plots/stream-lines.ts +151 -0
- package/src/plots/traced-path.ts +52 -0
- package/src/plots/vector-field.ts +88 -0
- package/src/structures/graph-layout.ts +145 -0
- package/src/structures/network-graph.ts +308 -0
- package/src/structures/sample-space.ts +209 -0
- package/src/systems/axes2d.ts +217 -0
- package/src/systems/number-line.ts +131 -0
- package/src/systems/number-plane.ts +203 -0
- package/src/systems/polar-plane.ts +176 -0
- package/src/tex/geometry.ts +703 -0
- package/src/tex/index.ts +14 -0
- package/src/tex/mathjax.ts +82 -0
- package/src/tex/matrix.ts +75 -0
- package/src/tex/node.ts +641 -0
- package/src/tex/tween.ts +308 -0
- package/src/three/axes3d.ts +240 -0
- package/src/three/curve-plot3d.ts +147 -0
- package/src/three/label3d.ts +50 -0
- package/src/three/plot-point3d.ts +66 -0
- package/src/three/space.ts +67 -0
- package/src/three/surface-plot3d.ts +323 -0
- package/src/three/vector-arrow3d.ts +77 -0
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { expressionOps } from "@motionscript/sdk";
|
|
2
|
+
import type { ExpressionDialect, ExpressionNode } from "@motionscript/sdk";
|
|
3
|
+
import { createBoundedCache } from "./cache";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The language a plot's equation is written in: the engine's own expression
|
|
7
|
+
* grammar (`expressionOps.parse`) under a dialect of its own, where trig is in
|
|
8
|
+
* radians, names are bare identifiers, and the logs and hyperbolics a plot
|
|
9
|
+
* wants are present. Never `new Function`: an equation is text stored in a
|
|
10
|
+
* document, and the shared parser can only produce arithmetic.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Named values an expression reads at call time, beside its two variables. */
|
|
14
|
+
export type ExpressionScope = Readonly<Record<string, number>>;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A compiled expression. The two variables are fixed slots because this is the
|
|
18
|
+
* hot path of every sampled curve; a one-variable expression never reads `b`.
|
|
19
|
+
*/
|
|
20
|
+
export type CompiledExpression = (a: number, b: number, scope?: ExpressionScope) => number;
|
|
21
|
+
|
|
22
|
+
const UNARY: Record<string, (v: number) => number> = {
|
|
23
|
+
sin: Math.sin, cos: Math.cos, tan: Math.tan,
|
|
24
|
+
asin: Math.asin, acos: Math.acos, atan: Math.atan,
|
|
25
|
+
sinh: Math.sinh, cosh: Math.cosh, tanh: Math.tanh,
|
|
26
|
+
sqrt: Math.sqrt, cbrt: Math.cbrt, abs: Math.abs, exp: Math.exp,
|
|
27
|
+
log: Math.log, ln: Math.log, log2: Math.log2, log10: Math.log10,
|
|
28
|
+
floor: Math.floor, ceil: Math.ceil, round: Math.round, sign: Math.sign, trunc: Math.trunc,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const NARY: Record<string, { fn: (...args: number[]) => number; arity: [number, number] }> = {
|
|
32
|
+
atan2: { fn: Math.atan2, arity: [2, 2] },
|
|
33
|
+
pow: { fn: Math.pow, arity: [2, 2] },
|
|
34
|
+
mod: { fn: (a, b) => a % b, arity: [2, 2] },
|
|
35
|
+
hypot: { fn: Math.hypot, arity: [1, Infinity] },
|
|
36
|
+
min: { fn: Math.min, arity: [1, Infinity] },
|
|
37
|
+
max: { fn: Math.max, arity: [1, Infinity] },
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const CONSTANTS: Record<string, number> = {
|
|
41
|
+
pi: Math.PI, PI: Math.PI, e: Math.E, E: Math.E, tau: Math.PI * 2, phi: (1 + Math.sqrt(5)) / 2,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const MATH_DIALECT: ExpressionDialect = {
|
|
45
|
+
functions: {
|
|
46
|
+
...Object.fromEntries(Object.keys(UNARY).map((name) => [name, { arity: [1, 1] as [number, number] }])),
|
|
47
|
+
...Object.fromEntries(Object.entries(NARY).map(([name, { arity }]) => [name, { arity }])),
|
|
48
|
+
},
|
|
49
|
+
constants: CONSTANTS,
|
|
50
|
+
refs: "bare",
|
|
51
|
+
unknownName: (name) => `Unknown name '${name}'`,
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** What an expression may name, for a host's "what can I write here" help. */
|
|
55
|
+
export interface ExpressionVocabulary {
|
|
56
|
+
variables: readonly string[];
|
|
57
|
+
functions: readonly string[];
|
|
58
|
+
constants: readonly string[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function expressionVocabulary(variables: readonly string[]): ExpressionVocabulary {
|
|
62
|
+
return {
|
|
63
|
+
variables,
|
|
64
|
+
functions: [...Object.keys(UNARY), ...Object.keys(NARY)].sort(),
|
|
65
|
+
constants: ["pi", "e", "tau", "phi"],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Compile `source` over up to two `variables`, in slot order, and any `params`
|
|
71
|
+
* it may read from the scope. Throws on a syntax error or an unknown name.
|
|
72
|
+
*/
|
|
73
|
+
export function compileExpression(
|
|
74
|
+
source: string,
|
|
75
|
+
variables: readonly string[],
|
|
76
|
+
params: readonly string[] = [],
|
|
77
|
+
): CompiledExpression {
|
|
78
|
+
// The parser folds a constant before it yields a reference, so a name that
|
|
79
|
+
// is both would silently stop being the variable it was passed as.
|
|
80
|
+
for (const name of [...variables, ...params]) {
|
|
81
|
+
if (Object.hasOwn(CONSTANTS, name)) throw new Error(`'${name}' is a constant, so it cannot be a variable`);
|
|
82
|
+
}
|
|
83
|
+
return emit(expressionOps.parse(source, MATH_DIALECT).root, variables, params);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function emit(node: ExpressionNode, variables: readonly string[], params: readonly string[]): CompiledExpression {
|
|
87
|
+
switch (node.kind) {
|
|
88
|
+
case "const": {
|
|
89
|
+
const { value } = node;
|
|
90
|
+
return () => value;
|
|
91
|
+
}
|
|
92
|
+
case "ref": {
|
|
93
|
+
const { name } = node;
|
|
94
|
+
const slot = variables.indexOf(name);
|
|
95
|
+
if (slot === 0) return (a) => a;
|
|
96
|
+
if (slot === 1) return (_a, b) => b;
|
|
97
|
+
if (params.includes(name)) return (_a, _b, scope) => scope?.[name] ?? NaN;
|
|
98
|
+
throw new Error(MATH_DIALECT.unknownName(name));
|
|
99
|
+
}
|
|
100
|
+
case "unary": {
|
|
101
|
+
const operand = emit(node.operand, variables, params);
|
|
102
|
+
return (a, b, s) => -operand(a, b, s);
|
|
103
|
+
}
|
|
104
|
+
case "binary": {
|
|
105
|
+
const l = emit(node.left, variables, params);
|
|
106
|
+
const r = emit(node.right, variables, params);
|
|
107
|
+
switch (node.op) {
|
|
108
|
+
case "+": return (a, b, s) => l(a, b, s) + r(a, b, s);
|
|
109
|
+
case "-": return (a, b, s) => l(a, b, s) - r(a, b, s);
|
|
110
|
+
case "*": return (a, b, s) => l(a, b, s) * r(a, b, s);
|
|
111
|
+
case "/": return (a, b, s) => l(a, b, s) / r(a, b, s);
|
|
112
|
+
case "%": return (a, b, s) => l(a, b, s) % r(a, b, s);
|
|
113
|
+
case "^": return (a, b, s) => Math.pow(l(a, b, s), r(a, b, s));
|
|
114
|
+
}
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
case "call": {
|
|
118
|
+
const args = node.args.map((arg) => emit(arg, variables, params));
|
|
119
|
+
const unary = UNARY[node.name];
|
|
120
|
+
if (unary) {
|
|
121
|
+
const [x] = args;
|
|
122
|
+
return (a, b, s) => unary(x(a, b, s));
|
|
123
|
+
}
|
|
124
|
+
const { fn } = NARY[node.name];
|
|
125
|
+
// The common arity, so the hot path allocates no array per sample.
|
|
126
|
+
if (args.length === 2) {
|
|
127
|
+
const [x, y] = args;
|
|
128
|
+
return (a, b, s) => fn(x(a, b, s), y(a, b, s));
|
|
129
|
+
}
|
|
130
|
+
return (a, b, s) => fn(...args.map((arg) => arg(a, b, s)));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
throw new Error("Unsupported expression");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const compiled = createBoundedCache<CompiledExpression | Error>(256);
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* {@link compileExpression}, memoised: equal source under equal names is the
|
|
140
|
+
* identical closure, so "did this expression change" is an `===`, and a failure
|
|
141
|
+
* is remembered rather than re-parsed every frame.
|
|
142
|
+
*/
|
|
143
|
+
export function compileExpressionCached(
|
|
144
|
+
source: string,
|
|
145
|
+
variables: readonly string[],
|
|
146
|
+
params: readonly string[] = [],
|
|
147
|
+
): CompiledExpression | Error {
|
|
148
|
+
const key = `${variables.join(",")}|${params.join(",")}|${source}`;
|
|
149
|
+
const hit = compiled.get(key);
|
|
150
|
+
if (hit !== undefined) return hit;
|
|
151
|
+
let result: CompiledExpression | Error;
|
|
152
|
+
try {
|
|
153
|
+
result = compileExpression(source, variables, params);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
result = error instanceof Error ? error : new Error(String(error));
|
|
156
|
+
}
|
|
157
|
+
compiled.set(key, result);
|
|
158
|
+
return result;
|
|
159
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import {
|
|
2
|
+
command,
|
|
3
|
+
Graphics2D,
|
|
4
|
+
property,
|
|
5
|
+
withdraw,
|
|
6
|
+
type Command,
|
|
7
|
+
type CommandArgs,
|
|
8
|
+
type Fill,
|
|
9
|
+
type FillResolved,
|
|
10
|
+
type PaintProps,
|
|
11
|
+
type RenderContext2D,
|
|
12
|
+
type StrokeResolved,
|
|
13
|
+
type Vector2,
|
|
14
|
+
} from "@motionscript/sdk";
|
|
15
|
+
import type { CoordinateMap } from "./coords";
|
|
16
|
+
import type { ExpressionScope } from "./expression";
|
|
17
|
+
import { fieldParams, parseField } from "./field";
|
|
18
|
+
import { boundsOfRuns, runsToPath, stated } from "./geometry";
|
|
19
|
+
import { Mark } from "./mark";
|
|
20
|
+
import { fillAt, lerpFillScale, readFillScale } from "./scale";
|
|
21
|
+
import { lerpParams, lerpSource, readSource, scopeFor, type PlotSource } from "./source";
|
|
22
|
+
import { FILL_PAINT, OUTLINE_TRIM } from "./withdrawn";
|
|
23
|
+
|
|
24
|
+
export interface FieldProps extends PaintProps {
|
|
25
|
+
expression?: string | PlotSource;
|
|
26
|
+
params?: ExpressionScope;
|
|
27
|
+
strengthFills?: Fill[];
|
|
28
|
+
maxMagnitude?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A field's vector at a graph point, written into `out`; `false` where it has none. */
|
|
32
|
+
export type FieldSampler = (x: number, y: number, out: Vector2) => boolean;
|
|
33
|
+
|
|
34
|
+
/** One thing a field draws, and how strong the field is there: what it is coloured by. */
|
|
35
|
+
export interface FieldStroke {
|
|
36
|
+
runs: Vector2[][];
|
|
37
|
+
magnitude: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** How many shades the strength fills are drawn in: each is one path. */
|
|
41
|
+
const SHADES = 12;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* A mark drawn from a vector field, `(P(x, y), Q(x, y))`: arrows, or the lines
|
|
45
|
+
* that follow it, all in one stroke. Without strength fills it is one path in
|
|
46
|
+
* the stroke's paint; with them, what it draws is sorted by the field's
|
|
47
|
+
* strength into a few shades.
|
|
48
|
+
*/
|
|
49
|
+
@withdraw(...FILL_PAINT, ...OUTLINE_TRIM)
|
|
50
|
+
export abstract class FieldMark<P extends FieldProps = FieldProps> extends Mark<P> {
|
|
51
|
+
@property({ default: "", mapper: readSource, tween: lerpSource, kind: "fieldEquation" })
|
|
52
|
+
declare expression: PlotSource;
|
|
53
|
+
|
|
54
|
+
/** The equation's named values: any name in it that is not `x`, `y`, a function or a constant. */
|
|
55
|
+
@property({ default: {}, tween: lerpParams }) declare params: ExpressionScope;
|
|
56
|
+
|
|
57
|
+
/** Paints by the field's strength, weakest first. Empty draws everything in the stroke's own paint. */
|
|
58
|
+
@property({ default: [], mapper: readFillScale, tween: lerpFillScale, kind: "vector" }) declare strengthFills: Fill[];
|
|
59
|
+
/** The strength the last paint stands for; zero takes the strongest the field is where it is drawn. */
|
|
60
|
+
@property({ default: 0, min: 0, step: 0.1 }) declare maxMagnitude: number;
|
|
61
|
+
|
|
62
|
+
/** Change the field, each vector turning from the one into the other. */
|
|
63
|
+
@command({ args: ["expression"] })
|
|
64
|
+
morphTo(args: CommandArgs<{ expression: string }> & { duration: number }): Command<P> {
|
|
65
|
+
return this.to({ data: stated(args.data) as Partial<P>, duration: args.duration, easing: args.easing });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Animate the equation's named values. */
|
|
69
|
+
@command({ args: ["params"] })
|
|
70
|
+
paramsTo(args: CommandArgs<{ params: ExpressionScope }> & { duration: number }): Command<P> {
|
|
71
|
+
return this.to({ data: stated(args.data) as Partial<P>, duration: args.duration, easing: args.easing });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** What is drawn of `field` through `map`. */
|
|
75
|
+
protected abstract strokes(map: CoordinateMap, field: FieldSampler): FieldStroke[];
|
|
76
|
+
|
|
77
|
+
/** The props of its own that change what {@link strokes} returns. */
|
|
78
|
+
protected abstract own(): string;
|
|
79
|
+
|
|
80
|
+
protected trace(map: CoordinateMap): Vector2[][] {
|
|
81
|
+
const { area } = map;
|
|
82
|
+
if (!Number.isFinite(area.maxX - area.minX)) return [];
|
|
83
|
+
const { source, blend } = this.expression;
|
|
84
|
+
const shift = this.shift();
|
|
85
|
+
const key = [source, blend?.from, blend?.t, map.revision, JSON.stringify(this.params), shift.x, shift.y, this.own()].join("|");
|
|
86
|
+
if (key !== this._key) {
|
|
87
|
+
this._key = key;
|
|
88
|
+
const field = this._sampler(shift);
|
|
89
|
+
this._drawn = field ? this.strokes(map, field) : [];
|
|
90
|
+
this._runs = this._drawn.flatMap((stroke) => stroke.runs);
|
|
91
|
+
}
|
|
92
|
+
return this._runs;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
protected override renderInk(ctx: RenderContext2D): void {
|
|
96
|
+
const scale = this.strengthFills as unknown as FillResolved[][];
|
|
97
|
+
const stroke = this.stroke as StrokeResolved[];
|
|
98
|
+
const ink = scale.length > 0 && stroke.length > 0 ? boundsOfRuns(this._runs) : null;
|
|
99
|
+
if (!ink) {
|
|
100
|
+
super.renderInk(ctx);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const top = this.maxMagnitude > 0 ? this.maxMagnitude : this._drawn.reduce((most, drawn) => Math.max(most, drawn.magnitude), 0);
|
|
104
|
+
const shades: Vector2[][][] = Array.from({ length: SHADES }, () => []);
|
|
105
|
+
for (const drawn of this._drawn) {
|
|
106
|
+
const share = top > 0 ? Math.min(1, drawn.magnitude / top) : 0;
|
|
107
|
+
shades[Math.min(SHADES - 1, Math.floor(share * SHADES))].push(...drawn.runs);
|
|
108
|
+
}
|
|
109
|
+
shades.forEach((runs, index) => {
|
|
110
|
+
if (runs.length === 0) return;
|
|
111
|
+
const fill = fillAt(scale, (index + 0.5) / SHADES);
|
|
112
|
+
ctx.draw(
|
|
113
|
+
new Graphics2D()
|
|
114
|
+
.path({ data: runsToPath(runs), centerBounds: [ink.minX, ink.minY, ink.maxX, ink.maxY], start: this.start, end: this.end })
|
|
115
|
+
.shadow(this.shadow)
|
|
116
|
+
.stroke(stroke.map((layer) => ({ ...layer, fill }))),
|
|
117
|
+
);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private _key = "";
|
|
122
|
+
private _drawn: FieldStroke[] = [];
|
|
123
|
+
private _runs: Vector2[][] = [];
|
|
124
|
+
|
|
125
|
+
/** The field at a graph point, measured from this mark's own shift, mid-morph a blend of two. */
|
|
126
|
+
private _sampler(shift: Vector2): FieldSampler | null {
|
|
127
|
+
const { source, blend } = this.expression;
|
|
128
|
+
const to = this._field(source, shift);
|
|
129
|
+
if (!to || !blend) return to;
|
|
130
|
+
const from = this._field(blend.from, shift);
|
|
131
|
+
if (!from) return to;
|
|
132
|
+
const start: Vector2 = { x: 0, y: 0 };
|
|
133
|
+
return (x, y, out) => {
|
|
134
|
+
if (!from(x, y, start) || !to(x, y, out)) return false;
|
|
135
|
+
out.x = start.x + (out.x - start.x) * blend.t;
|
|
136
|
+
out.y = start.y + (out.y - start.y) * blend.t;
|
|
137
|
+
return true;
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private _field(source: string, shift: Vector2): FieldSampler | null {
|
|
142
|
+
const names = fieldParams(source);
|
|
143
|
+
const field = parseField(source, names);
|
|
144
|
+
if (field instanceof Error) return null;
|
|
145
|
+
const params = scopeFor(names, this.params);
|
|
146
|
+
const { x, y } = field;
|
|
147
|
+
return (gx, gy, out) => {
|
|
148
|
+
const vx = x(gx - shift.x, gy - shift.y, params);
|
|
149
|
+
const vy = y(gx - shift.x, gy - shift.y, params);
|
|
150
|
+
out.x = vx;
|
|
151
|
+
out.y = vy;
|
|
152
|
+
return Number.isFinite(vx) && Number.isFinite(vy);
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
package/src/kit/field.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createBoundedCache } from "./cache";
|
|
2
|
+
import { equationNames, splitTuple } from "./equation";
|
|
3
|
+
import { compileExpressionCached, type CompiledExpression } from "./expression";
|
|
4
|
+
|
|
5
|
+
/** A vector at every point of the plane, two parts in `x` and `y`: `(-y, x)`. A warp is written the same way. */
|
|
6
|
+
export interface FieldEquation {
|
|
7
|
+
x: CompiledExpression;
|
|
8
|
+
y: CompiledExpression;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const FIELD_VARIABLES = ["x", "y"] as const;
|
|
12
|
+
|
|
13
|
+
const NAMES: ReadonlySet<string> = new Set(FIELD_VARIABLES);
|
|
14
|
+
const fields = createBoundedCache<FieldEquation | Error>(128);
|
|
15
|
+
|
|
16
|
+
/** The named values a field's equation reads: every name that is not `x` or `y`. */
|
|
17
|
+
export function fieldParams(source: string): readonly string[] {
|
|
18
|
+
return equationNames(source).filter((name) => !NAMES.has(name));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** `source` as a field, or the reason it is not one. Memoised, so an unchanged equation is the identical object. */
|
|
22
|
+
export function parseField(source: string, params: readonly string[] = []): FieldEquation | Error {
|
|
23
|
+
const key = `${params.join(",")}|${source}`;
|
|
24
|
+
const hit = fields.get(key);
|
|
25
|
+
if (hit !== undefined) return hit;
|
|
26
|
+
let result: FieldEquation | Error;
|
|
27
|
+
try {
|
|
28
|
+
const text = source.trim();
|
|
29
|
+
if (text === "") throw new Error("Empty equation");
|
|
30
|
+
const parts = splitTuple(text);
|
|
31
|
+
if (parts?.length !== 2) throw new Error("A field has two parts: (x, y)");
|
|
32
|
+
const [x, y] = parts.map((part) => {
|
|
33
|
+
const compiled = compileExpressionCached(part.trim(), FIELD_VARIABLES, params);
|
|
34
|
+
if (compiled instanceof Error) throw compiled;
|
|
35
|
+
return compiled;
|
|
36
|
+
});
|
|
37
|
+
result = { x, y };
|
|
38
|
+
} catch (error) {
|
|
39
|
+
result = error instanceof Error ? error : new Error(String(error));
|
|
40
|
+
}
|
|
41
|
+
fields.set(key, result);
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Why `source` is not a field, or `null`; empty text is not an error. */
|
|
46
|
+
export function fieldError(source: string): string | null {
|
|
47
|
+
if (source.trim() === "") return null;
|
|
48
|
+
const field = parseField(source, fieldParams(source));
|
|
49
|
+
return field instanceof Error ? field.message : null;
|
|
50
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import {
|
|
2
|
+
command,
|
|
3
|
+
findNode2D,
|
|
4
|
+
frameIn,
|
|
5
|
+
Graphics2D,
|
|
6
|
+
PaintNode,
|
|
7
|
+
pathOps,
|
|
8
|
+
property,
|
|
9
|
+
withdraw,
|
|
10
|
+
type BoxBounds,
|
|
11
|
+
type Command,
|
|
12
|
+
type CommandArgs,
|
|
13
|
+
type Node2D,
|
|
14
|
+
type PaintProps,
|
|
15
|
+
type PathCommand,
|
|
16
|
+
type Size2D,
|
|
17
|
+
type Vector2,
|
|
18
|
+
} from "@motionscript/sdk";
|
|
19
|
+
import { FILL_PAINT } from "./withdrawn";
|
|
20
|
+
|
|
21
|
+
/** A node with parts that can be pointed at by name: a formula's terms. */
|
|
22
|
+
export interface Parted {
|
|
23
|
+
/** The box of `part`, y-up from the node's centre, or `null` when it has no such part. */
|
|
24
|
+
partBounds(part: string, occurrence?: number): BoxBounds | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isParted(node: object): node is Parted {
|
|
28
|
+
return typeof (node as Partial<Parted>).partBounds === "function";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** What a mark is drawn on: a node by id, and one part of it where it has parts. */
|
|
32
|
+
export interface Target {
|
|
33
|
+
on: string;
|
|
34
|
+
part?: string;
|
|
35
|
+
occurrence?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A target on its way to another: `t` of the way from `from`, or from the mark's resting target. */
|
|
39
|
+
export interface Retarget extends Target {
|
|
40
|
+
from?: Target | null;
|
|
41
|
+
t: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A target's four corners in its mark's own frame, y-up: top left, top right, bottom right, bottom left. */
|
|
45
|
+
export type Quad = [Vector2, Vector2, Vector2, Vector2];
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The node a mark is drawn on: the one `on` names, or, naming none, the nearest
|
|
49
|
+
* node with parts the mark sits inside. Putting a box in a formula is how it is
|
|
50
|
+
* told which.
|
|
51
|
+
*/
|
|
52
|
+
export function followed(mark: Node2D, on: string): Node2D | null {
|
|
53
|
+
if (on !== "") {
|
|
54
|
+
const node = findNode2D(mark, on);
|
|
55
|
+
return node && node !== mark ? node : null;
|
|
56
|
+
}
|
|
57
|
+
for (let at: Node2D | null = mark.parent; at; at = at.parent) {
|
|
58
|
+
if (isParted(at)) return at;
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Where `target` is, as `mark` sees it; `null` when it names no node or part. */
|
|
64
|
+
export function quadOf(mark: Node2D, target: Target): Quad | null {
|
|
65
|
+
const node = followed(mark, target.on);
|
|
66
|
+
if (!node) return null;
|
|
67
|
+
const box: BoxBounds | null =
|
|
68
|
+
target.part && isParted(node)
|
|
69
|
+
? node.partBounds(target.part, target.occurrence || 1)
|
|
70
|
+
: { x: 0, y: 0, width: node.layoutBounds.width, height: node.layoutBounds.height };
|
|
71
|
+
if (!box) return null;
|
|
72
|
+
const frame = frameIn(mark, node);
|
|
73
|
+
const turn = (frame.rotation * Math.PI) / 180;
|
|
74
|
+
const cos = Math.cos(turn);
|
|
75
|
+
const sin = Math.sin(turn);
|
|
76
|
+
// The engine's turn is clockwise, in a y-up frame.
|
|
77
|
+
const place = (x: number, y: number): Vector2 => ({
|
|
78
|
+
x: frame.x + (cos * x + sin * y) * frame.scale,
|
|
79
|
+
y: frame.y + (-sin * x + cos * y) * frame.scale,
|
|
80
|
+
});
|
|
81
|
+
const w = box.width / 2;
|
|
82
|
+
const h = box.height / 2;
|
|
83
|
+
return [place(box.x - w, box.y + h), place(box.x + w, box.y + h), place(box.x + w, box.y - h), place(box.x - w, box.y - h)];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function lerpQuad(a: Quad, b: Quad, t: number): Quad {
|
|
87
|
+
return a.map((from, i) => ({ x: from.x + (b[i].x - from.x) * t, y: from.y + (b[i].y - from.y) * t })) as Quad;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const restOf = ({ on, part, occurrence }: Target): Target => ({ on, part, occurrence });
|
|
91
|
+
|
|
92
|
+
function lerpRetarget(from: Retarget | null, to: Retarget | null, t: number): Retarget | null {
|
|
93
|
+
if (t <= 0 || !to) return t < 1 ? from : to;
|
|
94
|
+
return { ...restOf(to), from: from ? restOf(from) : null, t };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface FollowProps extends PaintProps {
|
|
98
|
+
on?: string;
|
|
99
|
+
part?: string;
|
|
100
|
+
occurrence?: number;
|
|
101
|
+
retarget?: Retarget | null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Every drawn point's centre frame: the mark's own centre, so its outline is where it says. */
|
|
105
|
+
const OWN_FRAME: [number, number, number, number] = [-1, -1, 1, 1];
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* A mark drawn on another node, or on one part of a formula: a brace, a box,
|
|
109
|
+
* an underline. It has no size of its own and takes no place in a layout; it
|
|
110
|
+
* is drawn where its target is, wherever the two are in the tree, and its
|
|
111
|
+
* selection box is its ink.
|
|
112
|
+
*/
|
|
113
|
+
@withdraw(...FILL_PAINT)
|
|
114
|
+
export abstract class FollowMark<P extends FollowProps = FollowProps> extends PaintNode<P> {
|
|
115
|
+
/** The node this mark is drawn on, by id. Left empty, it is the formula the mark sits inside. */
|
|
116
|
+
@property({ default: "", kind: "nodeRef", animatable: false }) declare on: string;
|
|
117
|
+
/** One part of that node, by its source, where it has parts: `x^2` of a formula. */
|
|
118
|
+
@property({ default: "", animatable: false }) declare part: string;
|
|
119
|
+
/** Which of the places the part is written, counted from 1. */
|
|
120
|
+
@property({ default: 1, min: 1, step: 1, animatable: false }) declare occurrence: number;
|
|
121
|
+
/** Where a `retargetTo` has taken the mark, and how far along it is. Not an author's to state. */
|
|
122
|
+
@property({ default: null, tween: lerpRetarget }) declare retarget: Retarget | null;
|
|
123
|
+
|
|
124
|
+
/** Move the mark onto another node, or another part. */
|
|
125
|
+
@command({
|
|
126
|
+
args: [
|
|
127
|
+
{ key: "on", kind: "nodeRef" },
|
|
128
|
+
{ key: "part", kind: "text", default: "" },
|
|
129
|
+
{ key: "occurrence", kind: "number", min: 1, step: 1, default: 1 },
|
|
130
|
+
],
|
|
131
|
+
})
|
|
132
|
+
retargetTo(args: CommandArgs<Partial<Target>> & { duration: number }): Command<P> {
|
|
133
|
+
const next = args.data ?? {};
|
|
134
|
+
const held = this.retarget ?? this;
|
|
135
|
+
const to: Retarget = {
|
|
136
|
+
on: next.on ?? held.on,
|
|
137
|
+
part: next.part ?? (next.on ? "" : held.part),
|
|
138
|
+
occurrence: next.occurrence ?? 1,
|
|
139
|
+
t: 1,
|
|
140
|
+
};
|
|
141
|
+
return this.to({ data: { retarget: to } as Partial<P>, duration: args.duration, easing: args.easing });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The outline to draw around `quad`, in the mark's own frame, y-up. */
|
|
145
|
+
protected abstract outline(quad: Quad): PathCommand[];
|
|
146
|
+
|
|
147
|
+
/** The target's corners now: its resting one, or part-way to where a `retargetTo` is taking it. */
|
|
148
|
+
protected quad(): Quad | null {
|
|
149
|
+
const state = this.retarget;
|
|
150
|
+
if (!state) return quadOf(this, this);
|
|
151
|
+
const to = quadOf(this, state);
|
|
152
|
+
const from = quadOf(this, state.from ?? this);
|
|
153
|
+
if (!from || !to || state.t >= 1) return to ?? from;
|
|
154
|
+
return lerpQuad(from, to, state.t);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
override measure(): Partial<Size2D> {
|
|
158
|
+
return { width: 0, height: 0 };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
protected override shapeGraphics(): Graphics2D | null {
|
|
162
|
+
const data = this._outline();
|
|
163
|
+
if (data.length === 0) return null;
|
|
164
|
+
return new Graphics2D().path({ data, centerBounds: OWN_FRAME, start: this.start, end: this.end });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
override _localBounds(): BoxBounds {
|
|
168
|
+
const ink = pathOps.bounds(this._outline());
|
|
169
|
+
if (!ink) return { x: 0, y: 0, width: 0, height: 0 };
|
|
170
|
+
return { x: (ink.minX + ink.maxX) / 2, y: (ink.minY + ink.maxY) / 2, width: ink.maxX - ink.minX, height: ink.maxY - ink.minY };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private _outline(): PathCommand[] {
|
|
174
|
+
const quad = this.quad();
|
|
175
|
+
return quad ? this.outline(quad) : [];
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// --- Geometry the marks share ---
|
|
180
|
+
|
|
181
|
+
export const add = (a: Vector2, b: Vector2, k = 1): Vector2 => ({ x: a.x + b.x * k, y: a.y + b.y * k });
|
|
182
|
+
export const between = (a: Vector2, b: Vector2, t = 0.5): Vector2 => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });
|
|
183
|
+
|
|
184
|
+
/** The unit vector from `a` to `b`, and its length; a zero one points right. */
|
|
185
|
+
export function heading(a: Vector2, b: Vector2): { unit: Vector2; length: number } {
|
|
186
|
+
const dx = b.x - a.x;
|
|
187
|
+
const dy = b.y - a.y;
|
|
188
|
+
const length = Math.hypot(dx, dy);
|
|
189
|
+
return { unit: length === 0 ? { x: 1, y: 0 } : { x: dx / length, y: dy / length }, length };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** A quad grown by `by` pixels on every side, along its own edges. */
|
|
193
|
+
export function grown(quad: Quad, by: number): Quad {
|
|
194
|
+
const [tl, tr, br, bl] = quad;
|
|
195
|
+
const across = heading(tl, tr).unit;
|
|
196
|
+
const up = heading(bl, tl).unit;
|
|
197
|
+
return [
|
|
198
|
+
add(add(tl, across, -by), up, by),
|
|
199
|
+
add(add(tr, across, by), up, by),
|
|
200
|
+
add(add(br, across, by), up, -by),
|
|
201
|
+
add(add(bl, across, -by), up, -by),
|
|
202
|
+
];
|
|
203
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { Fills, Graphics2D, toPathString, type AssetScope, type Color, type StrokeResolved, type Vector2 } from "@motionscript/sdk";
|
|
2
|
+
import { buildLatexPath, LatexNotLoaded, loadMathJax, MATHJAX_LOADER } from "../tex/geometry";
|
|
3
|
+
import type { Interval } from "./coords";
|
|
4
|
+
|
|
5
|
+
/** Shared drawing for the systems' own furniture: axis lines, tick marks and their numbers. */
|
|
6
|
+
|
|
7
|
+
/** What a system draws its axes and numbers in, and a plot its curve, until told otherwise. */
|
|
8
|
+
export const AXIS_COLOR = "#9ca3af";
|
|
9
|
+
export const PLOT_COLOR = "#58a6ff";
|
|
10
|
+
|
|
11
|
+
/** A stroke without end markers: an axis wears a tip, its ticks do not. */
|
|
12
|
+
export function withoutTips(stroke: StrokeResolved[]): StrokeResolved[] {
|
|
13
|
+
return stroke.map((layer) => ({ ...layer, startCap: undefined, endCap: undefined }));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface LabelStyle {
|
|
17
|
+
fontSize: number;
|
|
18
|
+
fontFamily: string;
|
|
19
|
+
color: Color;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Label {
|
|
23
|
+
text: string;
|
|
24
|
+
/** Where the label's box is anchored, in pixels. */
|
|
25
|
+
at: Vector2;
|
|
26
|
+
align: "left" | "center" | "right";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** How wide a label's box is, in ems: room for a long number, so alignment is by the box's edge. */
|
|
30
|
+
const LABEL_BOX_EM = 8;
|
|
31
|
+
|
|
32
|
+
/** A label written between dollar signs is a formula: `$\\frac{\\pi}{2}$`. */
|
|
33
|
+
const FORMULA = /^\$([\s\S]+)\$$/;
|
|
34
|
+
|
|
35
|
+
/** Ask the host for MathJax when any of `texts` is a formula, so it is there before the node is laid out. */
|
|
36
|
+
export function declareFormulas(assets: AssetScope, texts: readonly string[]): void {
|
|
37
|
+
if (texts.some((text) => FORMULA.test(text.trim()))) assets.loader(MATHJAX_LOADER, loadMathJax, { gate: "layout" });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What draws `labels`: text in the scene's face, and a typeset formula for each one written as such. */
|
|
41
|
+
export function drawLabels(labels: readonly Label[], style: LabelStyle): Graphics2D[] {
|
|
42
|
+
const out: Graphics2D[] = [];
|
|
43
|
+
const fill = Fills.color(style.color);
|
|
44
|
+
const text = new Graphics2D();
|
|
45
|
+
const width = style.fontSize * LABEL_BOX_EM;
|
|
46
|
+
let written = false;
|
|
47
|
+
for (const label of labels) {
|
|
48
|
+
const formula = FORMULA.exec(label.text.trim());
|
|
49
|
+
const glyphs = formula ? typeset(formula[1], label, style.fontSize) : null;
|
|
50
|
+
if (glyphs) {
|
|
51
|
+
for (const glyph of glyphs) out.push(glyph.fill(fill));
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const { at, align } = label;
|
|
55
|
+
written = true;
|
|
56
|
+
text.text({
|
|
57
|
+
text: label.text,
|
|
58
|
+
fontSize: style.fontSize,
|
|
59
|
+
// An empty family is left out, so the label takes the scene's own face.
|
|
60
|
+
...(style.fontFamily === "" ? {} : { fontFamily: style.fontFamily }),
|
|
61
|
+
wrap: false,
|
|
62
|
+
width,
|
|
63
|
+
textAlign: align,
|
|
64
|
+
x: align === "center" ? at.x : align === "right" ? at.x - width / 2 : at.x + width / 2,
|
|
65
|
+
y: at.y,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (written) out.push(text.fill(fill));
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// A formula's glyphs with its box anchored at the label's point; `null` for one that will not typeset, which is then
|
|
73
|
+
// drawn as written, and nothing at all while MathJax is still on its way: its source is not a stand-in for it.
|
|
74
|
+
function typeset(source: string, { at, align }: Label, fontSize: number): Graphics2D[] | null {
|
|
75
|
+
let formula: ReturnType<typeof buildLatexPath>;
|
|
76
|
+
try {
|
|
77
|
+
formula = buildLatexPath(source, fontSize);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
return error instanceof LatexNotLoaded ? [] : null;
|
|
80
|
+
}
|
|
81
|
+
const [minX, minY, maxX, maxY] = formula.bounds;
|
|
82
|
+
const dx = at.x + (align === "left" ? formula.width / 2 : align === "right" ? -formula.width / 2 : 0);
|
|
83
|
+
// Glyph paths are y-down; the frame whose centre lands on the node's is shifted the other way.
|
|
84
|
+
const frame: [number, number, number, number] = [minX - dx, minY + at.y, maxX - dx, maxY + at.y];
|
|
85
|
+
return formula.tokens.map((token) => new Graphics2D().path({ data: toPathString(token.path), centerBounds: frame }));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Whether a mark `u` of the way along an axis is inside the part of it drawn so far. */
|
|
89
|
+
export function drawn(u: number, start: number, end: number): boolean {
|
|
90
|
+
return u >= start - 1e-9 && u <= end + 1e-9;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** How far along `range` a value is, 0 to 1, by pixel distance. */
|
|
94
|
+
export function along(at: Vector2, from: Vector2, to: Vector2): number {
|
|
95
|
+
const dx = to.x - from.x;
|
|
96
|
+
const dy = to.y - from.y;
|
|
97
|
+
const length = dx * dx + dy * dy;
|
|
98
|
+
return length === 0 ? 0 : ((at.x - from.x) * dx + (at.y - from.y) * dy) / length;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function lerpInterval(from: Interval, to: Interval, t: number): Interval {
|
|
102
|
+
return [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function readInterval(value: Interval | undefined, previous?: Interval): Interval {
|
|
106
|
+
const [min, max] = Array.isArray(value) ? value : (previous ?? [0, 1]);
|
|
107
|
+
return [Number(min), Number(max)];
|
|
108
|
+
}
|