@liqweed/motion-kit 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +4 -2
- package/docs/spec/technique.md +71 -2
- package/examples/isometric-swivel.scene.mjs +171 -0
- package/lib/check.mjs +33 -0
- package/package.json +2 -2
- package/runtime/iso.mjs +583 -0
- package/runtime/kit.mjs +5 -3
- package/runtime/scene.mjs +7 -1
- package/runtime/svg.mjs +47 -0
- package/skills/animated-diagram/SKILL.md +3 -2
- package/skills/animated-diagram/references/custom-scenes.md +49 -0
- package/skills/animated-diagram/references/motion-vocabulary.md +23 -0
- package/skills/animated-diagram/references/scene-types.md +3 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "motion-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Deterministic animated diagrams: scenes as pure functions of time for live pages, Slidev, slide frames, baked SVG and video; plus project logos/icons.",
|
|
5
5
|
"author": { "name": "Ophir Radnitz" },
|
|
6
6
|
"repository": "https://github.com/liqweed/motion-kit",
|
package/README.md
CHANGED
|
@@ -56,7 +56,8 @@ dependency) or Chrome; video: `ffmpeg`.
|
|
|
56
56
|
```
|
|
57
57
|
runtime/ dependency-free ES modules (browser + Node)
|
|
58
58
|
motion.mjs easing (exact cubic-bezier), progress, critically damped spring, retarget, split edges
|
|
59
|
-
svg.mjs escaping, rounding, el/text/fade, polyline + Bézier arc-length, drawOn
|
|
59
|
+
svg.mjs escaping, rounding, el/text/fade, polyline + Bézier arc-length, drawOn, several tokens
|
|
60
|
+
iso.mjs isometric kit for custom scenes: camera, solids, depth order, label anchors
|
|
60
61
|
wrap.mjs label wrapping with hard budgets
|
|
61
62
|
style.mjs tokens, neutral style, contrast checks, token resolution
|
|
62
63
|
scene.mjs scene contract, formats, renderSvg
|
|
@@ -70,7 +71,8 @@ lib/ Node-side: check (gate), export, build (HTML inliner), raster, v
|
|
|
70
71
|
adapters/ slidev (Vue), astro, element (custom element), page (README)
|
|
71
72
|
skills/ animated-diagram, motion-render, project-logo (Claude Code / Craft skills)
|
|
72
73
|
examples/ order-flow (sequence), smart-home (hub-spoke), incident (timeline),
|
|
73
|
-
web-stack (stack), custom-pulse (custom module)
|
|
74
|
+
web-stack (stack), custom-pulse (custom module),
|
|
75
|
+
isometric-swivel (custom module: isometric kit, several tokens)
|
|
74
76
|
bench/ heavy scene for npm run bench:player (live-player frame cost)
|
|
75
77
|
brand/ logo scene (built with motion-kit); renders go to assets/ + .idea/ (npm run media)
|
|
76
78
|
assets/ generated project icon: icon.svg, icon.png, icon-animated.svg
|
package/docs/spec/technique.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: motion-kit technique — normative specification
|
|
3
3
|
status: draft
|
|
4
|
-
last_updated: 2026-11-
|
|
4
|
+
last_updated: 2026-11-19
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# motion-kit technique — normative specification
|
|
@@ -39,6 +39,7 @@ A scene is a plain object (`runtime/scene.mjs:1-18`).
|
|
|
39
39
|
| `frame(t, ctx)` | `(number, {idPrefix}) → string` | MUST | Inner SVG markup at `t` (§2). `ctx.idPrefix` is unique to the rendered instance; every id the frame defines (clip paths, gradients, masks, markers, filters) MUST start with it, as `${idPrefix}-name` [gate] G14. A frame that defines no ids MAY ignore `ctx`. |
|
|
40
40
|
| `stepLabelsInFrame` | boolean | MAY | `false` declares narrative steps whose labels are not drawn; exempts the scene from gate rule G10 (`lib/check.mjs:74`; used by `examples/custom-pulse.scene.mjs:137`, `brand/logo.scene.mjs:108`). |
|
|
41
41
|
| `contrastPairs` | `{fg, bg, min, use?}[]` | MAY | Token pairs the scene draws beyond `CONTRAST_PAIRS` (§6); the gate checks the style against them in both themes [gate] G12 (`lib/check.mjs`, rule 8; used by `examples/custom-pulse.scene.mjs`). Tokens MUST be known and `min` in [1, 21]. |
|
|
42
|
+
| `labelBoxes(t)` | `(number) → LabelBox[]` | MAY | The box of every label `frame(t)` draws, in the scene's own coordinates (`{id, x, y, width, height, stem?, opacity?}`; `labelAnchor` returns one, §4.9). Must be a function [throws]. The gate fails a scene whose labels overlap, whose stems cross a label or that leave the picture [gate] G15 (`lib/check.mjs`, rule 9; each box MUST be `{id, x, y, width, height}` with finite numbers [gate]; used by `examples/isometric-swivel.scene.mjs`). |
|
|
42
43
|
| `type`, `format`, `locale` | string | MAY | Set by scene types; recorded in the export manifest (`lib/export.mjs:75-77`). |
|
|
43
44
|
|
|
44
45
|
- A scene MUST be produced by either a registered scene type —
|
|
@@ -47,7 +48,7 @@ A scene is a plain object (`runtime/scene.mjs:1-18`).
|
|
|
47
48
|
`sceneFromModule` (`runtime/kit.mjs`) with
|
|
48
49
|
`opts = { ...options, format, locale, kit }`. `options` are the caller's
|
|
49
50
|
serializable scene options, passed unchanged; option names `format`,
|
|
50
|
-
`locale` and `kit` throw. `kit` is the flat exports of the `motion`, `svg`, `style`, `scene` and `wrap` runtime modules (`KIT`); it has no `createScene`, scene types or player. Both paths
|
|
51
|
+
`locale` and `kit` throw. `kit` is the flat exports of the `motion`, `svg`, `iso`, `style`, `scene` and `wrap` runtime modules (`KIT`); it has no `createScene`, scene types or player. Both paths
|
|
51
52
|
run `validateScene`. The CLI (`--options`), the vendored gate and the Astro
|
|
52
53
|
adapter call `sceneFromModule`, so one module with the same options, format
|
|
53
54
|
and locale gives the same scene everywhere. A `build` page calls the factory
|
|
@@ -204,6 +205,70 @@ move ends at `start + lag + duration`, which is what step timing MUST budget.
|
|
|
204
205
|
opacities `1 − p` and `p` instead of interpolating colours, which would need
|
|
205
206
|
literals (`runtime/parts.mjs:1-8,68,94,109`).
|
|
206
207
|
|
|
208
|
+
### 4.8 Several tokens (`runtime/svg.mjs`)
|
|
209
|
+
|
|
210
|
+
- `tokenPoints(path, t, runs)` → `{index, progress, point, run}[]` for each
|
|
211
|
+
token in flight at `t`; `tokensAlong(path, t, runs, draw)` concatenates
|
|
212
|
+
`draw(point, {index, progress, run})` for them. `path` is anything with
|
|
213
|
+
`at(fraction) → point` (`polyline`, `cubic`, `path3`); `runs` is
|
|
214
|
+
`{start, duration, ease?, path?, hold?}[]`, one per token, each on its own
|
|
215
|
+
`path` if it has one and on `easeStandard` by default.
|
|
216
|
+
- A token is in flight while its eased progress is above 0 and below 1; with
|
|
217
|
+
`hold` it stays at the end of its path once it has arrived. Both are pure
|
|
218
|
+
functions of `t`: no token carries state from an earlier frame.
|
|
219
|
+
- Any number of tokens MAY move at the same time. The canon does not change:
|
|
220
|
+
they MUST move only between settled steps, so every token has arrived (or is
|
|
221
|
+
held still) at each step's `at` and the gate's settled-frame rule (G6)
|
|
222
|
+
holds. A token MUST NOT loop or restart: a scene plays once (§2).
|
|
223
|
+
|
|
224
|
+
### 4.9 Isometric kit (`runtime/iso.mjs`)
|
|
225
|
+
|
|
226
|
+
For custom scenes that draw a 3D view; handed to them in `kit`. Pure
|
|
227
|
+
functions; a colour is a token name, resolved with `tok()` (G4 applies).
|
|
228
|
+
|
|
229
|
+
- **Camera.** `camera({azimuth, elevation, zoom, pan})` (degrees, pixels per
|
|
230
|
+
world unit, and the screen position of the world origin; defaults: 45°,
|
|
231
|
+
`ISO_ELEVATION` = atan(1/√2) ≈ 35.264°, 1, the screen origin). `elevation`
|
|
232
|
+
MUST be in [0, 90], `zoom` > 0 [throws]. World: x east, y north, z up.
|
|
233
|
+
The projection is orthographic:
|
|
234
|
+
`x' = pan.x + zoom·u`, `y' = pan.y − zoom·(v·sin el + z·cos el)`,
|
|
235
|
+
`depth = −v·cos el + z·sin el`, with `u = x·cos az + y·sin az` and
|
|
236
|
+
`v = −x·sin az + y·cos az`. At 90° elevation the result does not depend on
|
|
237
|
+
`z`: the plan view, which has north up at azimuth 0 (sine and cosine are exact
|
|
238
|
+
at multiples of 90°); at the default 45° azimuth north points up and right.
|
|
239
|
+
`projector(cam)` / `project(cam, p)` give `{x, y, depth}`; larger `depth` is
|
|
240
|
+
nearer the viewer.
|
|
241
|
+
- **Swivel.** `lerpCamera(a, b, p)` interpolates every field linearly (`a` at
|
|
242
|
+
`p ≤ 0`, `b` at `p ≥ 1`); `fitCamera(points, cam, {width, height, margin})`
|
|
243
|
+
returns `cam` with the pan and zoom that centre and fit the points in what
|
|
244
|
+
the margins leave. A swivel is a move between two settled steps (§8).
|
|
245
|
+
- **Solids.** `prism({points, h, z, fill, sides, shade, stroke, strokeWidth,
|
|
246
|
+
opacity, id})` extrudes a convex footprint (any winding; stored
|
|
247
|
+
counter-clockwise) from base height `z` by `h` ≥ 0; `box` (centred on x, y)
|
|
248
|
+
and `slab` (default `h` 0.25) are rectangular prisms; `regularPolygon` makes
|
|
249
|
+
a footprint. A non-convex, degenerate or too-small footprint, an unknown
|
|
250
|
+
token or a negative height throws. `fill` is the token of the top face,
|
|
251
|
+
`sides` of the side faces (default `fill`); `shade` (default `ink`, `null`
|
|
252
|
+
for none) is layered over each side at an opacity from 0.10 to 0.26 by how
|
|
253
|
+
far the face turns from screen left. Faces are `<path>`s outlined with
|
|
254
|
+
`stroke`; only faces that face the camera are drawn (the top when elevation
|
|
255
|
+
> 0, a side when its outward normal faces the camera and elevation < 90°).
|
|
256
|
+
- **Depth order.** `orderSolids(solids, cam)` returns the solids far to near.
|
|
257
|
+
Two solids whose projections overlap are ordered by the axes that separate
|
|
258
|
+
them (a footprint edge, or height when seen from above); where the axes
|
|
259
|
+
disagree, or none separates them, they are not ordered. The result is a
|
|
260
|
+
topological sort, ties and cycles broken by the nearer centre, then by input
|
|
261
|
+
order: the same solids always give the same order. `drawSolids` draws in it.
|
|
262
|
+
- **Labels.** `labelAnchor(cam, {id, at, lines, fontSize, lift, side,
|
|
263
|
+
opacity})` draws a dot on the projected point, a vertical stem `lift` pixels
|
|
264
|
+
up and a label box above it (or beside its top), and returns the markup and
|
|
265
|
+
the `LabelBox`. `labelProblems(boxes, {width, height, gap = 4})` lists the
|
|
266
|
+
collisions G15 reports. Labels follow §7 (wrapped, localized, ≥ 14 px).
|
|
267
|
+
- **Paths.** `path3(points)` is a polyline through world points with its
|
|
268
|
+
length in world units, so a token keeps a constant speed whatever the camera
|
|
269
|
+
does when its progress is linear (`tokenPoints` defaults to `easeStandard`;
|
|
270
|
+
pass `ease: linear`).
|
|
271
|
+
|
|
207
272
|
## 5. Markup
|
|
208
273
|
|
|
209
274
|
- Text and attribute values MUST be escaped (`& < > " '`) via `esc`, `text` or
|
|
@@ -282,6 +347,9 @@ move ends at `start + lag + duration`, which is what step timing MUST budget.
|
|
|
282
347
|
or empty translation throws; null/undefined optional copy returns "".
|
|
283
348
|
- Labels are labels; sentences go in `detail`. Font size MUST NOT go below
|
|
284
349
|
14 px at 1× (§3).
|
|
350
|
+
- A scene that places labels in a projected or moving view (§4.9) SHOULD
|
|
351
|
+
declare their boxes in `labelBoxes` (§1); the gate then fails overlapping
|
|
352
|
+
labels in every format and locale (G15).
|
|
285
353
|
- Every shipped locale × format MUST pass the gate. `check` derives locales
|
|
286
354
|
from a `.json` spec's localized objects (keys `xx` or `xx-YY`)
|
|
287
355
|
(`lib/gate.mjs`). Modules export a non-empty unique `locales` array (default
|
|
@@ -543,6 +611,7 @@ remaining files are still checked; the exit code is 1 on any failure. `npm run g
|
|
|
543
611
|
| G12 | Style passes WCAG contrast in both themes for every pair in `CONTRAST_PAIRS` (once per run) and for each scene's `contrastPairs` (per scene). | `lib/gate.mjs`, `lib/check.mjs` (rule 8), `runtime/style.mjs` (`checkContrast`) | Legibility in light and dark, for the pairs actually drawn (§6). |
|
|
544
612
|
| G13 | Scene construction succeeds for the format × locale (validation, fit, collisions, wrapping). | `lib/gate.mjs` | Reject, don't invent: a broken picture never renders. |
|
|
545
613
|
| G14 | Rendered with two different `idPrefix` values, sampled frames share no `id`. | `lib/check.mjs` (rule 7) | Two instances on one page (wide and tall, or one diagram twice) must not share ids: `url(#x)` resolves to the first element with that id, and WCAG 2.1 SC 4.1.1 forbids duplicates. |
|
|
614
|
+
| G15 | If the scene defines `labelBoxes`, at each sampled time and each step time: no two boxes with `opacity` > 0 are closer than 4 px, no stem crosses another box and every box lies inside the picture (`0, 0, width, height`). `labelBoxes` MUST return an array and not throw. Each problem is reported once, at its first time. | `lib/check.mjs` (rule 9), `runtime/iso.mjs` (`labelProblems`) | Labels placed in a projected view move with the camera; nothing else checks them against one another. Opacity 0 is not drawn, so a scene hides labels while the camera moves. |
|
|
546
615
|
|
|
547
616
|
The gate checks structure, not looks. Visual review (before/after frames,
|
|
548
617
|
phone size, real-time playback, dark mode) is required by
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example custom scene: a plan view that swivels into isometric, then three
|
|
3
|
+
* work items travel a line of four stations at once.
|
|
4
|
+
*
|
|
5
|
+
* Shows the isometric kit (runtime/iso.mjs): a camera interpolated between the
|
|
6
|
+
* plan view and true isometric, fitted to the picture each frame (pan and
|
|
7
|
+
* zoom); solids (a slab, boxes and a hexagonal prism) coloured by tokens and
|
|
8
|
+
* depth ordered; label anchors with stems, whose boxes the gate checks; and
|
|
9
|
+
* several tokens on one path (`tokensAlong`), all inside a settled step.
|
|
10
|
+
* Nothing loops: the scene plays once and holds its last frame, and the
|
|
11
|
+
* swivel is one move between two settled steps. Pure: frame(t) depends only
|
|
12
|
+
* on t and constants.
|
|
13
|
+
*/
|
|
14
|
+
import { easeOut, easeStandard, linear, progress } from "../runtime/motion.mjs";
|
|
15
|
+
import { CAMERA_ISOMETRIC, CAMERA_PLAN, box, drawSolid, fitCamera, labelAnchor, lerpCamera, orderSolids, path3, prism, project, regularPolygon, slab } from "../runtime/iso.mjs";
|
|
16
|
+
import { FORMATS, localize } from "../runtime/scene.mjs";
|
|
17
|
+
import { tok } from "../runtime/style.mjs";
|
|
18
|
+
import { el, fade, num, tokensAlong } from "../runtime/svg.mjs";
|
|
19
|
+
import { wrapLabel } from "../runtime/wrap.mjs";
|
|
20
|
+
|
|
21
|
+
export const locales = ["en", "nl"];
|
|
22
|
+
|
|
23
|
+
const COPY = {
|
|
24
|
+
title: { en: "A floor plan that turns isometric", nl: "Een plattegrond die isometrisch draait" },
|
|
25
|
+
description: {
|
|
26
|
+
en: "Four stations stand on one floor, seen from above. The view swivels to isometric, and three work items travel the line at once.",
|
|
27
|
+
nl: "Vier stations staan op één vloer, van boven gezien. Het beeld draait naar isometrisch en drie werkitems reizen tegelijk langs de lijn.",
|
|
28
|
+
},
|
|
29
|
+
stations: [
|
|
30
|
+
{ en: "Intake", nl: "Intake" },
|
|
31
|
+
{ en: "Review", nl: "Controle" },
|
|
32
|
+
{ en: "Build", nl: "Bouw" },
|
|
33
|
+
{ en: "Deliver", nl: "Levering" },
|
|
34
|
+
],
|
|
35
|
+
steps: [
|
|
36
|
+
{ label: { en: "Seen from above", nl: "Van boven gezien" }, detail: { en: "Four stations on one floor, in plan.", nl: "Vier stations op één vloer, in plattegrond." } },
|
|
37
|
+
{ label: { en: "Turned isometric", nl: "Isometrisch gedraaid" }, detail: { en: "The same floor, now with height.", nl: "Dezelfde vloer, nu met hoogte." } },
|
|
38
|
+
{ label: { en: "Three items arrive", nl: "Drie items aangekomen" }, detail: { en: "Three work items travelled the line together.", nl: "Drie werkitems reisden samen langs de lijn." } },
|
|
39
|
+
],
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// World, in units: a 14 × 7 floor and four stations along a diagonal.
|
|
43
|
+
const FLOOR = { w: 14, d: 7, h: 0.3 };
|
|
44
|
+
const STATIONS = [
|
|
45
|
+
{ x: -4.5, y: -2, h: 0.8, hex: false },
|
|
46
|
+
{ x: -1.5, y: -0.7, h: 1.6, hex: false },
|
|
47
|
+
{ x: 1.5, y: 0.7, h: 1.2, hex: true },
|
|
48
|
+
{ x: 4.5, y: 2, h: 0.8, hex: false },
|
|
49
|
+
];
|
|
50
|
+
const CARRY = 2.5; // the height tokens travel at, above every station
|
|
51
|
+
const TOP = FLOOR.h;
|
|
52
|
+
|
|
53
|
+
// Timeline, in seconds. Every beat ends before the next one starts, so each
|
|
54
|
+
// step frame is settled (the gate checks it).
|
|
55
|
+
const ENTER = 0.4;
|
|
56
|
+
const STAGGER = 0.1;
|
|
57
|
+
const LABELS_IN = 0.9;
|
|
58
|
+
const LABEL_FADE = 0.4;
|
|
59
|
+
const STEP_PLAN = 1.6;
|
|
60
|
+
const LABELS_OUT = 1.9;
|
|
61
|
+
const SWIVEL_AT = 2.25;
|
|
62
|
+
const SWIVEL = 1.4;
|
|
63
|
+
const LABELS_BACK = 3.7;
|
|
64
|
+
const STEP_ISO = 4.3;
|
|
65
|
+
const GO = 4.4;
|
|
66
|
+
const GAP = 0.3;
|
|
67
|
+
const TRIP = 1.6;
|
|
68
|
+
const FILL = 0.3;
|
|
69
|
+
const RUNS = [0, 1, 2].map((i) => ({ start: GO + i * GAP, duration: TRIP, ease: linear }));
|
|
70
|
+
|
|
71
|
+
export default function make({ format = "16:9", locale = "en" } = {}) {
|
|
72
|
+
const f = FORMATS[format];
|
|
73
|
+
if (!f) throw new Error(`unknown format "${format}"`);
|
|
74
|
+
const W = f.width;
|
|
75
|
+
const H = f.height || (format === "tall" ? 520 : 400);
|
|
76
|
+
const names = COPY.stations.map((s) => wrapLabel(localize(s, locale), 12, 2));
|
|
77
|
+
const fs = 14;
|
|
78
|
+
|
|
79
|
+
// The fit's room: the labels stand above the stations, so the top margin is theirs.
|
|
80
|
+
// Neighbouring labels stand at two heights, further apart in a narrow picture, where they are closer.
|
|
81
|
+
const lifts = W < 600 ? [36, 112, 36, 112] : [36, 80, 36, 80];
|
|
82
|
+
const margin = { top: Math.max(...lifts) + 36, right: 20, bottom: 20, left: 20 };
|
|
83
|
+
// What the camera must keep in view: the floor, every station at full height, and the tokens' route.
|
|
84
|
+
const extent = [
|
|
85
|
+
...[-1, 1].flatMap((sx) => [-1, 1].map((sy) => ({ x: (sx * FLOOR.w) / 2, y: (sy * FLOOR.d) / 2, z: 0 }))),
|
|
86
|
+
...STATIONS.flatMap((s) => [-1, 1].flatMap((dx) => [-1, 1].map((dy) => ({ x: s.x + dx * 1.25, y: s.y + dy * 1.25, z: TOP + s.h })))),
|
|
87
|
+
...STATIONS.map((s) => ({ x: s.x, y: s.y, z: CARRY })),
|
|
88
|
+
];
|
|
89
|
+
const swivel = (/** @type {number} */ t) => progress(t, SWIVEL_AT, SWIVEL, easeStandard);
|
|
90
|
+
const cameraAt = (/** @type {number} */ t) => fitCamera(extent, lerpCamera(CAMERA_PLAN, CAMERA_ISOMETRIC, swivel(t)), { width: W, height: H, margin });
|
|
91
|
+
|
|
92
|
+
const route = path3(STATIONS.map((s) => ({ x: s.x, y: s.y, z: CARRY })));
|
|
93
|
+
// Station i is reached when the first token passes it: its share of the route, at constant speed.
|
|
94
|
+
let along = 0;
|
|
95
|
+
const reached = STATIONS.map((s, i) => {
|
|
96
|
+
if (i > 0) along += Math.hypot(s.x - STATIONS[i - 1].x, s.y - STATIONS[i - 1].y);
|
|
97
|
+
return RUNS[0].start + (along / route.length) * TRIP;
|
|
98
|
+
});
|
|
99
|
+
// The last token lands, and the last station has filled, before the last step.
|
|
100
|
+
const landed = Math.max(RUNS[RUNS.length - 1].start + TRIP, reached[reached.length - 1] + FILL);
|
|
101
|
+
const steps = [
|
|
102
|
+
{ at: STEP_PLAN, ...COPY.steps[0] },
|
|
103
|
+
{ at: STEP_ISO, ...COPY.steps[1] },
|
|
104
|
+
{ at: landed + 0.15, ...COPY.steps[2] },
|
|
105
|
+
];
|
|
106
|
+
const duration = steps[2].at + 0.35;
|
|
107
|
+
|
|
108
|
+
/** The solids at time t: the floor, then the stations (entering, rising with the swivel, filling). */
|
|
109
|
+
function scene(/** @type {number} */ t) {
|
|
110
|
+
const rise = progress(t, SWIVEL_AT + 0.1, SWIVEL, easeOut);
|
|
111
|
+
const floor = slab({ x: 0, y: 0, w: FLOOR.w, d: FLOOR.d, h: FLOOR.h, fill: "bg", opacity: progress(t, 0, ENTER) });
|
|
112
|
+
const stations = STATIONS.map((s, i) => {
|
|
113
|
+
const shape = { id: String(i), z: TOP, h: Math.max(0.02, s.h * rise), opacity: progress(t, STAGGER + i * STAGGER, ENTER) };
|
|
114
|
+
const make = (/** @type {string} */ fill) => (s.hex ? prism({ points: regularPolygon(s.x, s.y, 1.25, 6, 0), fill, ...shape }) : box({ x: s.x, y: s.y, w: 2, d: 2, fill, ...shape }));
|
|
115
|
+
const on = progress(t, reached[i], FILL, easeStandard);
|
|
116
|
+
return { base: make("surface"), on: on > 0 ? make("accent") : null, fill: on };
|
|
117
|
+
});
|
|
118
|
+
return { floor, stations };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The labels at time t, with their boxes: they stand while the camera rests. */
|
|
122
|
+
function labels(/** @type {number} */ t) {
|
|
123
|
+
const opacity = Math.max(progress(t, LABELS_IN, LABEL_FADE) * (1 - progress(t, LABELS_OUT, 0.25)), progress(t, LABELS_BACK, LABEL_FADE));
|
|
124
|
+
const cam = cameraAt(t);
|
|
125
|
+
const rise = progress(t, SWIVEL_AT + 0.1, SWIVEL, easeOut);
|
|
126
|
+
return STATIONS.map((s, i) => labelAnchor(cam, { id: `station-${i}`, at: { x: s.x, y: s.y, z: TOP + Math.max(0.02, s.h * rise) }, lines: names[i], fontSize: fs, lift: lifts[i], opacity }));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function frame(/** @type {number} */ t) {
|
|
130
|
+
const cam = cameraAt(t);
|
|
131
|
+
const { floor, stations } = scene(t);
|
|
132
|
+
const squash = Math.sin((cam.elevation * Math.PI) / 180); // a circle on the floor, seen at this elevation
|
|
133
|
+
// A token's size grows in over the first 8 % of its trip and shrinks out over the last 8 %.
|
|
134
|
+
const size = (/** @type {number} */ k) => Math.min(1, k / 0.08, (1 - k) / 0.08);
|
|
135
|
+
const out = [drawSolid(floor, cam)];
|
|
136
|
+
// A shadow under each token, on the floor, so its place in the world reads. Under the stations, which hide it.
|
|
137
|
+
out.push(
|
|
138
|
+
tokensAlong(route, t, RUNS, (p, { progress: k }) => {
|
|
139
|
+
const g = project(cam, { x: p.x, y: p.y, z: TOP });
|
|
140
|
+
return el("ellipse", { cx: g.x, cy: g.y, rx: 10 * size(k), ry: 10 * size(k) * squash, fill: tok("ink"), opacity: 0.18 });
|
|
141
|
+
}),
|
|
142
|
+
);
|
|
143
|
+
// Stations far to near, each with its reached layer fading in over the pending one.
|
|
144
|
+
for (const base of orderSolids(stations.map((s) => s.base), cam)) {
|
|
145
|
+
const s = stations[Number(base.id)];
|
|
146
|
+
out.push(drawSolid(base, cam), s.on ? fade(s.fill, {}, drawSolid(s.on, cam)) : "");
|
|
147
|
+
}
|
|
148
|
+
out.push(
|
|
149
|
+
tokensAlong(route, t, RUNS, (p, { progress: k }) => {
|
|
150
|
+
const a = project(cam, p);
|
|
151
|
+
return el("circle", { cx: a.x, cy: a.y, r: 7 * size(k), fill: tok("emphasis"), stroke: tok("bg"), "stroke-width": 1.5 });
|
|
152
|
+
}),
|
|
153
|
+
);
|
|
154
|
+
out.push(...labels(t).map((l) => l.markup));
|
|
155
|
+
return out.join("");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
id: `isometric-swivel-${format.replace(":", "x")}`,
|
|
160
|
+
width: W,
|
|
161
|
+
height: H,
|
|
162
|
+
duration,
|
|
163
|
+
title: localize(COPY.title, locale),
|
|
164
|
+
description: localize(COPY.description, locale),
|
|
165
|
+
// Steps are beats of the story: their labels live in the player's controls, not in the drawing.
|
|
166
|
+
stepLabelsInFrame: false,
|
|
167
|
+
steps: steps.map((s) => ({ at: s.at, label: localize(s.label, locale), detail: localize(s.detail, locale) })),
|
|
168
|
+
labelBoxes: (/** @type {number} */ t) => labels(t).map((l) => l.box),
|
|
169
|
+
frame,
|
|
170
|
+
};
|
|
171
|
+
}
|
package/lib/check.mjs
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Over files, formats and locales (the CLI and the vendored gate): lib/gate.mjs.
|
|
10
10
|
*/
|
|
11
|
+
import { labelProblems } from "../runtime/iso.mjs";
|
|
11
12
|
import { renderSvg, validateScene } from "../runtime/scene.mjs";
|
|
12
13
|
import { checkContrast, normalizeStyle } from "../runtime/style.mjs";
|
|
13
14
|
|
|
@@ -289,5 +290,37 @@ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
|
|
|
289
290
|
for (const p of checkContrast(style, scene.contrastPairs)) problems.push(`contrast: ${p}`);
|
|
290
291
|
}
|
|
291
292
|
|
|
293
|
+
// 9. Labels the scene declares (scene.labelBoxes): at the sampled times, each
|
|
294
|
+
// step and the end, no two overlap, no stem crosses another label and none
|
|
295
|
+
// leaves the picture. Each problem is reported once, at its first time.
|
|
296
|
+
if (scene.labelBoxes) {
|
|
297
|
+
const seen = new Set();
|
|
298
|
+
const times = [...Array.from({ length: samples + 1 }, (_, i) => at(i)), ...scene.steps.map((s) => s.at)].sort((a, b) => a - b);
|
|
299
|
+
for (const t of times) {
|
|
300
|
+
let boxes;
|
|
301
|
+
try {
|
|
302
|
+
boxes = scene.labelBoxes(Math.min(t, scene.duration));
|
|
303
|
+
} catch (e) {
|
|
304
|
+
problems.push(`labelBoxes() threw at t=${t.toFixed(3)}: ${e instanceof Error ? e.message : String(e)}`);
|
|
305
|
+
break;
|
|
306
|
+
}
|
|
307
|
+
if (!Array.isArray(boxes)) {
|
|
308
|
+
problems.push("labelBoxes() must return an array of label boxes");
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
const bad = boxes.findIndex((b) => !b || typeof b !== "object" || typeof b.id !== "string" || !["x", "y", "width", "height"].every((k) => Number.isFinite(b[k])) || (b.opacity !== undefined && !Number.isFinite(b.opacity)) || (b.stem !== undefined && (!b.stem || typeof b.stem !== "object" || !["x1", "y1", "x2", "y2"].every((k) => Number.isFinite(b.stem[k])))));
|
|
312
|
+
if (bad >= 0) {
|
|
313
|
+
problems.push(`labelBoxes() entry ${bad} must be { id, x, y, width, height } with finite numbers (and a stem, when given, { x1, y1, x2, y2 }), at t=${t.toFixed(3)}`);
|
|
314
|
+
break;
|
|
315
|
+
}
|
|
316
|
+
for (const p of labelProblems(boxes, { width: scene.width, height: scene.height })) {
|
|
317
|
+
if (seen.has(p)) continue;
|
|
318
|
+
seen.add(p);
|
|
319
|
+
problems.push(`${p} at t=${t.toFixed(3)}`);
|
|
320
|
+
}
|
|
321
|
+
if (problems.length > 12) break;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
292
325
|
return { ok: problems.length === 0, problems };
|
|
293
326
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@liqweed/motion-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Deterministic animated diagrams: scenes as pure functions of time, for live pages, slides, baked SVG and video.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"animation",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"prepare": "lefthook install || true",
|
|
48
48
|
"test": "node --test test/*.test.mjs",
|
|
49
49
|
"typecheck": "tsc -p .",
|
|
50
|
-
"check": "node cli/motion-kit.mjs check examples/order-flow.json examples/smart-home.json examples/release-pipeline.json examples/agent-loop.json examples/integrations.json examples/incident.json examples/web-stack.json examples/custom-pulse.scene.mjs brand/logo.scene.mjs examples/player-states.json examples/checkout.json examples/connection.json examples/pull-request.json",
|
|
50
|
+
"check": "node cli/motion-kit.mjs check examples/order-flow.json examples/smart-home.json examples/release-pipeline.json examples/agent-loop.json examples/integrations.json examples/incident.json examples/web-stack.json examples/custom-pulse.scene.mjs examples/isometric-swivel.scene.mjs brand/logo.scene.mjs examples/player-states.json examples/checkout.json examples/connection.json examples/pull-request.json",
|
|
51
51
|
"media": "scripts/render-media.sh",
|
|
52
52
|
"media:check": "scripts/render-media.sh --check",
|
|
53
53
|
"site": "npm run -w website build",
|
package/runtime/iso.mjs
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 Ophir Radnitz
|
|
3
|
+
/**
|
|
4
|
+
* motion-kit · the isometric kit, for custom scenes (`kit`).
|
|
5
|
+
*
|
|
6
|
+
* A camera, solids, depth order and label anchors, as pure functions: the same
|
|
7
|
+
* camera and solids give the same markup, so a scene that draws a 3D view
|
|
8
|
+
* stays a function of time. Handed to custom scenes as part of `opts.kit`.
|
|
9
|
+
*
|
|
10
|
+
* World: x east, y north, z up, in any unit. The camera looks at it from
|
|
11
|
+
* `azimuth` (degrees turned about z; 0 = from the south) and `elevation`
|
|
12
|
+
* (degrees above the horizon). 90° elevation with azimuth 0 is the plan view, with north up;
|
|
13
|
+
* `ISO_ELEVATION` with a 45° azimuth is true isometric. The projection is
|
|
14
|
+
* orthographic, so it is linear and a swivel from one camera to another is an
|
|
15
|
+
* interpolation of the camera (`lerpCamera`).
|
|
16
|
+
*
|
|
17
|
+
* screen.x = pan.x + zoom · u
|
|
18
|
+
* screen.y = pan.y − zoom · (v·sin(elevation) + z·cos(elevation))
|
|
19
|
+
* with u = x·cos(az) + y·sin(az) and v = −x·sin(az) + y·cos(az)
|
|
20
|
+
*
|
|
21
|
+
* `pan` is where the world origin lands on the screen, in pixels, and `zoom`
|
|
22
|
+
* is pixels per world unit. Colours are token names (`"surface"`), never
|
|
23
|
+
* literals: faces take `tok(name)`, the sides shaded by a translucent layer of
|
|
24
|
+
* a second token. Labels are boxes the gate checks (`labelProblems`).
|
|
25
|
+
*
|
|
26
|
+
* Imports stay single-line named imports: lib/bundle.mjs inlines only that form.
|
|
27
|
+
*/
|
|
28
|
+
import { estimateWidth } from "./wrap.mjs";
|
|
29
|
+
import { tok } from "./style.mjs";
|
|
30
|
+
import { el, fade, num, text } from "./svg.mjs";
|
|
31
|
+
|
|
32
|
+
/** The elevation, in degrees, of true isometric: atan(1/√2), about 35.264°. */
|
|
33
|
+
export const ISO_ELEVATION = (Math.atan(Math.SQRT1_2) * 180) / Math.PI;
|
|
34
|
+
|
|
35
|
+
/** @typedef {{ x: number, y: number, z?: number }} Point3 */
|
|
36
|
+
/**
|
|
37
|
+
* A camera: where it looks from, and the pan and zoom of the picture.
|
|
38
|
+
* @typedef {Readonly<{ azimuth: number, elevation: number, zoom: number, pan: { x: number, y: number } }>} Camera
|
|
39
|
+
*/
|
|
40
|
+
/**
|
|
41
|
+
* A projected point: its screen position, and `depth`, how near it is to the
|
|
42
|
+
* viewer (larger is nearer).
|
|
43
|
+
* @typedef {{ x: number, y: number, depth: number }} Projected
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Sine and cosine of an angle in degrees, exact at multiples of 90°, so the
|
|
48
|
+
* plan view (90° elevation) projects without trigonometric noise.
|
|
49
|
+
* @param {number} deg
|
|
50
|
+
* @returns {[number, number]} [sin, cos]
|
|
51
|
+
*/
|
|
52
|
+
function sincos(deg) {
|
|
53
|
+
const r = ((deg % 360) + 360) % 360;
|
|
54
|
+
if (r % 90 === 0) return /** @type {[number, number]} */ ([[0, 1], [1, 0], [0, -1], [-1, 0]][r / 90]);
|
|
55
|
+
const rad = (deg * Math.PI) / 180;
|
|
56
|
+
return [Math.sin(rad), Math.cos(rad)];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** @param {number} n */
|
|
60
|
+
const finite = (n) => typeof n === "number" && Number.isFinite(n);
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A camera. Defaults: true isometric (45° azimuth, `ISO_ELEVATION`), zoom 1,
|
|
64
|
+
* the world origin at the screen origin.
|
|
65
|
+
* @param {{ azimuth?: number, elevation?: number, zoom?: number, pan?: { x: number, y: number } }} [opts]
|
|
66
|
+
* @returns {Camera}
|
|
67
|
+
*/
|
|
68
|
+
export function camera({ azimuth = 45, elevation = ISO_ELEVATION, zoom = 1, pan = { x: 0, y: 0 } } = {}) {
|
|
69
|
+
if (!finite(azimuth)) throw new Error(`camera: azimuth must be a finite number of degrees, got ${azimuth}`);
|
|
70
|
+
if (!finite(elevation) || elevation < 0 || elevation > 90) throw new Error(`camera: elevation must be from 0 to 90 degrees, got ${elevation}`);
|
|
71
|
+
if (!finite(zoom) || zoom <= 0) throw new Error(`camera: zoom must be a positive number, got ${zoom}`);
|
|
72
|
+
if (!pan || !finite(pan.x) || !finite(pan.y)) throw new Error("camera: pan must be { x, y } in finite pixels");
|
|
73
|
+
return Object.freeze({ azimuth, elevation, zoom, pan: Object.freeze({ x: pan.x, y: pan.y }) });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The plan view: straight down, north up. */
|
|
77
|
+
export const CAMERA_PLAN = camera({ azimuth: 0, elevation: 90 });
|
|
78
|
+
/** True isometric. */
|
|
79
|
+
export const CAMERA_ISOMETRIC = camera({ azimuth: 45, elevation: ISO_ELEVATION });
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The camera `p` of the way from `a` to `b`: every field interpolated
|
|
83
|
+
* linearly, so a swivel is `lerpCamera(plan, iso, progress(t, …))`. At 0 and
|
|
84
|
+
* 1 it is `a` and `b` themselves.
|
|
85
|
+
* @param {Camera} a
|
|
86
|
+
* @param {Camera} b
|
|
87
|
+
* @param {number} p 0..1
|
|
88
|
+
* @returns {Camera}
|
|
89
|
+
*/
|
|
90
|
+
export function lerpCamera(a, b, p) {
|
|
91
|
+
if (p <= 0) return a;
|
|
92
|
+
if (p >= 1) return b;
|
|
93
|
+
const mix = (/** @type {number} */ x, /** @type {number} */ y) => x + (y - x) * p;
|
|
94
|
+
return camera({
|
|
95
|
+
azimuth: mix(a.azimuth, b.azimuth),
|
|
96
|
+
elevation: mix(a.elevation, b.elevation),
|
|
97
|
+
zoom: mix(a.zoom, b.zoom),
|
|
98
|
+
pan: { x: mix(a.pan.x, b.pan.x), y: mix(a.pan.y, b.pan.y) },
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The projection of a camera as a function of a world point.
|
|
104
|
+
* @param {Camera} cam
|
|
105
|
+
* @returns {(p: Point3) => Projected}
|
|
106
|
+
*/
|
|
107
|
+
export function projector(cam) {
|
|
108
|
+
const [sa, ca] = sincos(cam.azimuth);
|
|
109
|
+
const [se, ce] = sincos(cam.elevation);
|
|
110
|
+
const { zoom, pan } = cam;
|
|
111
|
+
return ({ x, y, z = 0 }) => {
|
|
112
|
+
const u = x * ca + y * sa;
|
|
113
|
+
const v = -x * sa + y * ca;
|
|
114
|
+
return { x: pan.x + zoom * u, y: pan.y - zoom * (v * se + z * ce), depth: -v * ce + z * se };
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* One world point on the screen.
|
|
120
|
+
* @param {Camera} cam
|
|
121
|
+
* @param {Point3} p
|
|
122
|
+
* @returns {Projected}
|
|
123
|
+
*/
|
|
124
|
+
export function project(cam, p) {
|
|
125
|
+
return projector(cam)(p);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* `cam` with the zoom and pan that fit `points` (world points: a scene's
|
|
130
|
+
* floor corners and tallest heights) into a `width` × `height` picture, centred
|
|
131
|
+
* in the area the margins leave. Fitting each frame's camera keeps the whole
|
|
132
|
+
* scene in view through a swivel; `cam`'s own zoom and pan are replaced.
|
|
133
|
+
* @param {Point3[]} points
|
|
134
|
+
* @param {Camera} cam
|
|
135
|
+
* @param {{ width: number, height: number, margin?: number | { top?: number, right?: number, bottom?: number, left?: number } }} area
|
|
136
|
+
* @returns {Camera}
|
|
137
|
+
*/
|
|
138
|
+
export function fitCamera(points, cam, { width, height, margin = 0 }) {
|
|
139
|
+
if (!points.length) throw new Error("fitCamera: needs at least one point");
|
|
140
|
+
const m = typeof margin === "number" ? { top: margin, right: margin, bottom: margin, left: margin } : margin;
|
|
141
|
+
const top = m.top ?? 0;
|
|
142
|
+
const right = m.right ?? 0;
|
|
143
|
+
const bottom = m.bottom ?? 0;
|
|
144
|
+
const left = m.left ?? 0;
|
|
145
|
+
const free = { w: width - left - right, h: height - top - bottom };
|
|
146
|
+
if (!(free.w > 0 && free.h > 0)) throw new Error("fitCamera: the margins leave no room");
|
|
147
|
+
const unit = projector(camera({ azimuth: cam.azimuth, elevation: cam.elevation }));
|
|
148
|
+
let minX = Infinity;
|
|
149
|
+
let maxX = -Infinity;
|
|
150
|
+
let minY = Infinity;
|
|
151
|
+
let maxY = -Infinity;
|
|
152
|
+
for (const p of points) {
|
|
153
|
+
const s = unit(p);
|
|
154
|
+
minX = Math.min(minX, s.x);
|
|
155
|
+
maxX = Math.max(maxX, s.x);
|
|
156
|
+
minY = Math.min(minY, s.y);
|
|
157
|
+
maxY = Math.max(maxY, s.y);
|
|
158
|
+
}
|
|
159
|
+
const w = maxX - minX;
|
|
160
|
+
const h = maxY - minY;
|
|
161
|
+
const zoom = Math.min(w > 0 ? free.w / w : Infinity, h > 0 ? free.h / h : Infinity);
|
|
162
|
+
if (!Number.isFinite(zoom)) throw new Error("fitCamera: the points have no extent");
|
|
163
|
+
return camera({
|
|
164
|
+
azimuth: cam.azimuth,
|
|
165
|
+
elevation: cam.elevation,
|
|
166
|
+
zoom,
|
|
167
|
+
pan: { x: left + free.w / 2 - ((minX + maxX) / 2) * zoom, y: top + free.h / 2 - ((minY + maxY) / 2) * zoom },
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* A polyline through world points with its length, so a token travels it at a
|
|
173
|
+
* constant speed in world units, whatever the camera does, when its progress is
|
|
174
|
+
* linear (`ease: linear`).
|
|
175
|
+
* @param {Point3[]} points
|
|
176
|
+
* @returns {{ length: number, points: Point3[], at: (f: number) => { x: number, y: number, z: number } }}
|
|
177
|
+
*/
|
|
178
|
+
export function path3(points) {
|
|
179
|
+
if (points.length < 2) throw new Error("path3: needs at least two points");
|
|
180
|
+
const pts = points.map((p) => ({ x: p.x, y: p.y, z: p.z ?? 0 }));
|
|
181
|
+
const starts = [0];
|
|
182
|
+
for (let i = 1; i < pts.length; i++) starts.push(starts[i - 1] + Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y, pts[i].z - pts[i - 1].z));
|
|
183
|
+
const length = starts[starts.length - 1];
|
|
184
|
+
return {
|
|
185
|
+
length,
|
|
186
|
+
points: pts,
|
|
187
|
+
at(f) {
|
|
188
|
+
const target = Math.min(Math.max(f, 0), 1) * length;
|
|
189
|
+
let i = 1;
|
|
190
|
+
while (i < pts.length - 1 && target > starts[i]) i++;
|
|
191
|
+
const a = pts[i - 1];
|
|
192
|
+
const b = pts[i];
|
|
193
|
+
const span = starts[i] - starts[i - 1];
|
|
194
|
+
const k = span === 0 ? 0 : (target - starts[i - 1]) / span;
|
|
195
|
+
return { x: a.x + (b.x - a.x) * k, y: a.y + (b.y - a.y) * k, z: a.z + (b.z - a.z) * k };
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/* ------------------------------------------------------------------ solids */
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* An extruded convex polygon: a footprint in the x-y plane, from `z0` up to
|
|
204
|
+
* `z1`. `fill` is the token of the top face; `sides` (default: `fill`) the
|
|
205
|
+
* token of the side faces, which a layer of `shade` at 10–26 % darkens or
|
|
206
|
+
* lightens by the face's turn from the light (screen left is lit). `shade:
|
|
207
|
+
* null` leaves them flat. `stroke` outlines every face.
|
|
208
|
+
* @typedef {Readonly<{ points: { x: number, y: number }[], z0: number, z1: number, fill: string, sides: string, shade: string | null, stroke: string, strokeWidth: number, opacity: number, id?: string }>} Solid
|
|
209
|
+
*/
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* @param {string} name a token name
|
|
213
|
+
* @returns {string}
|
|
214
|
+
*/
|
|
215
|
+
function token(name) {
|
|
216
|
+
tok(name); // throws for an unknown token
|
|
217
|
+
return name;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Footprint points counter-clockwise, or a throw for a footprint that is not a
|
|
222
|
+
* convex polygon.
|
|
223
|
+
* @param {{ x: number, y: number }[]} points
|
|
224
|
+
* @returns {{ x: number, y: number }[]}
|
|
225
|
+
*/
|
|
226
|
+
function convexCcw(points) {
|
|
227
|
+
if (!Array.isArray(points) || points.length < 3) throw new Error("a solid's footprint needs at least three points");
|
|
228
|
+
for (const p of points) if (!p || !finite(p.x) || !finite(p.y)) throw new Error("a solid's footprint points must be finite { x, y }");
|
|
229
|
+
let area = 0;
|
|
230
|
+
for (let i = 0; i < points.length; i++) {
|
|
231
|
+
const a = points[i];
|
|
232
|
+
const b = points[(i + 1) % points.length];
|
|
233
|
+
area += a.x * b.y - b.x * a.y;
|
|
234
|
+
}
|
|
235
|
+
if (Math.abs(area) < 1e-9) throw new Error("a solid's footprint has no area");
|
|
236
|
+
for (let i = 0; i < points.length; i++) {
|
|
237
|
+
const a = points[i];
|
|
238
|
+
const b = points[(i + 1) % points.length];
|
|
239
|
+
if (Math.hypot(b.x - a.x, b.y - a.y) < 1e-9) throw new Error("a solid's footprint has a repeated point");
|
|
240
|
+
}
|
|
241
|
+
const ccw = area > 0 ? points.map((p) => ({ x: p.x, y: p.y })) : points.map((p) => ({ x: p.x, y: p.y })).reverse();
|
|
242
|
+
for (let i = 0; i < ccw.length; i++) {
|
|
243
|
+
const a = ccw[i];
|
|
244
|
+
const b = ccw[(i + 1) % ccw.length];
|
|
245
|
+
const c = ccw[(i + 2) % ccw.length];
|
|
246
|
+
if ((b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x) < -1e-9) throw new Error("a solid's footprint must be convex");
|
|
247
|
+
}
|
|
248
|
+
// Consecutive turns alone pass a star that winds twice: every vertex must also
|
|
249
|
+
// lie on the inner side of every edge.
|
|
250
|
+
for (let i = 0; i < ccw.length; i++) {
|
|
251
|
+
const a = ccw[i];
|
|
252
|
+
const b = ccw[(i + 1) % ccw.length];
|
|
253
|
+
for (const p of ccw) if ((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) < -1e-9) throw new Error("a solid's footprint must be convex");
|
|
254
|
+
}
|
|
255
|
+
return ccw;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* A prism: `points` extruded by `h` from the base height `z`.
|
|
260
|
+
* @param {{ points: { x: number, y: number }[], h: number, z?: number, fill?: string, sides?: string, shade?: string | null, stroke?: string, strokeWidth?: number, opacity?: number, id?: string }} o
|
|
261
|
+
* @returns {Solid}
|
|
262
|
+
*/
|
|
263
|
+
export function prism({ points, h, z = 0, fill = "surface", sides, shade = "ink", stroke = "line", strokeWidth = 1.5, opacity = 1, id }) {
|
|
264
|
+
if (!finite(h) || h < 0) throw new Error(`a solid's height must be a number from 0 up, got ${h}`);
|
|
265
|
+
if (!finite(z)) throw new Error(`a solid's base height must be finite, got ${z}`);
|
|
266
|
+
return Object.freeze({
|
|
267
|
+
points: convexCcw(points),
|
|
268
|
+
z0: z,
|
|
269
|
+
z1: z + h,
|
|
270
|
+
fill: token(fill),
|
|
271
|
+
sides: token(sides ?? fill),
|
|
272
|
+
shade: shade === null ? null : token(shade),
|
|
273
|
+
stroke: token(stroke),
|
|
274
|
+
strokeWidth,
|
|
275
|
+
opacity,
|
|
276
|
+
id,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** @typedef {Omit<Parameters<typeof prism>[0], "points" | "h">} SolidStyle */
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* A box: `w` along x, `d` along y, `h` up, its footprint centred on (x, y).
|
|
284
|
+
* @param {{ x: number, y: number, w: number, d: number, h: number } & SolidStyle} o
|
|
285
|
+
* @returns {Solid}
|
|
286
|
+
*/
|
|
287
|
+
export function box({ x, y, w, d, h, ...style }) {
|
|
288
|
+
if (!(finite(w) && w > 0 && finite(d) && d > 0)) throw new Error("a box needs a positive width and depth");
|
|
289
|
+
const hw = w / 2;
|
|
290
|
+
const hd = d / 2;
|
|
291
|
+
return prism({ points: [{ x: x - hw, y: y - hd }, { x: x + hw, y: y - hd }, { x: x + hw, y: y + hd }, { x: x - hw, y: y + hd }], h, ...style });
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* A slab: a box that is thin (`h` default 0.25), for a floor or a platform.
|
|
296
|
+
* @param {{ x: number, y: number, w: number, d: number, h?: number } & SolidStyle} o
|
|
297
|
+
* @returns {Solid}
|
|
298
|
+
*/
|
|
299
|
+
export function slab({ h = 0.25, ...rest }) {
|
|
300
|
+
return box({ h, ...rest });
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* The corners of a regular polygon of `n` sides and circumradius `r` centred on
|
|
305
|
+
* (x, y), the first at `rotation` degrees from east: a footprint for `prism`.
|
|
306
|
+
* @param {number} x
|
|
307
|
+
* @param {number} y
|
|
308
|
+
* @param {number} r
|
|
309
|
+
* @param {number} n
|
|
310
|
+
* @param {number} [rotation]
|
|
311
|
+
* @returns {{ x: number, y: number }[]}
|
|
312
|
+
*/
|
|
313
|
+
export function regularPolygon(x, y, r, n, rotation = 0) {
|
|
314
|
+
if (!Number.isInteger(n) || n < 3) throw new Error(`a regular polygon needs at least 3 sides, got ${n}`);
|
|
315
|
+
return Array.from({ length: n }, (_, i) => {
|
|
316
|
+
const [s, c] = sincos(rotation + (360 * i) / n);
|
|
317
|
+
return { x: x + r * c, y: y + r * s };
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const EPS = 1e-9;
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* The faces of `solid` that face the camera, as screen polygons. Sides first,
|
|
325
|
+
* then the top: they never overlap, since the solid is convex.
|
|
326
|
+
* @param {Solid} solid
|
|
327
|
+
* @param {Camera} cam
|
|
328
|
+
* @returns {{ kind: "side" | "top", points: { x: number, y: number }[], shade: number }[]}
|
|
329
|
+
*/
|
|
330
|
+
function visibleFaces(solid, cam) {
|
|
331
|
+
const to = projector(cam);
|
|
332
|
+
const [sa, ca] = sincos(cam.azimuth);
|
|
333
|
+
const [se, ce] = sincos(cam.elevation);
|
|
334
|
+
const faces = /** @type {{ kind: "side" | "top", points: { x: number, y: number }[], shade: number }[]} */ ([]);
|
|
335
|
+
const pts = solid.points;
|
|
336
|
+
if (solid.z1 - solid.z0 > EPS) {
|
|
337
|
+
for (let i = 0; i < pts.length; i++) {
|
|
338
|
+
const a = pts[i];
|
|
339
|
+
const b = pts[(i + 1) % pts.length];
|
|
340
|
+
const len = Math.hypot(b.x - a.x, b.y - a.y);
|
|
341
|
+
const nx = (b.y - a.y) / len;
|
|
342
|
+
const ny = -(b.x - a.x) / len;
|
|
343
|
+
// Toward the camera, horizontally, is (sin az, −cos az).
|
|
344
|
+
if ((nx * sa - ny * ca) * ce <= EPS) continue;
|
|
345
|
+
const turn = nx * ca + ny * sa; // −1 faces screen left (lit), 1 faces screen right
|
|
346
|
+
faces.push({
|
|
347
|
+
kind: "side",
|
|
348
|
+
points: [to({ ...a, z: solid.z0 }), to({ ...b, z: solid.z0 }), to({ ...b, z: solid.z1 }), to({ ...a, z: solid.z1 })],
|
|
349
|
+
shade: Math.round((0.1 + 0.16 * ((turn + 1) / 2)) * 100) / 100,
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (se > EPS) faces.push({ kind: "top", points: pts.map((p) => to({ ...p, z: solid.z1 })), shade: 0 });
|
|
354
|
+
return faces;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** @param {{ x: number, y: number }[]} points */
|
|
358
|
+
const pathD = (points) => `${points.map((p, i) => `${i === 0 ? "M" : "L"}${num(p.x)} ${num(p.y)}`).join(" ")} Z`;
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Markup of one solid under a camera: only the faces that face the camera,
|
|
362
|
+
* each a path in its token, the sides with a shade layer. Nothing is drawn for
|
|
363
|
+
* a solid with zero opacity.
|
|
364
|
+
* @param {Solid} solid
|
|
365
|
+
* @param {Camera} cam
|
|
366
|
+
* @returns {string}
|
|
367
|
+
*/
|
|
368
|
+
export function drawSolid(solid, cam) {
|
|
369
|
+
const paths = visibleFaces(solid, cam).map((face) => {
|
|
370
|
+
const d = pathD(face.points);
|
|
371
|
+
const base = el("path", { d, fill: tok(face.kind === "top" ? solid.fill : solid.sides), stroke: tok(solid.stroke), "stroke-width": solid.strokeWidth, "stroke-linejoin": "round" });
|
|
372
|
+
return face.kind === "side" && solid.shade ? base + el("path", { d, fill: tok(solid.shade), opacity: face.shade }) : base;
|
|
373
|
+
});
|
|
374
|
+
return fade(solid.opacity, solid.id ? { "data-solid": solid.id } : {}, ...paths);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Whether the solids can be told apart in depth on the screen: the bounding
|
|
379
|
+
* boxes of their projections overlap.
|
|
380
|
+
* @param {{ min: { x: number, y: number }, max: { x: number, y: number } }} a
|
|
381
|
+
* @param {{ min: { x: number, y: number }, max: { x: number, y: number } }} b
|
|
382
|
+
*/
|
|
383
|
+
const screenOverlap = (a, b) => a.min.x < b.max.x - EPS && b.min.x < a.max.x - EPS && a.min.y < b.max.y - EPS && b.min.y < a.max.y - EPS;
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Which of two solids is drawn first, by the axes that separate them: -1 when
|
|
387
|
+
* `a` lies behind `b`, 1 when it lies in front, 0 when no axis, or two that
|
|
388
|
+
* disagree, decide (the solids then cannot hide one another).
|
|
389
|
+
* @param {Solid} a
|
|
390
|
+
* @param {Solid} b
|
|
391
|
+
* @param {number} sa sin of the azimuth
|
|
392
|
+
* @param {number} ca cos of the azimuth
|
|
393
|
+
* @param {number} se sin of the elevation
|
|
394
|
+
* @returns {-1 | 0 | 1}
|
|
395
|
+
*/
|
|
396
|
+
function behind(a, b, sa, ca, se) {
|
|
397
|
+
let vote = 0;
|
|
398
|
+
let conflict = false;
|
|
399
|
+
/** @param {-1 | 1} v */
|
|
400
|
+
const cast = (v) => {
|
|
401
|
+
if (vote !== 0 && vote !== v) conflict = true;
|
|
402
|
+
vote = v;
|
|
403
|
+
};
|
|
404
|
+
// Footprints: a separating line between two convex polygons lies along an edge of one.
|
|
405
|
+
for (const poly of [a.points, b.points]) {
|
|
406
|
+
for (let i = 0; i < poly.length; i++) {
|
|
407
|
+
const p = poly[i];
|
|
408
|
+
const q = poly[(i + 1) % poly.length];
|
|
409
|
+
const len = Math.hypot(q.x - p.x, q.y - p.y);
|
|
410
|
+
const nx = (q.y - p.y) / len;
|
|
411
|
+
const ny = -(q.x - p.x) / len;
|
|
412
|
+
const range = (/** @type {Solid} */ s) => {
|
|
413
|
+
const d = s.points.map((pt) => pt.x * nx + pt.y * ny);
|
|
414
|
+
return [Math.min(...d), Math.max(...d)];
|
|
415
|
+
};
|
|
416
|
+
const [a0, a1] = range(a);
|
|
417
|
+
const [b0, b1] = range(b);
|
|
418
|
+
const facing = nx * sa - ny * ca; // how much this axis points toward the camera
|
|
419
|
+
if (Math.abs(facing) <= EPS) continue;
|
|
420
|
+
if (a1 <= b0 + EPS) cast(facing > 0 ? -1 : 1); // b is on the positive side
|
|
421
|
+
else if (b1 <= a0 + EPS) cast(facing > 0 ? 1 : -1);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
// Heights: from above, the higher solid is nearer.
|
|
425
|
+
if (se > EPS) {
|
|
426
|
+
if (a.z1 <= b.z0 + EPS) cast(-1);
|
|
427
|
+
else if (b.z1 <= a.z0 + EPS) cast(1);
|
|
428
|
+
}
|
|
429
|
+
return conflict ? 0 : vote === 0 ? 0 : /** @type {-1 | 1} */ (vote);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* The solids in drawing order, farthest first, for `cam`. Two solids are
|
|
434
|
+
* ordered by the axes that separate them (footprint edges and height), only
|
|
435
|
+
* when they overlap on the screen; the rest is a topological sort, ties and
|
|
436
|
+
* cycles broken by how near each solid's centre is, then by input order. The
|
|
437
|
+
* same input always gives the same order.
|
|
438
|
+
* @template {Solid} S
|
|
439
|
+
* @param {S[]} solids
|
|
440
|
+
* @param {Camera} cam
|
|
441
|
+
* @returns {S[]}
|
|
442
|
+
*/
|
|
443
|
+
export function orderSolids(solids, cam) {
|
|
444
|
+
const to = projector(cam);
|
|
445
|
+
const [sa, ca] = sincos(cam.azimuth);
|
|
446
|
+
const [se] = sincos(cam.elevation);
|
|
447
|
+
const info = solids.map((s) => {
|
|
448
|
+
const corners = s.points.flatMap((p) => [to({ ...p, z: s.z0 }), to({ ...p, z: s.z1 })]);
|
|
449
|
+
const xs = corners.map((c) => c.x);
|
|
450
|
+
const ys = corners.map((c) => c.y);
|
|
451
|
+
const cx = s.points.reduce((n, p) => n + p.x, 0) / s.points.length;
|
|
452
|
+
const cy = s.points.reduce((n, p) => n + p.y, 0) / s.points.length;
|
|
453
|
+
return { min: { x: Math.min(...xs), y: Math.min(...ys) }, max: { x: Math.max(...xs), y: Math.max(...ys) }, near: to({ x: cx, y: cy, z: (s.z0 + s.z1) / 2 }).depth };
|
|
454
|
+
});
|
|
455
|
+
const after = solids.map(() => /** @type {number[]} */ ([])); // after[i]: drawn after i
|
|
456
|
+
const waiting = solids.map(() => 0);
|
|
457
|
+
for (let i = 0; i < solids.length; i++) {
|
|
458
|
+
for (let j = i + 1; j < solids.length; j++) {
|
|
459
|
+
if (!screenOverlap(info[i], info[j])) continue;
|
|
460
|
+
const order = behind(solids[i], solids[j], sa, ca, se);
|
|
461
|
+
if (order === 0) continue;
|
|
462
|
+
const [first, second] = order < 0 ? [i, j] : [j, i];
|
|
463
|
+
after[first].push(second);
|
|
464
|
+
waiting[second]++;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const done = solids.map(() => false);
|
|
468
|
+
const out = /** @type {S[]} */ ([]);
|
|
469
|
+
/** @param {number} i @param {number} j */
|
|
470
|
+
const nearer = (i, j) => info[i].near < info[j].near - EPS || (Math.abs(info[i].near - info[j].near) <= EPS && i < j);
|
|
471
|
+
while (out.length < solids.length) {
|
|
472
|
+
let pick = -1;
|
|
473
|
+
for (let i = 0; i < solids.length; i++) if (!done[i] && waiting[i] === 0 && (pick < 0 || nearer(i, pick))) pick = i;
|
|
474
|
+
if (pick < 0) for (let i = 0; i < solids.length; i++) if (!done[i] && (pick < 0 || nearer(i, pick))) pick = i; // a cycle
|
|
475
|
+
done[pick] = true;
|
|
476
|
+
out.push(solids[pick]);
|
|
477
|
+
for (const next of after[pick]) waiting[next]--;
|
|
478
|
+
}
|
|
479
|
+
return out;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Markup of several solids, depth ordered for `cam`.
|
|
484
|
+
* @param {Solid[]} solids
|
|
485
|
+
* @param {Camera} cam
|
|
486
|
+
* @returns {string}
|
|
487
|
+
*/
|
|
488
|
+
export function drawSolids(solids, cam) {
|
|
489
|
+
return orderSolids(solids, cam)
|
|
490
|
+
.map((s) => drawSolid(s, cam))
|
|
491
|
+
.join("");
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/* ----------------------------------------------------------- label anchors */
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* What the gate checks of a label: its box in the picture (top left, size), its
|
|
498
|
+
* stem, and whether it is drawn (`opacity` above 0).
|
|
499
|
+
* @typedef {{ id: string, x: number, y: number, width: number, height: number, stem?: { x1: number, y1: number, x2: number, y2: number }, opacity?: number }} LabelBox
|
|
500
|
+
*/
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* A label on a point of the world, with a stem: a dot on the point, a vertical
|
|
504
|
+
* stem `lift` pixels up, and the label's box at its top, placed in the
|
|
505
|
+
* projected view, so it follows the camera. `side` puts the box above the
|
|
506
|
+
* stem (`"up"`, centred), or beside its top (`"right"` or `"left"`).
|
|
507
|
+
* `lines` are the label's (already wrapped, localized) lines. Returns the
|
|
508
|
+
* markup and the box for the scene's `labelBoxes`.
|
|
509
|
+
* @param {Camera} cam
|
|
510
|
+
* @param {{ id: string, at: Point3, lines: string[], fontSize?: number, lift?: number, side?: "up" | "right" | "left", opacity?: number }} o
|
|
511
|
+
* @returns {{ markup: string, box: LabelBox }}
|
|
512
|
+
*/
|
|
513
|
+
export function labelAnchor(cam, { id, at, lines, fontSize = 14, lift = 40, side = "up", opacity = 1 }) {
|
|
514
|
+
if (!lines.length) throw new Error(`label "${id}" has no text`);
|
|
515
|
+
const p = project(cam, at);
|
|
516
|
+
const padX = 8;
|
|
517
|
+
const padY = 5;
|
|
518
|
+
const lineHeight = 1.25;
|
|
519
|
+
const width = Math.max(...lines.map((l) => estimateWidth(l, fontSize * 1.08))) + 2 * padX;
|
|
520
|
+
const height = lines.length * lineHeight * fontSize + 2 * padY;
|
|
521
|
+
const tipX = p.x;
|
|
522
|
+
const tipY = p.y - lift;
|
|
523
|
+
const x = side === "up" ? tipX - width / 2 : side === "right" ? tipX : tipX - width;
|
|
524
|
+
const y = side === "up" ? tipY - height : tipY - height / 2;
|
|
525
|
+
const stem = { x1: p.x, y1: p.y, x2: tipX, y2: tipY };
|
|
526
|
+
const markup = fade(
|
|
527
|
+
opacity,
|
|
528
|
+
{ "data-label": id },
|
|
529
|
+
el("line", { x1: stem.x1, y1: stem.y1, x2: stem.x2, y2: stem.y2, stroke: tok("line"), "stroke-width": 1.5 }),
|
|
530
|
+
el("circle", { cx: p.x, cy: p.y, r: 3.5, fill: tok("ink"), stroke: tok("bg"), "stroke-width": 1.5 }),
|
|
531
|
+
el("rect", { x, y, width, height, rx: 6, fill: tok("surface"), stroke: tok("line"), "stroke-width": 1.5 }),
|
|
532
|
+
text({ x: x + width / 2, y: y + height / 2, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fontSize, "font-weight": 600, fill: tok("ink") }, lines, lineHeight),
|
|
533
|
+
);
|
|
534
|
+
return { markup, box: { id, x, y, width, height, stem, opacity } };
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Whether the segment crosses the rectangle (Liang–Barsky).
|
|
539
|
+
* @param {{ x1: number, y1: number, x2: number, y2: number }} s
|
|
540
|
+
* @param {{ x: number, y: number, width: number, height: number }} r
|
|
541
|
+
*/
|
|
542
|
+
function segmentHits(s, r) {
|
|
543
|
+
let t0 = 0;
|
|
544
|
+
let t1 = 1;
|
|
545
|
+
const dx = s.x2 - s.x1;
|
|
546
|
+
const dy = s.y2 - s.y1;
|
|
547
|
+
for (const [p, q] of [[-dx, s.x1 - r.x], [dx, r.x + r.width - s.x1], [-dy, s.y1 - r.y], [dy, r.y + r.height - s.y1]]) {
|
|
548
|
+
if (p === 0) {
|
|
549
|
+
if (q < 0) return false;
|
|
550
|
+
} else {
|
|
551
|
+
const k = q / p;
|
|
552
|
+
if (p < 0) t0 = Math.max(t0, k);
|
|
553
|
+
else t1 = Math.min(t1, k);
|
|
554
|
+
if (t0 > t1) return false;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return true;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* What is wrong with a set of drawn labels: two boxes closer than `gap`
|
|
562
|
+
* pixels (overlapping), a stem running through another label, a box outside
|
|
563
|
+
* the picture. Boxes with `opacity` 0 are not drawn and are skipped. Each
|
|
564
|
+
* problem is one sentence; none for a clean set.
|
|
565
|
+
* @param {LabelBox[]} boxes
|
|
566
|
+
* @param {{ width: number, height: number, gap?: number }} view the picture's size
|
|
567
|
+
* @returns {string[]}
|
|
568
|
+
*/
|
|
569
|
+
export function labelProblems(boxes, { width, height, gap = 4 }) {
|
|
570
|
+
// Drawn unless it fades out: `fade` drops an element whose opacity rounds to 0.
|
|
571
|
+
const drawn = boxes.filter((b) => b.opacity === undefined || Math.round(b.opacity * 1000) > 0);
|
|
572
|
+
const problems = [];
|
|
573
|
+
for (const [i, a] of drawn.entries()) {
|
|
574
|
+
if (a.x < 0 || a.y < 0 || a.x + a.width > width || a.y + a.height > height) problems.push(`label "${a.id}" is outside the picture`);
|
|
575
|
+
for (const b of drawn.slice(i + 1)) {
|
|
576
|
+
if (a.x < b.x + b.width + gap && b.x < a.x + a.width + gap && a.y < b.y + b.height + gap && b.y < a.y + a.height + gap) problems.push(`labels "${a.id}" and "${b.id}" overlap`);
|
|
577
|
+
}
|
|
578
|
+
for (const b of drawn) {
|
|
579
|
+
if (b !== a && b.stem && segmentHits(b.stem, a)) problems.push(`the stem of label "${b.id}" crosses label "${a.id}"`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
return problems;
|
|
583
|
+
}
|
package/runtime/kit.mjs
CHANGED
|
@@ -24,12 +24,13 @@
|
|
|
24
24
|
import { DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 } from "./motion.mjs";
|
|
25
25
|
import { FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId } from "./scene.mjs";
|
|
26
26
|
import { CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok } from "./style.mjs";
|
|
27
|
-
import {
|
|
27
|
+
import { CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawSolid, drawSolids, fitCamera, labelAnchor, labelProblems, lerpCamera, orderSolids, path3, prism, project, projector, regularPolygon, slab } from "./iso.mjs";
|
|
28
|
+
import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment } from "./svg.mjs";
|
|
28
29
|
import { estimateWidth, wrapLabel } from "./wrap.mjs";
|
|
29
30
|
|
|
30
31
|
/**
|
|
31
32
|
* The runtime, flat, handed to custom scene modules as `opts.kit`: the exports
|
|
32
|
-
* of motion, scene, style, svg and wrap (not the scene types or the player).
|
|
33
|
+
* of motion, scene, style, svg, iso and wrap (not the scene types or the player).
|
|
33
34
|
* Named imports, because lib/bundle.mjs inlines only that form; a new export
|
|
34
35
|
* in one of those modules is added here (test/runtime.test.mjs checks).
|
|
35
36
|
*/
|
|
@@ -37,7 +38,8 @@ export const KIT = Object.freeze({
|
|
|
37
38
|
...{ DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
|
|
38
39
|
...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
|
|
39
40
|
...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok },
|
|
40
|
-
...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment },
|
|
41
|
+
...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment },
|
|
42
|
+
...{ CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawSolid, drawSolids, fitCamera, labelAnchor, labelProblems, lerpCamera, orderSolids, path3, prism, project, projector, regularPolygon, slab },
|
|
41
43
|
...{ estimateWidth, wrapLabel },
|
|
42
44
|
});
|
|
43
45
|
|
package/runtime/scene.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** @import { Style } from "./style.mjs" */
|
|
2
|
+
/** @import { LabelBox } from "./iso.mjs" */
|
|
2
3
|
// SPDX-License-Identifier: MIT
|
|
3
4
|
// Copyright (c) 2026 Ophir Radnitz
|
|
4
5
|
/**
|
|
@@ -11,6 +12,7 @@
|
|
|
11
12
|
* duration, // seconds until the final state
|
|
12
13
|
* title, description, // accessible name + description
|
|
13
14
|
* stepLabelsInFrame?: boolean, // false for narrative steps (default true)
|
|
15
|
+
* labelBoxes?(t) → LabelBox[], // the boxes of the labels drawn at t, for the gate
|
|
14
16
|
* steps: [{ at, label, detail?, id? }], // build steps; last = finished diagram
|
|
15
17
|
* frame(t, { idPrefix }) → string // inner SVG markup at time t
|
|
16
18
|
* }
|
|
@@ -40,7 +42,10 @@ import { normalizeStyle, cssVars, resolveTokens } from "./style.mjs";
|
|
|
40
42
|
* An animated diagram as a pure function of time (see the module comment).
|
|
41
43
|
* `contrastPairs`: token pairs the scene draws beyond CONTRAST_PAIRS
|
|
42
44
|
* (runtime/style.mjs), which the gate checks the style against.
|
|
43
|
-
*
|
|
45
|
+
* `labelBoxes`: the box of every label `frame(t)` draws, in the picture's
|
|
46
|
+
* coordinates (`labelAnchor` returns one); the gate fails a scene whose labels
|
|
47
|
+
* overlap, whose stems cross a label, or that leave the picture (runtime/iso.mjs).
|
|
48
|
+
* @typedef {{ id: string, width: number, height: number, duration: number, title: string, description: string, steps: Step[], frame: (t: number, ctx: FrameContext) => string, stepLabelsInFrame?: boolean, contrastPairs?: { fg: string, bg: string, min: number, use?: string }[], labelBoxes?: (t: number) => LabelBox[], type?: string, format?: string, locale?: string }} Scene
|
|
44
49
|
*/
|
|
45
50
|
|
|
46
51
|
/** Formats: name → viewBox. Layouts are computed per format, never cropped. */
|
|
@@ -94,6 +99,7 @@ export function validateScene(scene) {
|
|
|
94
99
|
if (!Number.isFinite(scene[key]) || scene[key] <= 0) throw new Error(`scene ${scene.id}: ${key} must be a positive finite number`);
|
|
95
100
|
}
|
|
96
101
|
if (typeof scene.frame !== "function") throw new Error(`scene ${scene.id}: frame must be a function`);
|
|
102
|
+
if (scene.labelBoxes !== undefined && typeof scene.labelBoxes !== "function") throw new Error(`scene ${scene.id}: labelBoxes must be a function`);
|
|
97
103
|
if (!Array.isArray(scene.steps) || !scene.steps.length) throw new Error(`scene ${scene.id}: needs at least one step`);
|
|
98
104
|
let prev = -Infinity;
|
|
99
105
|
const ids = new Set();
|
package/runtime/svg.mjs
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* here; numbers are rounded here. Numbers you interpolate into a template
|
|
9
9
|
* string yourself (transform, points, path d) must go through `num()`.
|
|
10
10
|
*/
|
|
11
|
+
import { easeStandard, progress } from "./motion.mjs";
|
|
11
12
|
|
|
12
13
|
const ESCAPES = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
13
14
|
|
|
@@ -163,3 +164,49 @@ export function drawOn(length, p) {
|
|
|
163
164
|
if (p >= 1) return {};
|
|
164
165
|
return { "stroke-dasharray": `${num(length)} ${num(length)}`, "stroke-dashoffset": num(length * (1 - p)) };
|
|
165
166
|
}
|
|
167
|
+
|
|
168
|
+
/* ------------------------------------------------------------------ tokens */
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* One token's journey: it starts at `start` s and takes `duration` s along
|
|
172
|
+
* `path` (default: the path given to the function), on `ease` (default
|
|
173
|
+
* `easeStandard`). It is drawn while it travels; with `hold` it stays at the
|
|
174
|
+
* end of the path once it has arrived.
|
|
175
|
+
* @typedef {{ start: number, duration: number, path?: { at: (f: number) => any }, ease?: (p: number) => number, hold?: boolean }} TokenRun
|
|
176
|
+
*/
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Where each of several tokens is at time t. Any number of tokens may travel
|
|
180
|
+
* at once, on one path or each on its own; a token not yet started, or
|
|
181
|
+
* arrived without `hold`, is left out. A scene keeps the steps settled by
|
|
182
|
+
* having every token arrive, and be gone, before the step's time.
|
|
183
|
+
* @param {{ at: (f: number) => any }} path anything with `at(fraction) → point`: `polyline`, `cubic`, `path3`
|
|
184
|
+
* @param {number} t
|
|
185
|
+
* @param {TokenRun[]} runs
|
|
186
|
+
* @returns {{ index: number, progress: number, point: any, run: TokenRun }[]}
|
|
187
|
+
*/
|
|
188
|
+
export function tokenPoints(path, t, runs) {
|
|
189
|
+
const out = [];
|
|
190
|
+
for (const [index, run] of runs.entries()) {
|
|
191
|
+
const p = progress(t, run.start, run.duration, run.ease ?? easeStandard);
|
|
192
|
+
if (p <= 0 || (p >= 1 && !run.hold)) continue;
|
|
193
|
+
out.push({ index, progress: p, point: (run.path ?? path).at(p), run });
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Several tokens travelling at once: `draw(point, { index, progress, run })`
|
|
200
|
+
* for each token in flight, concatenated. Pure like every frame helper, so any
|
|
201
|
+
* frame is the same whatever was drawn before it.
|
|
202
|
+
* @param {{ at: (f: number) => any }} path
|
|
203
|
+
* @param {number} t
|
|
204
|
+
* @param {TokenRun[]} runs
|
|
205
|
+
* @param {(point: any, info: { index: number, progress: number, run: TokenRun }) => string} draw
|
|
206
|
+
* @returns {string}
|
|
207
|
+
*/
|
|
208
|
+
export function tokensAlong(path, t, runs, draw) {
|
|
209
|
+
return tokenPoints(path, t, runs)
|
|
210
|
+
.map(({ point, index, progress, run }) => draw(point, { index, progress, run }))
|
|
211
|
+
.join("");
|
|
212
|
+
}
|
|
@@ -57,7 +57,8 @@ from the system's package manager (`brew install ffmpeg`, `apt install ffmpeg`).
|
|
|
57
57
|
`state-machine`, `request-journey`, `flowchart`). The user has a Mermaid
|
|
58
58
|
flowchart? `motion-kit import flow.mmd --out flow.json` writes the spec
|
|
59
59
|
(layout computed once). Only write a custom scene module when no type fits
|
|
60
|
-
(`references/custom-scenes.md`)
|
|
60
|
+
(`references/custom-scenes.md`): that file also covers an isometric view
|
|
61
|
+
(camera, solids, depth order, label anchors) and several tokens moving at once.
|
|
61
62
|
4. **Gate.** `motion-kit check spec.json` must pass in every format/locale
|
|
62
63
|
shipped: deterministic, settled steps, rounded numbers, token-only colours,
|
|
63
64
|
escaped labels, labels fit, holds the final frame.
|
|
@@ -112,7 +113,7 @@ headers when redistributing the vendored runtime and adapters.
|
|
|
112
113
|
| `references/targets.md` | Where it will be shown and what each target allows |
|
|
113
114
|
| `references/styles.md` | Neutral default, style files, brand presets, contrast |
|
|
114
115
|
| `references/qc.md` | Review stages, checklist, review-report template |
|
|
115
|
-
| `references/custom-scenes.md` | Writing a one-off scene module |
|
|
116
|
+
| `references/custom-scenes.md` | Writing a one-off scene module, including isometric views and several tokens at once |
|
|
116
117
|
| `references/ecosystem.md` | When GSAP, HyperFrames, Remotion, Motion Canvas, Manim, Mermaid or ELK are the better tool |
|
|
117
118
|
|
|
118
119
|
For rendering, slide packaging and video, see the **motion-render** skill.
|
|
@@ -110,6 +110,55 @@ Every command supports this, `motion-kit build` included (it bundles the whole
|
|
|
110
110
|
runtime and passes it as `kit`). A module that imports instead must use
|
|
111
111
|
relative imports to a vendored runtime.
|
|
112
112
|
|
|
113
|
+
## Isometric and 3D-looking scenes
|
|
114
|
+
|
|
115
|
+
`kit` carries a small isometric kit (`runtime/iso.mjs`), for a floor, machines
|
|
116
|
+
or buildings seen from an angle. Template: `examples/isometric-swivel.scene.mjs`
|
|
117
|
+
(plan view that swivels to isometric, then three work items travel a line).
|
|
118
|
+
Everything is a pure function: the same camera and solids give the same bytes.
|
|
119
|
+
|
|
120
|
+
World: x east, y north, `z` up, in any unit you like. Colours are token names
|
|
121
|
+
(`"surface"`, `"accent"`), never literals; the gate refuses a literal.
|
|
122
|
+
|
|
123
|
+
| Need | Use |
|
|
124
|
+
|---|---|
|
|
125
|
+
| A camera | `camera({ azimuth, elevation, zoom, pan })`: the view's angles in degrees, pixels per world unit, and where the world origin lands. `elevation: 90` with `azimuth: 0` is the plan view (north up); `CAMERA_ISOMETRIC` is true isometric (45° azimuth, `ISO_ELEVATION` ≈ 35.26°); `CAMERA_PLAN` is the plan view |
|
|
126
|
+
| A swivel | `lerpCamera(from, to, progress(t, start, dur, easeStandard))`: every field interpolates, so plan → isometric is one move between two settled steps |
|
|
127
|
+
| Keep it in the picture | `fitCamera(worldPoints, cam, { width, height, margin })` returns `cam` with the pan and zoom that fit the points (the floor corners, the tallest heights, the route). Call it with each frame's camera, and a swivel never clips |
|
|
128
|
+
| A point on the screen | `project(cam, { x, y, z })` → `{ x, y, depth }` (`projector(cam)` for many points; larger `depth` is nearer the viewer) |
|
|
129
|
+
| Solids | `box({ x, y, w, d, h, z })` (centred on x, y), `slab({ x, y, w, d })` (a thin box, for a floor), `prism({ points, h, z })` with `regularPolygon(x, y, r, n)` for a footprint. Options: `fill` (top token), `sides` (side token, default `fill`), `shade` (token layered over the sides at 10–26 %, `null` for flat; `ink` darkens in the light theme and lightens in the dark one, pick `bg` where the dark theme should be darker), `stroke`, `opacity`, `id` |
|
|
130
|
+
| Draw them | `drawSolid(solid, cam)`, or `drawSolids(list, cam)`, which orders them far to near first (`orderSolids` alone returns the order). Only faces that face the camera are drawn: at 90° elevation just the tops |
|
|
131
|
+
| Animate a solid | Build it again each frame with the animated `h`, `z` or `opacity`. Two-state fills cross-fade two solids (`fade(p, {}, drawSolid(reached, cam))` over the pending one), as with any other element |
|
|
132
|
+
| Labels | `labelAnchor(cam, { id, at: { x, y, z }, lines, lift, side, opacity })` → `{ markup, box }`: a dot on the point, a stem `lift` px up, the label above it (`side: "up"`, or beside the stem's top with `"right"` / `"left"`). Wrap and localize `lines` first (`wrapLabel`) |
|
|
133
|
+
| Several tokens | `tokensAlong(path, t, runs, draw)`: see below |
|
|
134
|
+
|
|
135
|
+
**The gate checks labels.** Return `labelBoxes: (t) => [box, …]` from the scene
|
|
136
|
+
(the `box` of each `labelAnchor` you draw at `t`), and `motion-kit check` fails
|
|
137
|
+
the scene when, at any sampled time or step, two label boxes overlap (closer
|
|
138
|
+
than 4 px), a stem runs through another label, or a box leaves the picture. Fix
|
|
139
|
+
it in the layout: alternate `lift` between neighbours (more in a narrow format,
|
|
140
|
+
where they stand closer), shorten the label, or fade labels out while the
|
|
141
|
+
camera moves, as the example does. Boxes with `opacity: 0` are skipped.
|
|
142
|
+
|
|
143
|
+
**Several tokens at once.** `tokensAlong(path, t, runs, draw)` draws every token
|
|
144
|
+
in flight. `path` is anything with `at(fraction)`: `polyline`, `cubic`, or
|
|
145
|
+
`path3(worldPoints)`, which gives positions by distance, so a token moves at a constant speed in the
|
|
146
|
+
world whatever the camera does when its `ease` is linear (the default is
|
|
147
|
+
`easeStandard`; project each point in `draw`). `runs` is `[{ start, duration, ease?,
|
|
148
|
+
path?, hold? }]`, one per token, each with its own start and, if it needs one,
|
|
149
|
+
its own `path`; a token is drawn from `start` until it arrives (kept at the end
|
|
150
|
+
with `hold`). `tokenPoints` gives the positions without drawing. Stagger the
|
|
151
|
+
starts (`stagger()`) so the tokens do not sit on one another. Several tokens
|
|
152
|
+
may move at the same time **inside the story's beats only**: every token has
|
|
153
|
+
arrived, and the arrivals have filled, before the step's time (the settled-step
|
|
154
|
+
rule in the gate applies as ever), and a token that stops mid-path is not a
|
|
155
|
+
resting state. A token never loops back to the start.
|
|
156
|
+
|
|
157
|
+
Canon: no loops, no ambient motion, no continuous scrubbing, 12 s hard limit
|
|
158
|
+
(8 s target). An isometric scene plays once and holds its last frame, like any
|
|
159
|
+
other, and under reduced motion the player shows that frame. A constantly
|
|
160
|
+
moving hero is a 3D model's job, not motion-kit's.
|
|
161
|
+
|
|
113
162
|
## Declared locales and narrative steps
|
|
114
163
|
|
|
115
164
|
Export `const locales = ["en", "nl"]` alongside the default factory so both
|
|
@@ -54,6 +54,29 @@ little later with the same curve: the shape stretches in flight and settles at
|
|
|
54
54
|
its own length. `splitEdge(t, start, dur, lag = 0.07)` → `{ lead, trail }`.
|
|
55
55
|
Use 50–100 ms lag. Draw the shape from `trail` to `lead`.
|
|
56
56
|
|
|
57
|
+
## Camera swivel, depth and several tokens (isometric kit)
|
|
58
|
+
|
|
59
|
+
- **Swivel:** a camera move is one beat on `easeStandard`, 1.2–1.5 s, from one
|
|
60
|
+
settled view to another (plan → isometric is `lerpCamera(plan, iso, p)`).
|
|
61
|
+
Nothing else but the things that need the new view (solids rising to their
|
|
62
|
+
height) moves with it. Fit the camera to the picture each frame, so no frame
|
|
63
|
+
of the swivel clips.
|
|
64
|
+
- **Labels and a moving camera:** fade labels out before the camera moves and
|
|
65
|
+
back in after it rests (≈ 250–400 ms each): text is not read mid-swivel,
|
|
66
|
+
and its boxes cannot collide while it is hidden. The gate checks the boxes at
|
|
67
|
+
every sampled time.
|
|
68
|
+
- **Heights:** solids rise during the swivel, not before it: in plan view
|
|
69
|
+
height is invisible. Draw a flat top first (`h` > 0 only so the faces exist).
|
|
70
|
+
- **Depth:** `orderSolids` is the order; never draw by hand. Heights and
|
|
71
|
+
footprints decide it; a floor slab is drawn first.
|
|
72
|
+
- **Several tokens:** stagger their starts by 0.25–0.4 s on a trip of 1.2–2 s,
|
|
73
|
+
so 3–4 are in flight at once without touching. Use `linear` for tokens that
|
|
74
|
+
travel a conveyor at a steady speed, and grow them in and out over the first
|
|
75
|
+
and last ≈ 8 % of the trip, so they do not pop. All have arrived, and their
|
|
76
|
+
targets have filled, ≥ 50 ms before the step (the usual pause between beats).
|
|
77
|
+
A shadow on the floor under each token (an ellipse of `ink` at ≈ 18 %,
|
|
78
|
+
squashed by `sin(elevation)`) shows where it is in the world.
|
|
79
|
+
|
|
57
80
|
## Container and text timing
|
|
58
81
|
|
|
59
82
|
- The container (box, card) starts moving immediately; new text appears only
|
|
@@ -102,7 +102,9 @@ names a state. Each path edge must start where the previous one ended; branches,
|
|
|
102
102
|
cycles, repeated transitions and self-transitions are supported. The path is
|
|
103
103
|
explicit: the runtime never decides which branch to take. All states appear
|
|
104
104
|
pending, the initial state fills, then a single token follows the path while
|
|
105
|
-
the current state fills accent. Completed edges retain their accent.
|
|
105
|
+
the current state fills accent. Completed edges retain their accent. The
|
|
106
|
+
built-in types carry one token at a time; a custom scene that needs several
|
|
107
|
+
pieces of work moving at once uses `tokensAlong` (`custom-scenes.md`).
|
|
106
108
|
|
|
107
109
|
Layouts use a column in reading order with separate connector lanes outside
|
|
108
110
|
the labels; each fixed format centers the fitted graph, and strips grow to
|