Merge fix/text-bidi (main) into fix/text-fallback
# Conflicts: # docs/roadmap.md
No files matched your search
@@ -18,7 +18,7 @@ crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes,
|
||||
crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009)
|
||||
crates/svg L2 SVG import: shapes, groups, use, styles, gradients, clips/masks → mask layers, text
|
||||
crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format
|
||||
crates/gpu L3 wgpu stage renderer (the default stage): tile binning, compute coverage, bitmaps, filters (ADR 0019, 0031)
|
||||
crates/gpu L3 wgpu stage renderer (the default stage): tile binning, compute coverage, bitmaps, filters (ADR 0019, 0029, 0032)
|
||||
crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve/mcp
|
||||
src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
|
||||
```
|
||||
@@ -31,7 +31,10 @@ a new crate needs a row here and in its `LAYERS` table.
|
||||
|
||||
* **Principal-engineer check.** For every proposal ask: "Is this how a principal engineer
|
||||
would do it?" If not, use the better method or ask the project lead. Record hard-to-reverse
|
||||
decisions as ADRs in `docs/adr/`.
|
||||
decisions as ADRs in `docs/adr/`. **ADR numbers never move:** take the next number above
|
||||
every ADR and every reservation in `docs/adr/README.md`, and reserve it there in the same
|
||||
PR. An open PR keeps its number until it merges or closes, so no one renumbers because
|
||||
another PR merged first; maintainers reserve the numbers outside PRs already use.
|
||||
* **Users are artists and creatives** (many coming from Adobe Animate). The product must be
|
||||
professional, fast, reliable and easy, with smooth, predictable flow: common actions one
|
||||
click or key away, shortcuts for power users, no modal interruptions for routine edits.
|
||||
@@ -40,6 +43,9 @@ a new crate needs a row here and in its `LAYERS` table.
|
||||
(labels, menus, buttons, names, dialog text) is proportional. No raw font sizes or colours
|
||||
outside `theme.rs` (enforced by `guidelines_tests`). Typefaces: Inter + JetBrains Mono via
|
||||
`CRAFT_FONTS_DIR`, with egui defaults as fallback.
|
||||
* **Interface text is translatable** (ADR 0040, `docs/localisation.md`): write English through
|
||||
`tr!` / `trn!` / `tr_noop!`, one template per sentence, and translate keys only where they are
|
||||
drawn. Command ids, the CLI, MCP and the file format stay English. Check with `--lang pseudo`.
|
||||
* **Cross-platform** (ADR 0006): macOS, Windows and Linux are first-class. OS-specific
|
||||
behaviour lives only in `src/platform.rs` (shortcut labels with ⌘ on macOS, app menu,
|
||||
window chrome, settings folder, native dialogs, GPU backend fallback). Shortcut text always
|
||||
@@ -104,8 +110,8 @@ a new crate needs a row here and in its `LAYERS` table.
|
||||
workspace produce artifacts with the same names, so a single shared folder lets one track's
|
||||
build overwrite another's and tests run against the wrong code. Before opening or updating
|
||||
a PR, bring in `origin/main` and keep shared files (CHANGELOG, roadmap, Cargo.lock, the
|
||||
workspace map) conflict-free. ADR numbers are assigned by the lead when a task starts, so
|
||||
parallel tracks never collide. A track never merges its own PR: the lead reviews it
|
||||
workspace map) conflict-free. ADR numbers are reserved in `docs/adr/README.md` when a task
|
||||
starts and never move (see below). A track never merges its own PR: the lead reviews it
|
||||
(principal engineer and senior designer) and merges it when CI is green, one at a time.
|
||||
* **A new command namespace** needs a plug-in policy (`plugin_may_call` in
|
||||
`crates/engine/src/cmds_plugin.rs`); a test fails until it has one.
|
||||
|
||||
@@ -19,7 +19,7 @@ shaders or SDK code).
|
||||
| Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | <https://github.com/source-foundry/Hack> | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) |
|
||||
| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | <https://github.com/googlefonts/noto-emoji> | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) |
|
||||
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
|
||||
| `assets/icons/anicraft-*.svg` (16 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound) | Align panel, layer-type, Width tool, Camera, Brush, Eraser and Eyedropper tool icons, the timeline's mute toggle | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
|
||||
| `assets/icons/anicraft-*.svg` (19 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
|
||||
| `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
| `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) |
|
||||
@@ -58,6 +58,13 @@ here.
|
||||
| Inter Regular | UI prose (primary) | The Inter Project Authors (Rasmus Andersson) | SIL OFL 1.1, shipped as `OFL-Inter.txt` |
|
||||
| JetBrains Mono Regular | UI data: timeline, readouts, values, shortcuts (primary) | The JetBrains Mono Project Authors | SIL OFL 1.1, shipped as `OFL-JetBrainsMono.txt` |
|
||||
|
||||
### Optional build input: craft-i18n (not files in this repo)
|
||||
|
||||
Builds made with `CRAFT_I18N_DIR` (ADR 0040) embed the interface catalogs of the shared
|
||||
[storytold/craft-i18n](https://github.com/storytold/craft-i18n) repository
|
||||
(`locales/<locale>/common.tsv` and `anicraft.tsv`), MIT OR Apache-2.0, by its translators
|
||||
(credited in its own `ATTRIBUTION.md`). No catalog file is committed here.
|
||||
|
||||
No font *files* are committed. Every committed image, icon and sound (the two tiny test sounds)
|
||||
is listed above; everything else is either embedded by a dependency crate or generated by our
|
||||
code.
|
||||
@@ -72,6 +79,8 @@ OR Apache-2.0) is noted in the table.
|
||||
|---|---|---|---|
|
||||
| Signed-area coverage accumulation rasterizer | `crates/render/src/raster.rs` | Raph Levien, *font-rs* (2016), <https://github.com/raphlinus/font-rs>, Apache-2.0; also stb_truetype v2 (public domain) | Our implementation follows the published accumulate-and-prefix-sum approach. Credited here; Apache-2.0 includes a patent licence. |
|
||||
| Tile binning with per-row backdrops; per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (<https://github.com/linebender/vello>, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019). |
|
||||
| Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), <https://cldr.unicode.org>, Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. |
|
||||
| Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). |
|
||||
| Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | |
|
||||
| Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. |
|
||||
| Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs`, `crates/gpu/src/fine.wgsl` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. |
|
||||
@@ -80,6 +89,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| Bevel and Gradient Bevel by offset differences of the blurred opacity; Gradient Glow and Gradient Bevel through a colour ramp | `crates/render/src/filters.rs` | Standard image processing: embossing as the difference of an image offset along the light direction (a directional derivative; e.g. R. C. Gonzalez & R. E. Woods, *Digital Image Processing*); parameters and behaviour from Adobe's public Animate user guide and ActionScript 3.0 reference (`BevelFilter`, `GradientGlowFilter`, `GradientBevelFilter`) | Public descriptions only; no Adobe code or assets (ADR 0025). |
|
||||
| Bevel and gradient filters in SVG export (`feComposite` arithmetic, `feComponentTransfer` tables) | `crates/render/src/svg.rs` | W3C Filter Effects Module Level 1 / SVG 1.1 filters | W3C Royalty-Free Patent Policy. |
|
||||
| Timeline playback semantics for actions (stop, play, go to frame or label, next/previous frame and scene; button Up/Over/Down/Hit states; mouse events) | `crates/actions`, `crates/doc/src/player.rs` | Behaviour learned from Adobe's public *ActionScript 3.0 Reference* (`MovieClip`, `SimpleButton`, `MouseEvent`) and the public Animate user guide on buttons, plus observation (ADR 0013, ADR 0024) | Clean room: no Adobe code, SDKs or players; names used nominatively. |
|
||||
| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the action IR | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `EventDispatcher.addEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. |
|
||||
| Cubic-Bézier easing (CSS model) | `crates/doc/src/easing.rs` | W3C CSS Easing Functions Level 1 | W3C Royalty-Free Patent Policy. |
|
||||
| SVG path data syntax (file format v2) | `crates/geom/src/path.rs` | W3C SVG 1.1 / 2 | W3C Royalty-Free Patent Policy. |
|
||||
| Marching-squares contour tracing (Paint Bucket regions, Brush outlines) | `crates/geom/src/trace.rs` | Lorensen & Cline (1987); public algorithm | Ported from PhotoCraft's mask tracer (same project family and licence) and reviewed. |
|
||||
@@ -95,10 +105,13 @@ OR Apache-2.0) is noted in the table.
|
||||
| Affine QR decomposition for tweening | `crates/geom/src/affine.rs` | Standard linear algebra | |
|
||||
| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. |
|
||||
| Monotone cubic interpolation of stroke widths (width profiles) | `crates/doc/src/width.rs` | F. N. Fritsch and R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 17(2), 1980 | Published algorithm (harmonic-mean tangents). |
|
||||
| Stroke caps, joins, miter limit and dash patterns (`butt`/`square` caps, miter length and limit, dash arrays restarting per subpath, zero-length round-capped dashes as dots) | `crates/doc/src/stroke_style.rs`, `crates/render/src/stroke.rs`, SVG/HTML/Lottie export, `crates/svg` | W3C SVG 1.1 §11.4 and SVG 2 / CSS Fill and Stroke Module Level 3 (stroke properties); WHATWG HTML canvas line styles; the public Lottie JSON schema (`lc`, `lj`, `ml`, `d`); public descriptions of XFL `SolidStroke`/`DashedStroke`/`DottedStroke` attributes | W3C Royalty-Free Patent Policy; open specifications. |
|
||||
| Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. |
|
||||
| Brush outlines (the swept tip as a signed distance field: exact distance to the convex hull of two tips, L2 for round and L∞ for square tips, minimised in closed form; traced at level zero) | `crates/geom/src/brush.rs` | Standard sweep and distance-field constructions from the public computer-graphics literature; behaviour of Animate's Brush tool learned from Adobe's public help and observation | Own implementation (ADR 0033); no Adobe code or presets. |
|
||||
| Eraser (the swept tip as a fill in the planar merge whose regions are dropped; exact fill areas by Green's theorem with five-point Gauss–Legendre quadrature) and Eyedropper | `crates/engine/src/cmds_erase.rs`, `crates/engine/src/cmds_paint.rs` | Green's theorem and Gauss–Legendre quadrature (public mathematical results); behaviour of Animate's Eraser and Eyedropper learned from Adobe's public help and observation | Own implementation (ADR 0034); no Adobe code or presets. |
|
||||
| WebAssembly plug-in host (module validation, limits, fuel, resumable host calls) | `crates/plugins` | W3C WebAssembly Core Specification 1.0 / 2.0 (W3C Royalty-Free Patent Policy); the `wasmi` interpreter (MIT OR Apache-2.0) | Host model ported from PhotoCraft's filter plug-ins (same project family and licence) and extended with the AniCraft request ABI (ADR 0017). |
|
||||
| Selection tool on raw shapes: bending an edge (least-squares control-point move), following a bent edge in every shape that shares it, snapping, a marquee that cuts | `crates/geom/src/raw.rs`, `crates/geom/src/planar.rs`, `crates/engine/src/cmds_raw.rs` | Bernstein polynomials and least squares (public mathematical results); behaviour of Animate's Selection tool learned from issue #42, Adobe's public help and observation | Own implementation (ADR 0041); no Adobe code. |
|
||||
| Inverse kinematics by cyclic coordinate descent (bone drags, `bone.solve`), with joint limits as a clamp per step | `crates/doc/src/armature.rs` | L.-C. T. Wang and C. C. Chen, *A combined optimization method for solving the inverse kinematics problem of mechanical manipulators*, IEEE Trans. Robotics and Automation 7(4), 1991; C. Welman, *Inverse Kinematics and Geometric Constraints for Articulated Figure Manipulation*, MSc thesis, Simon Fraser University, 1993 | Published algorithm; own implementation (ADR 0043). |
|
||||
| De Casteljau subdivision, Ramer–Douglas–Peucker simplification | `crates/geom/src/edit.rs` | Public mathematical results (de Casteljau 1959; Ramer 1972; Douglas & Peucker 1973) | |
|
||||
| WAV (RIFF WAVE) reading and writing: PCM 8/16/24/32-bit, IEEE float, `WAVE_FORMAT_EXTENSIBLE` | `crates/audio/src/wav.rs` | Microsoft/IBM, *Multimedia Programming Interface and Data Specifications 1.0* (1991), and Microsoft's public `WAVE_FORMAT_EXTENSIBLE` description | Public file format descriptions. |
|
||||
| Resampling by cubic Hermite (Catmull-Rom) interpolation | `crates/audio/src/mix.rs` | E. Catmull and R. Rom, *A class of local interpolating splines* (1974); R. Keys, *Cubic convolution interpolation for digital image processing* (1981) | Public mathematical results. |
|
||||
|
||||
@@ -2,6 +2,195 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Motion path points pinned to frames** (ADR 0049, M2). As in Animate, a motion tween's
|
||||
position keyframes are now points on its path: move the object at a frame and the path gets a
|
||||
point there that the object passes exactly on that frame, whatever else you do to the path.
|
||||
* Moving the object between the ends adds a pinned point where you put it; after the last
|
||||
position keyframe the path carries on to the new place. The eases on X and Y time the
|
||||
object between pinned points as they did between the ends.
|
||||
* Pinned points are diamonds with their frame number on the stage, and Selection can drag
|
||||
them. With Subselection, right-click any point to **Pin to Frame** (the playhead's frame)
|
||||
or **Unpin**. Properties › Frame has **Pin Here** / **Unpin**, and F6 inside a path tween
|
||||
pins where the object is.
|
||||
* The Motion Editor draws a pinned frame's X and Y keys in blue; dragging one moves its
|
||||
point. The timeline marks pinned frames with a larger diamond.
|
||||
* Adding and deleting points keeps the pins on their points; deleting a pinned point, or
|
||||
unpinning it, removes its frame's X and Y keys and the motion flows as before.
|
||||
* Older files open and play exactly as they did (only the ends are pinned).
|
||||
* Headless: new `motion.pin_point` and `motion.unpin_point`; `motion.info` and the path
|
||||
commands report `pins`.
|
||||
|
||||
* **Stroke caps, joins, miter limit, and dashed and dotted lines** (ADR 0046, M7). Properties ›
|
||||
Stroke has Animate's rows: **Style** (Solid, Dashed with a dash and gap editor, Dotted with
|
||||
dot spacing), **Cap** (None, Round, Square), **Join** (Miter, Round, Bevel) and **Miter**
|
||||
(the limit past which corners are bevelled). The drawing tools' options set them for new
|
||||
strokes, the Ink Bottle gives them and the Eyedropper picks them.
|
||||
* Drawn exactly by the CPU renderer and the GPU stage: butt and square caps, miter joins with
|
||||
their limit, dashes by arc length along curves (restarting on each subpath, an offset into
|
||||
the pattern), round dots one width across, and dashes that keep a width profile's widths.
|
||||
Patterns finer than a pixel draw solid and lighter. No slower than round strokes.
|
||||
* SVG, HTML canvas and Lottie export write caps, joins, miter limit and dashes; SVG import
|
||||
reads `stroke-linecap`, `stroke-linejoin`, `stroke-miterlimit`, `stroke-dasharray` and
|
||||
`stroke-dashoffset`; Animate documents bring their caps, joins, miter limit, dashed and
|
||||
dotted strokes (ragged, stipple and hatched strokes are drawn solid and reported).
|
||||
* Merge drawing keeps a dashed line's style on every piece it is cut into; shape tweens blend
|
||||
miter limits and dash lengths. Older files open unchanged.
|
||||
* Headless: new `stroke.set_style`; `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`
|
||||
and `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`.
|
||||
* **Onion skin controls and Edit Multiple Frames** (ADR 0047, M1). Onion skin works as Animate
|
||||
users expect:
|
||||
* **Markers** on the frame ruler: drag the start and end brackets to choose how many frames
|
||||
show before and after the playhead. The onion menu (the arrow next to the timeline's onion
|
||||
buttons, a right-click on the ruler, or View › Onion Skin Options) has Always Show Markers,
|
||||
Anchor Markers (they stay put when the playhead moves), and the Onion 2, Onion 5 and Onion
|
||||
All presets.
|
||||
* Frames before the playhead are tinted blue and frames after it green, each fainter the
|
||||
farther it is. Pick your own colours or turn tinting or fading off in the menu; **Outlines**
|
||||
draws onion frames as outlines only, and **Keyframes Only** shows only keyframes. Your
|
||||
choices are remembered.
|
||||
* Onion frames now show over a background layer (they used to be hidden under it), and locked
|
||||
layers are left out, as in Animate.
|
||||
* **Edit Multiple Frames** (the timeline button next to Onion Skin) shows every keyframe
|
||||
between the markers at full strength. Click, Shift-click, marquee or Select All to select
|
||||
artwork on all of them, then drag it or use the arrow keys to move it everywhere at once:
|
||||
one undo step. A motion tween's path moves with its object.
|
||||
* Headless: `frames.artwork` lists the artwork on those keyframes and
|
||||
`frames.edit_multiple` moves it.
|
||||
* **ActionScript that controls the timeline now runs** (ADR 0013 tier 2). Frame scripts in
|
||||
Animate documents, and ones you type in the Actions panel, play in Test Movie and in the
|
||||
HTML canvas export when they use the ActionScript 3.0 most animation and e-learning files
|
||||
use: `stop()`, `play()`, `gotoAndPlay`/`gotoAndStop` by frame or label (and scene),
|
||||
`nextFrame()`, `prevFrame()`, `nextScene()`, `prevScene()`, on this timeline or on named
|
||||
instances (`hero_mc.gotoAndStop("run")`, `MovieClip(parent).play()`); button and movie clip
|
||||
listeners (`btn.addEventListener(MouseEvent.CLICK, onClick)` for click, mouse down and up,
|
||||
roll over and out, with a named or inline function); `trace`; and setting `x`, `y`,
|
||||
`alpha`, `visible`, `rotation`, `scaleX` and `scaleY`.
|
||||
* A script runs whole or not at all. Anything else (variables, `if`, loops, reading
|
||||
properties) keeps it from running, and AniCraft says where: the Script view lists each
|
||||
problem with its line and column above the code and marks the lines (click one to go
|
||||
there), or says the script runs. Test Movie's Output begins with which scripts run and
|
||||
which don't, and why.
|
||||
* `navigateToURL` and other calls that reach outside the movie are ignored and noted.
|
||||
* The XFL import report lists the frame scripts that run apart from those only kept.
|
||||
* Headless: `script.set` and `script.list` say `runs` and `problems`; new `script.check`
|
||||
compiles a text without storing it. A new XFL corpus package, `interactive`, plays its
|
||||
ActionScript through the player.
|
||||
* **Selection across layers** (ADR 0044, issue #42, M1). A selection can hold artwork on several
|
||||
layers, as in Animate:
|
||||
* The Selection tool's **marquee** selects on every visible, unlocked layer, cutting raw fills
|
||||
and lines at its edges on each layer (and taking the cut back when you let go of it).
|
||||
**Shift-click** adds or removes artwork on any layer; **Select All** (Ctrl+A) takes every
|
||||
unlocked layer. Locked and hidden layers are never selected; locking or hiding a layer lets
|
||||
go of what was selected on it.
|
||||
* Move, nudge, delete, duplicate, arrange (within each layer), transforms, alpha, fill and
|
||||
stroke, filters, blending, break apart and width profiles act on every selected layer, one
|
||||
undo step per gesture. Inside a tween each layer gets its own keyframe.
|
||||
* Align and distribute work across the layers; Free Transform's box covers the whole
|
||||
selection; copy keeps each layer's artwork apart, and paste puts it back on those layers
|
||||
(or on the active layer and the ones below, creating missing layers in another document).
|
||||
* **Convert to Symbol** (F8) of a selection on several layers keeps those layers inside the
|
||||
symbol and places the instance on the topmost of them.
|
||||
* The **timeline** shows a square in the layer's colour after the name of every layer with
|
||||
selected artwork. **Properties** says "6 elements on 4 layers", shows the combined box's
|
||||
position, and marks values that differ as "mixed".
|
||||
* Headless: `element.select` takes ids on any layer (and `layer?`); `doc.info` reports
|
||||
`selection_layers`; per-layer commands report the `layers` they ran on.
|
||||
* Clicking a layer's name in the timeline selects all of its artwork at the playhead and
|
||||
makes it active, as in Animate (`layer.select {select: true}`).
|
||||
* Not yet: "mixed" on every Properties row.
|
||||
|
||||
* **Interface languages** (ADR 0040, first slice; `docs/localisation.md`). Every string the
|
||||
window shows, and every name a screen reader announces, can now be translated.
|
||||
* Preferences › Appearance › **Language**: *System language* by default, or any language
|
||||
this build has, named in itself. A change shows at once. `--lang <code>` sets it for one
|
||||
run.
|
||||
* Translations come from the Craft family's shared **craft-i18n** catalogs, built in with
|
||||
`CRAFT_I18N_DIR`; a missing one shows the English. craft-i18n has no AniCraft catalog yet,
|
||||
so builds are English for now: `scripts/i18n-extract.sh` lists every string for
|
||||
translators (and, with a craft-i18n checkout, how much each language already covers).
|
||||
* A **pseudo-locale** (`--lang pseudo`) draws everything accented, longer and bracketed, to
|
||||
find text that skipped translation or gets cut off.
|
||||
* Messages that say how to undo show your Undo key as this computer writes it (⌘Z on a
|
||||
Mac, and a rebound key wherever it is), instead of a fixed "Ctrl+Z".
|
||||
* Menus, the command palette and the shortcut sheet translate the command registry's labels
|
||||
as they are drawn; command ids, `.anicraft` files, `anicraft-cli` and MCP stay English.
|
||||
* For developers: `tr!`, `trn!` (plurals by CLDR rules), `trc!` and `tr_noop!`; a test fails
|
||||
on new interface text that skips them. Not yet: engine messages, right-to-left languages
|
||||
(egui can't lay them out yet), Chinese, Japanese and Korean (need a font).
|
||||
|
||||
* **Bone tool and inverse kinematics, first slice** (ADR 0043, M7). Join symbol instances into
|
||||
an armature and pose it:
|
||||
* With the **Bone tool** (M), drag from one symbol instance to another: a bone joins them and
|
||||
both move to a new **armature layer** (bone icon in the timeline). Drag from a bone's end to
|
||||
the next instance to continue the chain; drag from any instance of the armature to branch.
|
||||
* Bones show on the stage as wedges from their round joint to their end, in the armature
|
||||
layer's colour; click one to select it (selection colour).
|
||||
* With the **Selection tool**, drag a bone or an instance to pose the armature by inverse
|
||||
kinematics: the bones above it turn so it follows the pointer; an unreachable point leaves
|
||||
the chain stretched straight toward it. Drag the root instance to move the whole armature.
|
||||
Each drag is one undo step.
|
||||
* A pose at another frame keys it; poses tween with the span's easing and are exact at their
|
||||
keyframes. Every export, the GPU stage and Test Movie show them.
|
||||
* **Properties › Bone**: the joint angle at the playhead, Constrain rotation with min and
|
||||
max (kept in every pose), Pin (the bone and those it hangs from stay put while you drag
|
||||
below it), and Remove Bone (also Delete). Removing frees the instances where they are, on
|
||||
a layer of their own; it asks first when the armature has more than one pose.
|
||||
* Headless: `bone.add`, `bone.remove`, `bone.set_limits`, `bone.pin`, `bone.pose`,
|
||||
`bone.solve` (IK) and `bone.info`; plug-ins may call them. A 64-bone chain solves in about
|
||||
5 ms from rest.
|
||||
* Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import of
|
||||
armature layers, editing armature members' colour effects in place.
|
||||
|
||||
* **Subselection on raw drawings, Snap to Objects, and merging everywhere** (ADR 0042, issue
|
||||
#42). With Object Drawing off:
|
||||
* Click a raw line or fill with the **Subselection tool** (A) to see the points of everything
|
||||
connected to it: hollow squares, one per shared corner. Click a point to select it (Shift
|
||||
adds or removes). The curve handles of the selected points, and of the edge you clicked,
|
||||
show as lines ending in dots.
|
||||
* Drag a point to move it together with the other selected points; every shape that shares
|
||||
a point moves with it, and it snaps as with the Selection tool. Drag a handle to change the
|
||||
curve; a fill and its outline change together.
|
||||
* Drag a line or fill to move everything connected to it. A marquee shows the shapes it
|
||||
touches on the active layer and selects the points inside it. Arrow keys move the selected
|
||||
points 1 screen pixel (Shift: 10). Each drag or press is one undo step.
|
||||
* **Snap to Objects**, in View › Snapping, as the magnet under the tools and in the
|
||||
selection tools' options, turns snapping on and off. It is on by default.
|
||||
* **The Paint Bucket** fills a raw drawing exactly up to its lines and fill edges, and the
|
||||
fill joins any fill of its colour it touches. Recolouring a fill joins it to its new
|
||||
colour's neighbours.
|
||||
* **Pasted** raw shapes (Paste and Paste in Place) cut and join the drawing they land on.
|
||||
* **Animate files**: raw shapes open as raw shapes, merged into one drawing per keyframe.
|
||||
Drawing objects and groups stay objects.
|
||||
* **Gradient and bitmap fills** now merge like solid ones, each piece keeping its part of the
|
||||
gradient. Strokes with a width profile are still drawn as objects.
|
||||
|
||||
Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on
|
||||
`raw.move_point`, `draw.snap_to_objects`, and `object` on `paint.bucket`; plug-ins may call
|
||||
them.
|
||||
|
||||
* **The Selection tool on raw drawings** (ADR 0041, issue #42). With Object Drawing off, the
|
||||
Selection tool now edits raw strokes and fills the way Animate does:
|
||||
* Drag an unselected line or the edge of a fill to **bend** it. The segment becomes a curve
|
||||
through the point you drag, its ends stay put, and a fill under an outline (or next to it)
|
||||
bends with it. Straight lines stay straight until you drag them.
|
||||
* Drag an unselected **corner or end** to move it. Every raw shape that shares the point
|
||||
moves with it, so the drawing stays joined; where a line ends on an edge, the edge moves
|
||||
too.
|
||||
* Drag a fill to move only that fill, not its outline. Drag anything selected to move the
|
||||
selection.
|
||||
* A small corner or curve mark next to the pointer shows what a drag will do.
|
||||
* Dragged points and selections **snap** to corners, ends, lines and fill edges within 10
|
||||
screen pixels, at any zoom, with a ring where they snap. Arrow-key nudges join ends within
|
||||
0.2 px at their midpoint, and an end that comes within 0.2 px of a line goes onto it
|
||||
without changing the line.
|
||||
* The **marquee** selects the parts of raw fills and lines under it, cut at its edges, and
|
||||
objects wholly inside it; Shift adds more. If you click away without changing them, the
|
||||
drawing is whole again: selecting is never an undo step and leaves a saved file saved.
|
||||
* Each drag is one undo step, and what it changed merges again when you let go.
|
||||
|
||||
Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`,
|
||||
and `snap`/`from` on `element.translate`; plug-ins may call them.
|
||||
|
||||
* **Sound effects, layer volume and sounds inside symbols** (ADR 0039, M5 second slice).
|
||||
* Properties › Sound has an **Effect**, as in Animate: Left channel, Right channel, Fade left
|
||||
to right, Fade right to left, Fade in and Fade out, shaped over the time the sound is
|
||||
|
||||
@@ -223,6 +223,7 @@ dependencies = [
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
@@ -3810,6 +3811,18 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sys-locale"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tag_ptr"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -98,6 +98,8 @@ fontdb.workspace = true
|
||||
anicraft-audio.workspace = true
|
||||
serde_json.workspace = true
|
||||
web-time.workspace = true
|
||||
# The system's interface language, for the default language (ADR 0040; MIT OR Apache-2.0).
|
||||
sys-locale = "0.3"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
eframe.workspace = true
|
||||
@@ -114,6 +116,8 @@ eframe = { version = "0.36", default-features = false, features = ["accesskit",
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
# In the browser the page's language (navigator.languages) is the system's.
|
||||
sys-locale = { version = "0.3", features = ["js"] }
|
||||
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] }
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -194,8 +194,8 @@ The details, including the server entry for other MCP clients, are in [`docs/mcp
|
||||
|
||||
[**docs/roadmap.md**](docs/roadmap.md) has the honest status by dimension, milestones M0–M8 and what's next.
|
||||
|
||||
**What's missing:** audio layers, ActionScript (frame scripts are counted
|
||||
on import but not kept yet, ADR 0013), motion tweens from XFL, a GPU renderer, and macOS and Linux CI runners
|
||||
**What's missing:** audio layers, ActionScript beyond the timeline subset (frame scripts
|
||||
are kept, and those that control the timeline run; ADR 0013), motion tweens from XFL, a GPU renderer, and macOS and Linux CI runners
|
||||
(AniCraft is verified on Windows so far).
|
||||
|
||||
**Workspace:** strict downward-only layering, checked by `cargo test`:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="6" cy="6" r="3" />
|
||||
<path d="M8.1 3.9 L16.6 16.6 L3.9 8.1" />
|
||||
<circle cx="18" cy="18" r="2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 301 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M9 3 L19 3 A2 2 0 0 1 21 5 L21 15" />
|
||||
<path d="M6 6 L16 6 A2 2 0 0 1 18 8 L18 18" />
|
||||
<rect x="3" y="9" width="12" height="12" rx="2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 340 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M5 4 L10 4 L10 12 A2 2 0 0 0 14 12 L14 4 L19 4 L19 12 A7 7 0 0 1 5 12 Z" />
|
||||
<path d="M5 8 L10 8" />
|
||||
<path d="M14 8 L19 8" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 329 B |
@@ -1,10 +1,13 @@
|
||||
//! Optional font build input (the Craft family convention, as in PhotoCraft), and the app icon
|
||||
//! Optional build inputs (the Craft family convention, as in PhotoCraft), and the app icon
|
||||
//! embedded in the Windows executable.
|
||||
//!
|
||||
//! `CRAFT_FONTS_DIR=<craft-fonts checkout> cargo build` embeds the UI typefaces chosen in
|
||||
//! ADR 0005: Inter (prose) and JetBrains Mono (data), both SIL OFL 1.1. Font files are never
|
||||
//! committed to this repository. Without the variable the app uses egui's bundled defaults, and
|
||||
//! everything still works.
|
||||
//!
|
||||
//! `CRAFT_I18N_DIR=<craft-i18n checkout>` embeds the interface catalogs (ADR 0040); without it
|
||||
//! the interface is English. Neither repository is ever a Cargo dependency.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -123,8 +126,92 @@ fn main() {
|
||||
}
|
||||
}
|
||||
code.push_str(&format!("pub const CRAFT_FONT_BYTES: u64 = {total};\n"));
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("fonts.rs");
|
||||
let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default());
|
||||
let out = out_dir.join("fonts.rs");
|
||||
if let Err(e) = std::fs::write(&out, code) {
|
||||
println!("cargo:warning=could not write {}: {e}", out.display());
|
||||
}
|
||||
let out = out_dir.join("craft_i18n.rs");
|
||||
if let Err(e) = std::fs::write(&out, craft_i18n()) {
|
||||
println!("cargo:warning=could not write {}: {e}", out.display());
|
||||
}
|
||||
}
|
||||
|
||||
/// AniCraft's own catalog in a craft-i18n locale: `locales/<locale>/anicraft.tsv`.
|
||||
const APP_CATALOG: &str = "anicraft.tsv";
|
||||
|
||||
/// `CRAFT_I18N` (ADR 0040), as craft-i18n's `docs/integration.md` describes: one
|
||||
/// `(locale, common.tsv, anicraft.tsv)` entry per locale with AniCraft's own catalog, and the
|
||||
/// base language of a regional one (`pt` for `pt-br`) so it can fall back, embedded with
|
||||
/// `include_str!`. Without `CRAFT_I18N_DIR` the list is empty and the interface is English.
|
||||
/// `CRAFT_I18N_REQUIRED=1` makes a missing or empty checkout an error (for releases).
|
||||
fn craft_i18n() -> String {
|
||||
println!("cargo:rerun-if-env-changed=CRAFT_I18N_DIR");
|
||||
let required = required("CRAFT_I18N_REQUIRED");
|
||||
let entries = match std::env::var_os("CRAFT_I18N_DIR").filter(|d| !d.is_empty()) {
|
||||
// Not canonicalized: on Windows that gives `\\?\C:\…`.
|
||||
Some(dir) => i18n_locales(&PathBuf::from(dir).join("locales")).unwrap_or_else(|e| {
|
||||
if required {
|
||||
fail(&format!("CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR: {e}"));
|
||||
}
|
||||
println!("cargo:warning=CRAFT_I18N_DIR: {e}; the interface is English only");
|
||||
Vec::new()
|
||||
}),
|
||||
None => {
|
||||
if required {
|
||||
fail("CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR is not set");
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let mut code = String::from("// Generated by build.rs (CRAFT_I18N_DIR catalog input).\npub static CRAFT_I18N: &[(&str, &str, &str)] = &[\n");
|
||||
let include = |p: &Option<PathBuf>| p.as_ref().map_or_else(|| "\"\"".to_string(), |p| format!("include_str!({:?})", p.display().to_string()));
|
||||
for (locale, common, app) in entries {
|
||||
code.push_str(&format!(" ({locale:?}, {}, {}),\n", include(&common), include(&app)));
|
||||
}
|
||||
code.push_str("];\n");
|
||||
code
|
||||
}
|
||||
|
||||
/// `(locale, common.tsv, anicraft.tsv)` for every locale under `dir` with AniCraft's catalog,
|
||||
/// and for the base language of each regional one.
|
||||
type I18nEntry = (String, Option<PathBuf>, Option<PathBuf>);
|
||||
|
||||
fn i18n_locales(dir: &Path) -> Result<Vec<I18nEntry>, String> {
|
||||
// `include_str!` resolves a relative path against the generated file, not this crate.
|
||||
if !dir.is_absolute() {
|
||||
return Err(format!("{} is not an absolute path", dir.display()));
|
||||
}
|
||||
let list = std::fs::read_dir(dir).map_err(|e| format!("{} is not a craft-i18n checkout ({e})", dir.display()))?;
|
||||
println!("cargo:rerun-if-changed={}", dir.display());
|
||||
let file = |locale: &str, name: &str| Some(dir.join(locale).join(name)).filter(|p| p.is_file());
|
||||
let mut wanted: Vec<String> = Vec::new();
|
||||
for path in list.flatten().map(|e| e.path()) {
|
||||
let Some(locale) = path.file_name().and_then(|n| n.to_str()).map(str::to_ascii_lowercase) else { continue };
|
||||
if !path.join(APP_CATALOG).is_file() {
|
||||
continue;
|
||||
}
|
||||
// A regional locale (last subtag two letters or three digits) falls back to its base.
|
||||
if let Some((base, region)) = locale.rsplit_once('-')
|
||||
&& ((region.len() == 2 && region.chars().all(|c| c.is_ascii_alphabetic())) || (region.len() == 3 && region.chars().all(|c| c.is_ascii_digit())))
|
||||
&& dir.join(base).is_dir()
|
||||
{
|
||||
wanted.push(base.to_string());
|
||||
}
|
||||
wanted.push(locale);
|
||||
}
|
||||
wanted.sort();
|
||||
wanted.dedup();
|
||||
if wanted.is_empty() {
|
||||
return Err(format!("{} has no locale with {APP_CATALOG} yet", dir.display()));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for locale in wanted {
|
||||
let (common, app) = (file(&locale, "common.tsv"), file(&locale, APP_CATALOG));
|
||||
for p in common.iter().chain(app.iter()) {
|
||||
println!("cargo:rerun-if-changed={}", p.display());
|
||||
}
|
||||
out.push((locale, common, app));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
//! The lexer: source text to tokens with their line and column (ECMA-262 3rd edition §7, with
|
||||
//! ActionScript 3.0's extra punctuators). Bounded: it stops with a problem after
|
||||
//! [`super::MAX_TOKENS`] tokens.
|
||||
|
||||
use super::{MAX_TOKENS, Pos, Problem};
|
||||
|
||||
/// A token's kind.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Tok {
|
||||
/// An identifier or a keyword (the parser tells them apart).
|
||||
Name(String),
|
||||
Num(f64),
|
||||
Str(String),
|
||||
/// A punctuator, as written (`(`, `===`, `>>>=`, …).
|
||||
Punct(&'static str),
|
||||
Eof,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Token {
|
||||
pub tok: Tok,
|
||||
pub pos: Pos,
|
||||
/// A line break comes before it (for semicolon insertion).
|
||||
pub nl: bool,
|
||||
}
|
||||
|
||||
/// Longest first, so the scan takes the longest punctuator that matches.
|
||||
const PUNCTS: [&str; 54] = [
|
||||
">>>=", "...", "===", "!==", ">>>", "<<=", ">>=", "&&=", "||=", "::", "..", "==", "!=", "<=", ">=", "&&", "||", "++", "--", "<<", ">>", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", ".<", "{", "}", "(", ")", "[", "]", ";", ",", "<", ">", "+", "-", "*", "/", "%", "&", "|", "^", "!", "~", "?", ":", "=", ".",
|
||||
];
|
||||
|
||||
fn ident_start(c: char) -> bool {
|
||||
c.is_alphabetic() || c == '_' || c == '$'
|
||||
}
|
||||
|
||||
fn ident_part(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_' || c == '$'
|
||||
}
|
||||
|
||||
struct Lexer<'a> {
|
||||
src: &'a str,
|
||||
/// Byte offset of the next character.
|
||||
at: usize,
|
||||
line: u32,
|
||||
col: u32,
|
||||
}
|
||||
|
||||
impl Lexer<'_> {
|
||||
fn peek(&self) -> Option<char> {
|
||||
self.src.get(self.at..).and_then(|s| s.chars().next())
|
||||
}
|
||||
|
||||
fn peek2(&self) -> Option<char> {
|
||||
self.src.get(self.at..).and_then(|s| s.chars().nth(1))
|
||||
}
|
||||
|
||||
fn pos(&self) -> Pos {
|
||||
Pos { line: self.line, column: self.col }
|
||||
}
|
||||
|
||||
/// Takes one character; a CR LF pair counts as one line break.
|
||||
fn bump(&mut self) -> Option<char> {
|
||||
let c = self.peek()?;
|
||||
self.at += c.len_utf8();
|
||||
match c {
|
||||
'\r' if self.peek() == Some('\n') => {}
|
||||
'\n' | '\r' | '\u{2028}' | '\u{2029}' => {
|
||||
self.line = self.line.saturating_add(1);
|
||||
self.col = 1;
|
||||
}
|
||||
_ => self.col = self.col.saturating_add(1),
|
||||
}
|
||||
Some(c)
|
||||
}
|
||||
|
||||
/// Skips white space and comments; `true` when a line break was among them.
|
||||
fn skip(&mut self) -> Result<bool, Problem> {
|
||||
let mut nl = false;
|
||||
loop {
|
||||
match self.peek() {
|
||||
Some('\n' | '\r' | '\u{2028}' | '\u{2029}') => {
|
||||
nl = true;
|
||||
self.bump();
|
||||
}
|
||||
Some(c) if c.is_whitespace() || c == '\u{feff}' => {
|
||||
self.bump();
|
||||
}
|
||||
Some('/') if self.peek2() == Some('/') => {
|
||||
while self.peek().is_some_and(|c| !matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')) {
|
||||
self.bump();
|
||||
}
|
||||
}
|
||||
Some('/') if self.peek2() == Some('*') => {
|
||||
let start = self.pos();
|
||||
self.bump();
|
||||
self.bump();
|
||||
loop {
|
||||
match self.bump() {
|
||||
None => return Err(Problem::at(start, "this comment is never closed (a `*/` is missing)")),
|
||||
Some('*') if self.peek() == Some('/') => {
|
||||
self.bump();
|
||||
break;
|
||||
}
|
||||
Some('\n' | '\r' | '\u{2028}' | '\u{2029}') => nl = true,
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return Ok(nl),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn number(&mut self, start: Pos) -> Result<f64, Problem> {
|
||||
let from = self.at;
|
||||
if self.peek() == Some('0') && matches!(self.peek2(), Some('x' | 'X')) {
|
||||
self.bump();
|
||||
self.bump();
|
||||
let mut v = 0f64;
|
||||
let mut digits = 0;
|
||||
while let Some(d) = self.peek().and_then(|c| c.to_digit(16)) {
|
||||
v = v * 16.0 + f64::from(d);
|
||||
digits += 1;
|
||||
self.bump();
|
||||
}
|
||||
if digits == 0 {
|
||||
return Err(Problem::at(start, "a hexadecimal number needs digits after `0x`"));
|
||||
}
|
||||
if self.peek().is_some_and(ident_part) {
|
||||
return Err(Problem::at(self.pos(), "a number can't run straight into a name"));
|
||||
}
|
||||
return Ok(v);
|
||||
}
|
||||
while self.peek().is_some_and(|c| c.is_ascii_digit()) {
|
||||
self.bump();
|
||||
}
|
||||
if self.peek() == Some('.') && self.peek2().is_none_or(|c| c != '.') {
|
||||
self.bump();
|
||||
while self.peek().is_some_and(|c| c.is_ascii_digit()) {
|
||||
self.bump();
|
||||
}
|
||||
}
|
||||
if matches!(self.peek(), Some('e' | 'E')) {
|
||||
let save = (self.at, self.line, self.col);
|
||||
self.bump();
|
||||
if matches!(self.peek(), Some('+' | '-')) {
|
||||
self.bump();
|
||||
}
|
||||
if !self.peek().is_some_and(|c| c.is_ascii_digit()) {
|
||||
(self.at, self.line, self.col) = save;
|
||||
return Err(Problem::at(self.pos(), "a number's exponent needs digits"));
|
||||
}
|
||||
while self.peek().is_some_and(|c| c.is_ascii_digit()) {
|
||||
self.bump();
|
||||
}
|
||||
}
|
||||
if self.peek().is_some_and(ident_part) {
|
||||
return Err(Problem::at(self.pos(), "a number can't run straight into a name"));
|
||||
}
|
||||
let text = self.src.get(from..self.at).unwrap_or("0");
|
||||
text.parse::<f64>().map_err(|_| Problem::at(start, "this isn't a number"))
|
||||
}
|
||||
|
||||
fn string(&mut self, quote: char, start: Pos) -> Result<String, Problem> {
|
||||
self.bump();
|
||||
let mut s = String::new();
|
||||
loop {
|
||||
let here = self.pos();
|
||||
match self.bump() {
|
||||
None | Some('\n' | '\r' | '\u{2028}' | '\u{2029}') => return Err(Problem::at(start, "this string is never closed (its quote is missing on this line)")),
|
||||
Some(c) if c == quote => return Ok(s),
|
||||
Some('\\') => match self.bump() {
|
||||
None => return Err(Problem::at(start, "this string is never closed")),
|
||||
Some('n') => s.push('\n'),
|
||||
Some('t') => s.push('\t'),
|
||||
Some('r') => s.push('\r'),
|
||||
Some('b') => s.push('\u{8}'),
|
||||
Some('f') => s.push('\u{c}'),
|
||||
Some('v') => s.push('\u{b}'),
|
||||
Some('0') if !self.peek().is_some_and(|c| c.is_ascii_digit()) => s.push('\0'),
|
||||
Some('x') => s.push(self.hex(2, here)?),
|
||||
Some('u') => s.push(self.hex(4, here)?),
|
||||
// A backslash before a line break continues the string on the next line.
|
||||
Some('\n' | '\u{2028}' | '\u{2029}') => {}
|
||||
Some('\r') => {
|
||||
if self.peek() == Some('\n') {
|
||||
self.bump();
|
||||
}
|
||||
}
|
||||
Some(c) => s.push(c),
|
||||
},
|
||||
Some(c) => s.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(&mut self, n: usize, at: Pos) -> Result<char, Problem> {
|
||||
let mut v = 0u32;
|
||||
for _ in 0..n {
|
||||
let d = self.peek().and_then(|c| c.to_digit(16)).ok_or_else(|| Problem::at(at, "this escape needs hexadecimal digits"))?;
|
||||
v = v * 16 + d;
|
||||
self.bump();
|
||||
}
|
||||
char::from_u32(v).ok_or_else(|| Problem::at(at, "this escape isn't a character"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The tokens of `src`, ending with [`Tok::Eof`].
|
||||
pub fn tokens(src: &str) -> Result<Vec<Token>, Problem> {
|
||||
let mut lx = Lexer { src, at: 0, line: 1, col: 1 };
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let nl = lx.skip()?;
|
||||
let pos = lx.pos();
|
||||
if out.len() >= MAX_TOKENS {
|
||||
return Err(Problem::at(pos, format!("the script is longer than {MAX_TOKENS} tokens")));
|
||||
}
|
||||
let Some(c) = lx.peek() else {
|
||||
out.push(Token { tok: Tok::Eof, pos, nl: true });
|
||||
return Ok(out);
|
||||
};
|
||||
let tok = if ident_start(c) {
|
||||
let from = lx.at;
|
||||
while lx.peek().is_some_and(ident_part) {
|
||||
lx.bump();
|
||||
}
|
||||
Tok::Name(src.get(from..lx.at).unwrap_or_default().to_string())
|
||||
} else if c.is_ascii_digit() || (c == '.' && lx.peek2().is_some_and(|d| d.is_ascii_digit())) {
|
||||
Tok::Num(lx.number(pos)?)
|
||||
} else if c == '"' || c == '\'' {
|
||||
Tok::Str(lx.string(c, pos)?)
|
||||
} else {
|
||||
let rest = src.get(lx.at..).unwrap_or_default();
|
||||
let Some(p) = PUNCTS.iter().find(|p| rest.starts_with(**p)) else {
|
||||
return Err(Problem::at(pos, format!("unexpected character {c:?}")));
|
||||
};
|
||||
for _ in 0..p.chars().count() {
|
||||
lx.bump();
|
||||
}
|
||||
Tok::Punct(p)
|
||||
};
|
||||
out.push(Token { tok, pos, nl });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! Lowering: the syntax tree to the action IR. It accepts only what it can say exactly in the
|
||||
//! IR and reports everything else where it is, so a script either runs whole or not at all.
|
||||
|
||||
use super::parse::{E, Expr, Func, S, Stmt};
|
||||
use super::{Compiled, Listener, MAX_INLINE_DEPTH, MAX_LISTENERS, MAX_PROBLEMS, Pos, Problem, ScriptOp};
|
||||
use crate::{Action, ButtonEvent, FrameRef, MAX_ACTIONS, MAX_FRAME, MAX_LABEL_CHARS, MAX_TRACE_CHARS, Property, Target, valid_instance_name};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The timeline methods a script may call (on this timeline or on a named instance).
|
||||
const METHODS: [&str; 8] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene"];
|
||||
/// Names a script's own function can't take: they would hide the timeline's methods.
|
||||
const BUILTINS: [&str; 11] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene", "trace", "addEventListener", "removeEventListener"];
|
||||
/// Calls that would reach outside the movie: ignored, and noted.
|
||||
const OUTSIDE: [&str; 4] = ["navigateToURL", "sendToURL", "fscommand", "fsCommand"];
|
||||
/// Type casts that leave an instance path as it is (`MovieClip(parent)`).
|
||||
const CASTS: [&str; 7] = ["MovieClip", "Object", "Sprite", "DisplayObject", "DisplayObjectContainer", "InteractiveObject", "SimpleButton"];
|
||||
|
||||
/// A constant value, as ActionScript computes it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Val {
|
||||
Num(f64),
|
||||
Str(String),
|
||||
Bool(bool),
|
||||
Null,
|
||||
Undefined,
|
||||
}
|
||||
|
||||
impl Val {
|
||||
fn number(&self) -> f64 {
|
||||
match self {
|
||||
Val::Num(n) => *n,
|
||||
Val::Bool(b) => f64::from(u8::from(*b)),
|
||||
Val::Null => 0.0,
|
||||
Val::Undefined => f64::NAN,
|
||||
Val::Str(s) => {
|
||||
// ECMA-262 §9.3.1: a decimal number with optional sign and exponent (Rust would
|
||||
// also read "inf" and "nan").
|
||||
let t = s.trim();
|
||||
match t.trim_start_matches(['+', '-']) {
|
||||
"" if t.is_empty() => 0.0,
|
||||
"Infinity" => if t.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY },
|
||||
u if u.chars().all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-')) => t.parse().unwrap_or(f64::NAN),
|
||||
_ => f64::NAN,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
match self {
|
||||
Val::Num(n) => number_text(*n),
|
||||
Val::Str(s) => s.clone(),
|
||||
Val::Bool(b) => b.to_string(),
|
||||
Val::Null => "null".into(),
|
||||
Val::Undefined => "undefined".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A number as ActionScript writes it (`Number.toString()`, ECMA-262 §9.8.1): integers without
|
||||
/// a point, exponents outside 1e-6 … 1e21.
|
||||
pub(super) fn number_text(n: f64) -> String {
|
||||
if n.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
if n.is_infinite() {
|
||||
return if n > 0.0 { "Infinity".into() } else { "-Infinity".into() };
|
||||
}
|
||||
if n == 0.0 {
|
||||
return "0".into();
|
||||
}
|
||||
let a = n.abs();
|
||||
if (1e-6..1e21).contains(&a) {
|
||||
return format!("{n}");
|
||||
}
|
||||
let s = format!("{n:e}");
|
||||
match s.split_once('e') {
|
||||
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
|
||||
_ => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where lowering is.
|
||||
#[derive(Clone, Default)]
|
||||
struct Cx {
|
||||
/// Inside a listener's function: its event parameter and the instance it listens on (what
|
||||
/// `e.currentTarget` is).
|
||||
event: Option<(String, Vec<String>)>,
|
||||
/// Inside a listener (or a function it calls): listeners can't be added there yet.
|
||||
in_listener: bool,
|
||||
/// Inside a function body (functions can't be declared there).
|
||||
in_function: bool,
|
||||
/// The parameters of the function being lowered (they can't be read).
|
||||
params: Vec<String>,
|
||||
/// The script's functions being lowered, innermost last (to refuse recursion).
|
||||
stack: Vec<String>,
|
||||
}
|
||||
|
||||
struct Lower<'a> {
|
||||
funcs: BTreeMap<&'a str, &'a Func>,
|
||||
problems: Vec<Problem>,
|
||||
notes: Vec<Problem>,
|
||||
listeners: usize,
|
||||
/// Statements lowered so far, counting each inlined copy (calls can fan out).
|
||||
work: usize,
|
||||
}
|
||||
|
||||
/// Most statements lowered for one script, inlined copies included.
|
||||
const MAX_WORK: usize = 100_000;
|
||||
|
||||
/// Whether the statement list ended in a `return`.
|
||||
type Returned = bool;
|
||||
|
||||
impl<'a> Lower<'a> {
|
||||
fn problem(&mut self, pos: Pos, msg: impl Into<String>) {
|
||||
if self.problems.len() < MAX_PROBLEMS * 4 {
|
||||
self.problems.push(Problem::at(pos, msg));
|
||||
}
|
||||
}
|
||||
|
||||
fn note(&mut self, pos: Pos, msg: impl Into<String>) {
|
||||
if self.notes.len() < MAX_PROBLEMS * 4 {
|
||||
self.notes.push(Problem::at(pos, msg));
|
||||
}
|
||||
}
|
||||
|
||||
fn stmts(&mut self, list: &'a [Stmt], cx: &Cx, out: &mut Vec<ScriptOp>) -> Returned {
|
||||
for s in list {
|
||||
if self.stmt(s, cx, out) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn stmt(&mut self, s: &'a Stmt, cx: &Cx, out: &mut Vec<ScriptOp>) -> Returned {
|
||||
self.work += 1;
|
||||
if self.work > MAX_WORK {
|
||||
if self.work == MAX_WORK + 1 {
|
||||
self.problem(s.pos, format!("the script's functions call each other into more than {MAX_WORK} statements"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
match &s.kind {
|
||||
S::Empty | S::Import => {}
|
||||
// Declared functions run where they are called or listened for.
|
||||
S::Function(_) => {
|
||||
if cx.in_function {
|
||||
self.problem(s.pos, "functions declared inside functions aren't supported yet");
|
||||
}
|
||||
}
|
||||
S::Block(b) => return self.stmts(b, cx, out),
|
||||
S::Var(w) => self.problem(s.pos, format!("variables (`{w}`) aren't supported yet")),
|
||||
S::If(..) => self.problem(s.pos, "`if` statements aren't supported yet"),
|
||||
S::Other(w, _) => {
|
||||
let what = match *w {
|
||||
"for" | "while" | "do" => format!("`{w}` loops aren't supported yet"),
|
||||
_ => format!("`{w}` statements aren't supported yet"),
|
||||
};
|
||||
self.problem(s.pos, what);
|
||||
}
|
||||
S::Return(None) => return true,
|
||||
S::Return(Some(e)) => {
|
||||
if self.constant(e, cx).is_err() {
|
||||
self.problem(e.pos, "returning a value isn't supported");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
S::Expr(e) => self.expr_stmt(e, cx, out),
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn expr_stmt(&mut self, e: &'a Expr, cx: &Cx, out: &mut Vec<ScriptOp>) {
|
||||
match &e.kind {
|
||||
E::Call(callee, args) => self.call(e.pos, callee, args, cx, out),
|
||||
E::Assign("=", lhs, rhs) => self.assign(e.pos, lhs, rhs, cx, out),
|
||||
E::Assign(op, _, _) => self.problem(e.pos, format!("`{op}` reads a value first; only `=` with a value is supported")),
|
||||
E::Comma(list) => {
|
||||
for x in list {
|
||||
self.expr_stmt(x, cx, out);
|
||||
}
|
||||
}
|
||||
// A literal alone does nothing (`"use strict"`).
|
||||
E::Num(_) | E::Str(_) | E::Bool(_) | E::Null => {}
|
||||
E::Unary("++" | "--", _) | E::Postfix(..) => self.problem(e.pos, "`++` and `--` read a value first and aren't supported"),
|
||||
_ => self.problem(e.pos, "only calls (such as `stop()`) and settings (such as `hero_mc.x = 10`) run as statements"),
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], cx: &Cx, out: &mut Vec<ScriptOp>) {
|
||||
match &callee.kind {
|
||||
E::Name(n) => {
|
||||
let n = n.as_str();
|
||||
if let Some(f) = self.funcs.get(n).copied() {
|
||||
return self.inline(pos, f, args, cx, out);
|
||||
}
|
||||
match n {
|
||||
"trace" => self.trace(pos, args, cx, out),
|
||||
"addEventListener" => self.listen(pos, Vec::new(), args, cx, out),
|
||||
n if METHODS.contains(&n) => self.method(pos, Vec::new(), n, args, cx, out),
|
||||
n if OUTSIDE.contains(&n) => self.note(pos, format!("`{n}` is ignored: a movie here can't open web pages or reach outside itself")),
|
||||
"removeEventListener" => self.problem(pos, "removing listeners isn't supported yet"),
|
||||
n if CASTS.contains(&n) => self.problem(pos, format!("`{n}(…)` alone does nothing; call a method on it, as in `{n}(parent).play()`")),
|
||||
n => self.problem(pos, format!("`{n}` isn't declared in this frame script (functions from other frames, and the rest of the language, aren't supported yet)")),
|
||||
}
|
||||
}
|
||||
E::Member(obj, m) => {
|
||||
let m = m.as_str();
|
||||
if OUTSIDE.contains(&m) || (matches!(&obj.kind, E::Name(o) if o == "ExternalInterface") && matches!(m, "call" | "addCallback")) {
|
||||
return self.note(pos, format!("`{m}` is ignored: a movie here can't open web pages or reach outside itself"));
|
||||
}
|
||||
let known = METHODS.contains(&m) || m == "addEventListener";
|
||||
if !known {
|
||||
let msg = if m == "removeEventListener" { "removing listeners isn't supported yet".to_string() } else { format!("calling `{m}` isn't supported (timeline methods such as `play()` and `gotoAndStop()`, and `addEventListener`, are)") };
|
||||
return self.problem(pos, msg);
|
||||
}
|
||||
let Some(t) = self.target(obj, cx) else { return };
|
||||
if m == "addEventListener" { self.listen(pos, t, args, cx, out) } else { self.method(pos, t, m, args, cx, out) }
|
||||
}
|
||||
_ => self.problem(pos, "only named functions and methods can be called"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A call to one of the script's own functions: its body runs in place.
|
||||
fn inline(&mut self, pos: Pos, f: &'a Func, args: &'a [Expr], cx: &Cx, out: &mut Vec<ScriptOp>) {
|
||||
let name = f.name.clone().unwrap_or_default();
|
||||
if cx.stack.contains(&name) {
|
||||
return self.problem(pos, format!("`{name}` calls itself; recursion isn't supported"));
|
||||
}
|
||||
if cx.stack.len() >= MAX_INLINE_DEPTH {
|
||||
return self.problem(pos, format!("functions call each other more than {MAX_INLINE_DEPTH} deep"));
|
||||
}
|
||||
// Arguments are passed but never read (a parameter read is reported in the body).
|
||||
for a in args {
|
||||
let passes_event = matches!((&a.kind, &cx.event), (E::Name(n), Some((e, _))) if n == e);
|
||||
if !passes_event && self.constant(a, cx).is_err() {
|
||||
self.problem(a.pos, "arguments are values or the event; computing them isn't supported");
|
||||
}
|
||||
}
|
||||
if args.len() < f.params.iter().filter(|p| !p.default && !p.rest).count() {
|
||||
return self.problem(pos, format!("`{name}` needs more arguments than this call passes"));
|
||||
}
|
||||
let mut inner = Cx { event: None, in_listener: cx.in_listener, in_function: true, params: f.params.iter().map(|p| p.name.clone()).collect(), stack: cx.stack.clone() };
|
||||
inner.stack.push(name);
|
||||
self.stmts(&f.body, &inner, out);
|
||||
}
|
||||
|
||||
fn trace(&mut self, pos: Pos, args: &'a [Expr], cx: &Cx, out: &mut Vec<ScriptOp>) {
|
||||
let mut parts = Vec::new();
|
||||
for a in args {
|
||||
match self.constant(a, cx) {
|
||||
Ok(v) => parts.push(v.text()),
|
||||
Err(p) => return self.problems.push(p),
|
||||
}
|
||||
}
|
||||
let message = parts.join(" ");
|
||||
if message.chars().count() > MAX_TRACE_CHARS {
|
||||
return self.problem(pos, format!("a trace message is at most {MAX_TRACE_CHARS} characters"));
|
||||
}
|
||||
out.push(ScriptOp::Action(Action::Trace { message }));
|
||||
}
|
||||
|
||||
/// A timeline method on the instance at `path`.
|
||||
fn method(&mut self, pos: Pos, path: Vec<String>, m: &str, args: &'a [Expr], cx: &Cx, out: &mut Vec<ScriptOp>) {
|
||||
let Some(target) = self.path(pos, &path) else { return };
|
||||
let none = |l: &mut Self| {
|
||||
if args.is_empty() {
|
||||
true
|
||||
} else {
|
||||
l.problem(pos, format!("`{m}()` takes no arguments"));
|
||||
false
|
||||
}
|
||||
};
|
||||
let action = match m {
|
||||
"stop" if none(self) => Action::Stop { target },
|
||||
"play" if none(self) => Action::Play { target },
|
||||
"nextFrame" if none(self) => Action::NextFrame { target },
|
||||
"prevFrame" if none(self) => Action::PrevFrame { target },
|
||||
"nextScene" | "prevScene" => {
|
||||
if !none(self) {
|
||||
return;
|
||||
}
|
||||
// Scenes belong to the main timeline; on this timeline the player checks that
|
||||
// it is the main one (a movie clip has no other scenes).
|
||||
if !target.is_this() {
|
||||
return self.problem(pos, format!("call `{m}()` in the main timeline's own script: scenes belong to the main timeline"));
|
||||
}
|
||||
if m == "nextScene" { Action::NextScene } else { Action::PrevScene }
|
||||
}
|
||||
"gotoAndPlay" | "gotoAndStop" => {
|
||||
let (Some(f), true) = (args.first(), args.len() <= 2) else {
|
||||
return self.problem(pos, format!("`{m}` takes a frame, and optionally a scene"));
|
||||
};
|
||||
let frame = match self.constant(f, cx) {
|
||||
Ok(Val::Num(n)) if n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(&n) => FrameRef::Number(n as u32 - 1),
|
||||
Ok(Val::Num(_)) => return self.problem(f.pos, format!("a frame number is a whole number from 1 to {}", u64::from(MAX_FRAME) + 1)),
|
||||
Ok(Val::Str(s)) if label_ok(&s) => FrameRef::Label(s),
|
||||
Ok(Val::Str(_)) => return self.problem(f.pos, format!("a frame label is 1 to {MAX_LABEL_CHARS} printable characters")),
|
||||
Ok(_) => return self.problem(f.pos, "the frame is a number or a label"),
|
||||
Err(p) => return self.problems.push(p),
|
||||
};
|
||||
let scene = match args.get(1).map(|s| (s.pos, self.constant(s, cx))) {
|
||||
None | Some((_, Ok(Val::Null | Val::Undefined))) => None,
|
||||
Some((_, Ok(Val::Str(s)))) if label_ok(&s) => Some(s),
|
||||
Some((p, Ok(_))) => return self.problem(p, "the scene is its name, as a string"),
|
||||
Some((_, Err(p))) => return self.problems.push(p),
|
||||
};
|
||||
if m == "gotoAndPlay" { Action::GotoAndPlay { target, frame, scene } } else { Action::GotoAndStop { target, frame, scene } }
|
||||
}
|
||||
_ => return,
|
||||
};
|
||||
out.push(ScriptOp::Action(action));
|
||||
}
|
||||
|
||||
/// `target.addEventListener(event, function)`.
|
||||
fn listen(&mut self, pos: Pos, path: Vec<String>, args: &'a [Expr], cx: &Cx, out: &mut Vec<ScriptOp>) {
|
||||
if cx.in_listener {
|
||||
return self.problem(pos, "adding a listener from inside a listener isn't supported yet");
|
||||
}
|
||||
let Some(target) = self.path(pos, &path) else { return };
|
||||
let (Some(ev), Some(handler), true) = (args.first(), args.get(1), args.len() <= 5) else {
|
||||
return self.problem(pos, "`addEventListener` takes an event and a function");
|
||||
};
|
||||
let Some(event) = self.event(ev) else { return };
|
||||
if let Some(c) = args.get(2)
|
||||
&& !matches!(self.constant(c, cx), Ok(Val::Bool(false) | Val::Null | Val::Undefined))
|
||||
{
|
||||
return self.problem(c.pos, "capture-phase listeners (`useCapture`) aren't supported");
|
||||
}
|
||||
for extra in args.iter().skip(3) {
|
||||
if self.constant(extra, cx).is_err() {
|
||||
return self.problem(extra.pos, "listener priority and weak references are values");
|
||||
}
|
||||
}
|
||||
let (f, function) = match &handler.kind {
|
||||
E::Name(n) => match self.funcs.get(n.as_str()).copied() {
|
||||
Some(f) => (f, n.clone()),
|
||||
None => return self.problem(handler.pos, format!("`{n}` isn't a function declared in this frame script")),
|
||||
},
|
||||
E::Function(f) => (&**f, format!("function at line {}", f.pos.line)),
|
||||
_ => return self.problem(handler.pos, "the listener is a function declared in this frame script, or written in place"),
|
||||
};
|
||||
// The event is passed to the function: it takes exactly one argument.
|
||||
let required = f.params.iter().filter(|p| !p.default && !p.rest).count();
|
||||
let Some(first) = f.params.first().filter(|_| required <= 1) else {
|
||||
return self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`");
|
||||
};
|
||||
if cx.stack.contains(&function) {
|
||||
return self.problem(pos, format!("`{function}` adds itself as a listener; recursion isn't supported"));
|
||||
}
|
||||
if self.listeners >= MAX_LISTENERS {
|
||||
return self.problem(pos, format!("a frame script adds at most {MAX_LISTENERS} listeners"));
|
||||
}
|
||||
self.listeners += 1;
|
||||
let mut inner = Cx { event: Some((first.name.clone(), path)), in_listener: true, in_function: true, params: f.params.iter().map(|p| p.name.clone()).collect(), stack: cx.stack.clone() };
|
||||
inner.stack.push(function.clone());
|
||||
let mut body = Vec::new();
|
||||
self.stmts(&f.body, &inner, &mut body);
|
||||
let actions: Vec<Action> = body
|
||||
.into_iter()
|
||||
.filter_map(|op| match op {
|
||||
ScriptOp::Action(a) => Some(a),
|
||||
ScriptOp::Listen(_) => None,
|
||||
})
|
||||
.collect();
|
||||
if actions.len() > MAX_ACTIONS {
|
||||
return self.problem(f.pos, format!("a listener runs at most {MAX_ACTIONS} actions"));
|
||||
}
|
||||
out.push(ScriptOp::Listen(Listener { target, event, function, actions: Arc::new(actions) }));
|
||||
}
|
||||
|
||||
/// The mouse event an `addEventListener` names.
|
||||
fn event(&mut self, e: &Expr) -> Option<ButtonEvent> {
|
||||
let (pos, name, constant) = match &e.kind {
|
||||
E::Member(o, k) if matches!(&o.kind, E::Name(c) if c == "MouseEvent" || c == "Event" || c.ends_with("Event")) => {
|
||||
let class = if let E::Name(c) = &o.kind { c.as_str() } else { "" };
|
||||
(e.pos, format!("{class}.{k}"), if class == "MouseEvent" { k.as_str() } else { "" })
|
||||
}
|
||||
E::Str(s) => (e.pos, format!("\"{s}\""), match s.as_str() {
|
||||
"click" => "CLICK",
|
||||
"mouseDown" => "MOUSE_DOWN",
|
||||
"mouseUp" => "MOUSE_UP",
|
||||
"rollOver" => "ROLL_OVER",
|
||||
"rollOut" => "ROLL_OUT",
|
||||
"mouseOver" => "MOUSE_OVER",
|
||||
"mouseOut" => "MOUSE_OUT",
|
||||
_ => "",
|
||||
}),
|
||||
_ => {
|
||||
self.problem(e.pos, "the event is a constant such as `MouseEvent.CLICK`");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let ev = match constant {
|
||||
"CLICK" => ButtonEvent::Click,
|
||||
"MOUSE_DOWN" => ButtonEvent::Press,
|
||||
"MOUSE_UP" => ButtonEvent::Release,
|
||||
"ROLL_OVER" | "MOUSE_OVER" => ButtonEvent::Over,
|
||||
"ROLL_OUT" | "MOUSE_OUT" => ButtonEvent::Out,
|
||||
_ => {
|
||||
self.problem(pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT are)"));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some(ev)
|
||||
}
|
||||
|
||||
/// `x = value` on this timeline or `path.x = value`.
|
||||
fn assign(&mut self, pos: Pos, lhs: &'a Expr, rhs: &'a Expr, cx: &Cx, out: &mut Vec<ScriptOp>) {
|
||||
let (obj, prop) = match &lhs.kind {
|
||||
E::Member(o, p) => (Some(&**o), p.as_str()),
|
||||
E::Name(n) => (None, n.as_str()),
|
||||
_ => return self.problem(pos, "only instance properties can be set"),
|
||||
};
|
||||
let property = match prop {
|
||||
"x" => Property::X,
|
||||
"y" => Property::Y,
|
||||
"alpha" => Property::Alpha,
|
||||
"visible" => Property::Visible,
|
||||
"rotation" => Property::Rotation,
|
||||
"scaleX" => Property::ScaleX,
|
||||
"scaleY" => Property::ScaleY,
|
||||
"buttonMode" | "useHandCursor" => return self.note(pos, format!("`{prop}` is ignored: the pointer is a hand over everything clickable here")),
|
||||
p if obj.is_none() => return self.problem(pos, format!("setting `{p}` isn't supported: variables don't run yet")),
|
||||
p => return self.problem(pos, format!("setting `{p}` isn't supported yet (x, y, alpha, visible, rotation, scaleX and scaleY are)")),
|
||||
};
|
||||
let path = match obj {
|
||||
Some(o) => match self.target(o, cx) {
|
||||
Some(t) => t,
|
||||
None => return,
|
||||
},
|
||||
None => Vec::new(),
|
||||
};
|
||||
let Some(target) = self.path(pos, &path) else { return };
|
||||
let value = match self.constant(rhs, cx) {
|
||||
Ok(v @ (Val::Num(_) | Val::Bool(_))) => v.number(),
|
||||
Ok(_) => return self.problem(rhs.pos, format!("`{prop}` is set to a number{}", if property == Property::Visible { " or true or false" } else { "" })),
|
||||
Err(p) => return self.problems.push(p),
|
||||
};
|
||||
if !value.is_finite() {
|
||||
return self.problem(rhs.pos, "the value must be a finite number");
|
||||
}
|
||||
out.push(ScriptOp::Action(Action::SetProperty { target, property, value }));
|
||||
}
|
||||
|
||||
/// An instance path as names (`root`, `parent` and instance names), relative to the
|
||||
/// script's timeline; `None` after reporting why it isn't one.
|
||||
fn target(&mut self, e: &Expr, cx: &Cx) -> Option<Vec<String>> {
|
||||
let mut path = match &e.kind {
|
||||
E::This => Vec::new(),
|
||||
E::Name(n) if n == "root" || n == "parent" => vec![n.clone()],
|
||||
E::Name(n) if n == "stage" => {
|
||||
self.problem(e.pos, "the stage isn't supported as a target");
|
||||
return None;
|
||||
}
|
||||
E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => {
|
||||
self.problem(e.pos, format!("the event `{n}` isn't an instance; `{n}.currentTarget` is the one listened to"));
|
||||
return None;
|
||||
}
|
||||
E::Name(n) if cx.params.contains(n) => {
|
||||
self.problem(e.pos, format!("reading the parameter `{n}` isn't supported"));
|
||||
return None;
|
||||
}
|
||||
E::Name(n) => vec![n.clone()],
|
||||
E::Member(o, m) if m == "currentTarget" && matches!((&o.kind, &cx.event), (E::Name(n), Some((p, _))) if n == p) => cx.event.as_ref().map(|(_, t)| t.clone()).unwrap_or_default(),
|
||||
E::Member(o, m) if m == "target" && matches!((&o.kind, &cx.event), (E::Name(n), Some((p, _))) if n == p) => {
|
||||
self.problem(e.pos, "`target` can be a part inside the instance; use `currentTarget`, the instance listened to");
|
||||
return None;
|
||||
}
|
||||
E::Member(o, m) => {
|
||||
let mut p = self.target(o, cx)?;
|
||||
p.push(m.clone());
|
||||
p
|
||||
}
|
||||
E::Call(f, args) if matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1 => return args.first().and_then(|a| self.target(a, cx)),
|
||||
E::Binary("as", x, _) => return self.target(x, cx),
|
||||
_ => {
|
||||
self.problem(e.pos, "this isn't an instance (a name path such as `hero_mc.arm_mc`, `parent` or `root`)");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// Every instance's `root` is the main timeline.
|
||||
if let Some(i) = path.iter().rposition(|s| s == "root") {
|
||||
path.drain(..i);
|
||||
}
|
||||
Some(path)
|
||||
}
|
||||
|
||||
/// The IR target for a path, checked.
|
||||
fn path(&mut self, pos: Pos, path: &[String]) -> Option<Target> {
|
||||
for s in path {
|
||||
if !matches!(s.as_str(), "root" | "parent") && !valid_instance_name(s) {
|
||||
self.problem(pos, format!("`{s}` isn't an instance name AniCraft can address (1-64 letters, digits, `_` or `$`)"));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let t = Target::new(path.join("."));
|
||||
match t.segments() {
|
||||
Ok(_) => Some(t),
|
||||
Err(e) => {
|
||||
self.problem(pos, e);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A value computed from literals (`"Score: " + 10`, `-5`, `0.5`).
|
||||
fn constant(&self, e: &Expr, cx: &Cx) -> Result<Val, Problem> {
|
||||
Ok(match &e.kind {
|
||||
E::Num(n) => Val::Num(*n),
|
||||
E::Str(s) => Val::Str(s.clone()),
|
||||
E::Bool(b) => Val::Bool(*b),
|
||||
E::Null => Val::Null,
|
||||
E::Name(n) if n == "undefined" => Val::Undefined,
|
||||
E::Name(n) if n == "NaN" => Val::Num(f64::NAN),
|
||||
E::Name(n) if n == "Infinity" => Val::Num(f64::INFINITY),
|
||||
E::Unary("-", x) => Val::Num(-self.constant(x, cx)?.number()),
|
||||
E::Unary("+", x) => Val::Num(self.constant(x, cx)?.number()),
|
||||
E::Unary("!", x) => Val::Bool(!truthy(&self.constant(x, cx)?)),
|
||||
E::Binary(op @ ("+" | "-" | "*" | "/" | "%"), a, b) => {
|
||||
let (a, b) = (self.constant(a, cx)?, self.constant(b, cx)?);
|
||||
match *op {
|
||||
"+" if matches!(a, Val::Str(_)) || matches!(b, Val::Str(_)) => {
|
||||
let s = a.text() + &b.text();
|
||||
if s.len() > MAX_TRACE_CHARS * 4 {
|
||||
return Err(Problem::at(e.pos, "this text is too long"));
|
||||
}
|
||||
Val::Str(s)
|
||||
}
|
||||
"+" => Val::Num(a.number() + b.number()),
|
||||
"-" => Val::Num(a.number() - b.number()),
|
||||
"*" => Val::Num(a.number() * b.number()),
|
||||
"/" => Val::Num(a.number() / b.number()),
|
||||
_ => Val::Num(a.number() % b.number()),
|
||||
}
|
||||
}
|
||||
E::Name(n) => {
|
||||
let msg = if cx.event.as_ref().is_some_and(|(p, _)| p == n) { format!("reading the event `{n}` isn't supported") } else { format!("reading `{n}` isn't supported: only values written out (numbers, strings, true, false) and `+` of them are") };
|
||||
return Err(Problem::at(e.pos, msg));
|
||||
}
|
||||
E::Member(..) => {
|
||||
let mut root = e;
|
||||
while let E::Member(o, _) = &root.kind {
|
||||
root = o;
|
||||
}
|
||||
let msg = match &root.kind {
|
||||
E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => format!("reading the event `{n}` isn't supported"),
|
||||
_ => "reading properties isn't supported: only values written out (numbers, strings, true, false) and `+` of them are".into(),
|
||||
};
|
||||
return Err(Problem::at(e.pos, msg));
|
||||
}
|
||||
_ => return Err(Problem::at(e.pos, "only values written out (numbers, strings, true, false) and `+` of them are supported here")),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn truthy(v: &Val) -> bool {
|
||||
match v {
|
||||
Val::Num(n) => *n != 0.0 && !n.is_nan(),
|
||||
Val::Str(s) => !s.is_empty(),
|
||||
Val::Bool(b) => *b,
|
||||
Val::Null | Val::Undefined => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn label_ok(s: &str) -> bool {
|
||||
let n = s.chars().count();
|
||||
(1..=MAX_LABEL_CHARS).contains(&n) && !s.chars().any(char::is_control) && s.chars().any(|c| !c.is_whitespace())
|
||||
}
|
||||
|
||||
/// The statements' top-level function declarations (also those in plain blocks, which
|
||||
/// ActionScript hoists too).
|
||||
fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, problems: &mut Vec<Problem>) {
|
||||
for s in list {
|
||||
match &s.kind {
|
||||
S::Function(f) => {
|
||||
let Some(n) = f.name.as_deref() else { continue };
|
||||
if BUILTINS.contains(&n) || CASTS.contains(&n) {
|
||||
problems.push(Problem::at(s.pos, format!("a function named `{n}` would hide ActionScript's own `{n}`")));
|
||||
} else if funcs.insert(n, f).is_some() {
|
||||
problems.push(Problem::at(s.pos, format!("`{n}` is declared twice")));
|
||||
}
|
||||
}
|
||||
S::Block(b) => declare(b, funcs, problems),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn lower(prog: &[Stmt]) -> Result<Compiled, Vec<Problem>> {
|
||||
let mut funcs = BTreeMap::new();
|
||||
let mut problems = Vec::new();
|
||||
declare(prog, &mut funcs, &mut problems);
|
||||
let mut l = Lower { funcs, problems, notes: Vec::new(), listeners: 0, work: 0 };
|
||||
let mut ops = Vec::new();
|
||||
l.stmts(prog, &Cx::default(), &mut ops);
|
||||
if ops.len() > MAX_ACTIONS {
|
||||
l.problems.push(Problem::whole(format!("a frame script runs at most {MAX_ACTIONS} steps")));
|
||||
}
|
||||
let tidy = |mut v: Vec<Problem>| {
|
||||
v.sort();
|
||||
v.dedup();
|
||||
v.truncate(MAX_PROBLEMS);
|
||||
v
|
||||
};
|
||||
if l.problems.is_empty() { Ok(Compiled { ops, notes: tidy(l.notes) }) } else { Err(tidy(l.problems)) }
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The ActionScript 3.0 timeline subset (ADR 0013 tier 2): a hand-written lexer and
|
||||
//! recursive-descent parser, and a lowering to the action IR.
|
||||
//!
|
||||
//! What runs is what most Animate frame scripts do: `stop()`, `play()`, `gotoAndPlay` and
|
||||
//! `gotoAndStop` by frame number or label (and scene), `nextFrame()`, `prevFrame()`,
|
||||
//! `nextScene()` and `prevScene()`, on this timeline or on instance-name paths
|
||||
//! (`hero_mc.gotoAndStop("run")`, `MovieClip(this.parent).play()`); mouse listeners
|
||||
//! (`btn.addEventListener(MouseEvent.CLICK, onClick)` with `function onClick(e:MouseEvent):void
|
||||
//! { … }` made of those calls, or an inline function); `trace` of literals and their `+`; and
|
||||
//! setting `x`, `y`, `alpha`, `visible`, `rotation`, `scaleX` and `scaleY` on named instances to
|
||||
//! values. A function declared in the script and called from it runs in place.
|
||||
//!
|
||||
//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all:
|
||||
//! nothing is ever half-run. Calls that would reach outside the movie (`navigateToURL`,
|
||||
//! `fscommand`, `ExternalInterface`) are ignored and listed as notes.
|
||||
//!
|
||||
//! Learned from the ECMAScript 3rd edition standard (ECMA-262) and Adobe's public ActionScript
|
||||
//! 3.0 language reference; no Adobe code. Everything is bounded: source length, token count,
|
||||
//! nesting depth, inlining depth, actions, listeners and problems.
|
||||
|
||||
mod lex;
|
||||
mod lower;
|
||||
mod parse;
|
||||
|
||||
use crate::{Action, ButtonEvent, Target};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Longest script that runs, in bytes (far more than frame scripts written by hand).
|
||||
pub const MAX_RUN_BYTES: usize = 256 * 1024;
|
||||
/// Most tokens in a script that runs.
|
||||
pub const MAX_TOKENS: usize = 65_536;
|
||||
/// Deepest nesting of statements and expressions.
|
||||
pub const MAX_DEPTH: usize = 64;
|
||||
/// Deepest chain of calls to the script's own functions.
|
||||
pub const MAX_INLINE_DEPTH: usize = 16;
|
||||
/// Most listeners one script adds.
|
||||
pub const MAX_LISTENERS: usize = 64;
|
||||
/// Most problems reported for one script.
|
||||
pub const MAX_PROBLEMS: usize = 32;
|
||||
|
||||
/// A place in the script: 1-based line and column (in characters; a tab is one).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct Pos {
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
}
|
||||
|
||||
/// Why a script doesn't run (or, as a note, what in it is ignored). `line` and `column` are 0
|
||||
/// when it is about the whole script.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct Problem {
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl Problem {
|
||||
pub fn at(pos: Pos, message: impl Into<String>) -> Problem {
|
||||
Problem { line: pos.line, column: pos.column, message: message.into() }
|
||||
}
|
||||
pub fn whole(message: impl Into<String>) -> Problem {
|
||||
Problem { line: 0, column: 0, message: message.into() }
|
||||
}
|
||||
pub fn pos(&self) -> Option<Pos> {
|
||||
(self.line > 0).then_some(Pos { line: self.line, column: self.column })
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Problem {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if self.line > 0 { write!(f, "line {}, column {}: {}", self.line, self.column, self.message) } else { f.write_str(&self.message) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A mouse listener a script adds: when `event` happens on `target` (a button or movie clip,
|
||||
/// named from the script's timeline), `actions` run on the script's timeline.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Listener {
|
||||
#[serde(default, skip_serializing_if = "Target::is_this")]
|
||||
pub target: Target,
|
||||
pub event: ButtonEvent,
|
||||
/// The function's name (`function at line 7` for an inline one): adding the same function
|
||||
/// for the same event again changes nothing, as in ActionScript.
|
||||
pub function: String,
|
||||
pub actions: Arc<Vec<Action>>,
|
||||
}
|
||||
|
||||
impl Listener {
|
||||
pub fn describe(&self) -> String {
|
||||
let body = if self.actions.is_empty() { "nothing".to_string() } else { self.actions.iter().map(Action::describe).collect::<Vec<_>>().join("; ") };
|
||||
format!("On {} ({}): {body}", self.event.key(), self.target)
|
||||
}
|
||||
}
|
||||
|
||||
/// One step of a script, in source order.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ScriptOp {
|
||||
Action(Action),
|
||||
Listen(Listener),
|
||||
}
|
||||
|
||||
impl ScriptOp {
|
||||
pub fn describe(&self) -> String {
|
||||
match self {
|
||||
ScriptOp::Action(a) => a.describe(),
|
||||
ScriptOp::Listen(l) => l.describe(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A script that runs: its steps, and what in it is ignored.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Compiled {
|
||||
pub ops: Vec<ScriptOp>,
|
||||
/// Calls that are ignored (they would reach outside the movie, or do nothing here).
|
||||
pub notes: Vec<Problem>,
|
||||
}
|
||||
|
||||
/// Compiles ActionScript 3.0 source to the action IR, or says why it doesn't run (the
|
||||
/// problems sorted by position, at most [`MAX_PROBLEMS`]).
|
||||
pub fn compile(src: &str) -> Result<Compiled, Vec<Problem>> {
|
||||
if src.len() > MAX_RUN_BYTES {
|
||||
return Err(vec![Problem::whole(format!("the script is longer than {} KiB, the most that runs", MAX_RUN_BYTES / 1024))]);
|
||||
}
|
||||
let toks = lex::tokens(src).map_err(|p| vec![p])?;
|
||||
let prog = parse::parse(&toks).map_err(|p| vec![p])?;
|
||||
lower::lower(&prog)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,736 @@
|
||||
//! The parser: tokens to a syntax tree, by recursive descent (the grammar of ECMA-262 3rd
|
||||
//! edition §11–14, with ActionScript 3.0's type annotations, `import`, `as`, `is`, rest
|
||||
//! parameters and `for each`). It reads more of the language than AniCraft runs, so lowering
|
||||
//! can say exactly which construct isn't run and where; what it reads but never runs (loop
|
||||
//! headers, `switch` and `try` bodies) is skipped by balanced brackets. Bounded: nesting
|
||||
//! deeper than [`super::MAX_DEPTH`] is a problem, not a stack overflow.
|
||||
|
||||
use super::lex::{Tok, Token};
|
||||
use super::{MAX_DEPTH, Pos, Problem};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Expr {
|
||||
pub pos: Pos,
|
||||
pub kind: E,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum E {
|
||||
Num(f64),
|
||||
Str(String),
|
||||
Bool(bool),
|
||||
Null,
|
||||
This,
|
||||
Name(String),
|
||||
/// `a.b`
|
||||
Member(Box<Expr>, String),
|
||||
/// `a[b]`
|
||||
Index(Box<Expr>, Box<Expr>),
|
||||
Call(Box<Expr>, Vec<Expr>),
|
||||
New(Box<Expr>, Vec<Expr>),
|
||||
/// A prefix operator (`!`, `-`, `typeof`, `++`, …).
|
||||
Unary(&'static str, Box<Expr>),
|
||||
/// `x++`, `x--`
|
||||
Postfix(&'static str, Box<Expr>),
|
||||
Binary(&'static str, Box<Expr>, Box<Expr>),
|
||||
/// `=`, `+=`, …
|
||||
Assign(&'static str, Box<Expr>, Box<Expr>),
|
||||
Cond(Box<Expr>, Box<Expr>, Box<Expr>),
|
||||
Function(Box<Func>),
|
||||
Array(Vec<Expr>),
|
||||
Object(Vec<(String, Expr)>),
|
||||
/// `a, b`
|
||||
Comma(Vec<Expr>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Param {
|
||||
pub name: String,
|
||||
pub pos: Pos,
|
||||
pub default: bool,
|
||||
pub rest: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Func {
|
||||
pub name: Option<String>,
|
||||
pub pos: Pos,
|
||||
pub params: Vec<Param>,
|
||||
pub body: Vec<Stmt>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Stmt {
|
||||
pub pos: Pos,
|
||||
pub kind: S,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum S {
|
||||
Expr(Expr),
|
||||
Import,
|
||||
Function(Func),
|
||||
/// `var`, `const`.
|
||||
Var(&'static str),
|
||||
If(Expr, Vec<Stmt>, Vec<Stmt>),
|
||||
Return(Option<Expr>),
|
||||
Block(Vec<Stmt>),
|
||||
Empty,
|
||||
/// A statement the parser reads but lowering never runs, by its keyword (`for`, `while`,
|
||||
/// `switch`, …), with the statements inside it.
|
||||
Other(&'static str, Vec<Stmt>),
|
||||
}
|
||||
|
||||
/// Words that can't name a variable or function (ActionScript 3.0's reserved words).
|
||||
const RESERVED: [&str; 46] = [
|
||||
"as", "break", "case", "catch", "class", "const", "continue", "default", "delete", "do", "else", "extends", "false", "finally", "for", "function", "if", "implements", "import", "in", "instanceof", "interface", "internal", "is", "native", "new", "null", "package", "private", "protected", "public", "return", "super", "switch", "this", "throw", "to", "true", "try", "typeof", "use", "var", "void", "while", "with", "include",
|
||||
];
|
||||
|
||||
/// Attribute words that may stand before a declaration in a frame script.
|
||||
const ATTRIBUTES: [&str; 9] = ["public", "private", "protected", "internal", "static", "override", "final", "dynamic", "native"];
|
||||
|
||||
pub fn reserved(s: &str) -> bool {
|
||||
RESERVED.contains(&s)
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
toks: &'a [Token],
|
||||
i: usize,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
type R<T> = Result<T, Problem>;
|
||||
|
||||
/// What a token reads as in a message.
|
||||
fn shown(t: &Tok) -> String {
|
||||
match t {
|
||||
Tok::Name(n) => format!("`{n}`"),
|
||||
Tok::Num(_) => "a number".into(),
|
||||
Tok::Str(_) => "a string".into(),
|
||||
Tok::Punct(p) => format!("`{p}`"),
|
||||
Tok::Eof => "the end of the script".into(),
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
fn tok(&self) -> &'a Tok {
|
||||
self.toks.get(self.i).map_or(&Tok::Eof, |t| &t.tok)
|
||||
}
|
||||
|
||||
fn tok_at(&self, k: usize) -> &'a Tok {
|
||||
self.toks.get(self.i + k).map_or(&Tok::Eof, |t| &t.tok)
|
||||
}
|
||||
|
||||
fn pos(&self) -> Pos {
|
||||
self.toks.get(self.i).or(self.toks.last()).map_or(Pos { line: 1, column: 1 }, |t| t.pos)
|
||||
}
|
||||
|
||||
fn nl(&self) -> bool {
|
||||
self.toks.get(self.i).is_none_or(|t| t.nl)
|
||||
}
|
||||
|
||||
fn next(&mut self) -> &'a Tok {
|
||||
let t = self.tok();
|
||||
if self.i < self.toks.len() {
|
||||
self.i += 1;
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
fn is(&self, p: &str) -> bool {
|
||||
matches!(self.tok(), Tok::Punct(q) if *q == p)
|
||||
}
|
||||
|
||||
fn is_word(&self, w: &str) -> bool {
|
||||
matches!(self.tok(), Tok::Name(n) if n == w)
|
||||
}
|
||||
|
||||
fn eat(&mut self, p: &str) -> bool {
|
||||
if self.is(p) {
|
||||
self.i += 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn eat_word(&mut self, w: &str) -> bool {
|
||||
if self.is_word(w) {
|
||||
self.i += 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn expect(&mut self, p: &str, what: &str) -> R<()> {
|
||||
if self.eat(p) { Ok(()) } else { Err(self.unexpected(&format!("`{p}` {what}"))) }
|
||||
}
|
||||
|
||||
fn unexpected(&self, wanted: &str) -> Problem {
|
||||
Problem::at(self.pos(), format!("expected {wanted}, found {}", shown(self.tok())))
|
||||
}
|
||||
|
||||
/// Enters one level of nesting.
|
||||
fn deeper(&mut self) -> R<()> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH { Err(Problem::at(self.pos(), format!("the code is nested more than {MAX_DEPTH} levels deep"))) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn name(&mut self, what: &str) -> R<(String, Pos)> {
|
||||
let pos = self.pos();
|
||||
match self.tok() {
|
||||
Tok::Name(n) if !reserved(n) => {
|
||||
self.i += 1;
|
||||
Ok((n.clone(), pos))
|
||||
}
|
||||
_ => Err(self.unexpected(what)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a statement: `;`, or a line break, `}` or the end (semicolon insertion).
|
||||
fn end(&mut self) -> R<()> {
|
||||
if self.eat(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(self.unexpected("`;` or a new line"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Skips a balanced `( … )`, `[ … ]` or `{ … }` starting at the current token.
|
||||
fn skip_group(&mut self) -> R<()> {
|
||||
let start = self.pos();
|
||||
let mut stack: Vec<&str> = Vec::new();
|
||||
loop {
|
||||
match self.next() {
|
||||
Tok::Punct(p @ ("(" | "[" | "{")) => {
|
||||
stack.push(match *p {
|
||||
"(" => ")",
|
||||
"[" => "]",
|
||||
_ => "}",
|
||||
});
|
||||
if stack.len() > MAX_DEPTH {
|
||||
return Err(Problem::at(start, format!("the code is nested more than {MAX_DEPTH} levels deep")));
|
||||
}
|
||||
}
|
||||
Tok::Punct(p @ (")" | "]" | "}")) => {
|
||||
if stack.pop() != Some(*p) {
|
||||
return Err(Problem::at(self.toks.get(self.i.saturating_sub(1)).map_or(start, |t| t.pos), format!("`{p}` doesn't match an opening bracket")));
|
||||
}
|
||||
if stack.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Tok::Eof => return Err(Problem::at(start, "this bracket is never closed")),
|
||||
_ if stack.is_empty() => return Err(Problem::at(start, "expected a bracket")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `: Type` (read and dropped: `*`, `void`, `a.b.C`, `Vector.<T>`).
|
||||
fn annotation(&mut self) -> R<()> {
|
||||
if !self.eat(":") {
|
||||
return Ok(());
|
||||
}
|
||||
self.type_name()
|
||||
}
|
||||
|
||||
fn type_name(&mut self) -> R<()> {
|
||||
if self.eat("*") || self.eat_word("void") {
|
||||
return Ok(());
|
||||
}
|
||||
self.name("a type")?;
|
||||
loop {
|
||||
if self.eat(".<") {
|
||||
self.deeper()?;
|
||||
self.type_name()?;
|
||||
self.depth -= 1;
|
||||
// `>>` closes two generics at once.
|
||||
if !self.eat(">") {
|
||||
return Err(self.unexpected("`>` to close the type"));
|
||||
}
|
||||
} else if self.eat(".") {
|
||||
self.name("a type")?;
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn program(&mut self) -> R<Vec<Stmt>> {
|
||||
let mut out = Vec::new();
|
||||
while !matches!(self.tok(), Tok::Eof) {
|
||||
out.push(self.statement()?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn block(&mut self) -> R<Vec<Stmt>> {
|
||||
self.expect("{", "to open the block")?;
|
||||
let mut out = Vec::new();
|
||||
while !self.eat("}") {
|
||||
if matches!(self.tok(), Tok::Eof) {
|
||||
return Err(self.unexpected("`}` to close the block"));
|
||||
}
|
||||
out.push(self.statement()?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A statement as a body (`if (…) stmt`): a block's statements, or one statement.
|
||||
fn body(&mut self) -> R<Vec<Stmt>> {
|
||||
if self.is("{") {
|
||||
let pos = self.pos();
|
||||
let b = self.block()?;
|
||||
Ok(vec![Stmt { pos, kind: S::Block(b) }])
|
||||
} else {
|
||||
Ok(vec![self.statement()?])
|
||||
}
|
||||
}
|
||||
|
||||
fn statement(&mut self) -> R<Stmt> {
|
||||
self.deeper()?;
|
||||
let s = self.statement_inner();
|
||||
self.depth -= 1;
|
||||
s
|
||||
}
|
||||
|
||||
fn statement_inner(&mut self) -> R<Stmt> {
|
||||
let pos = self.pos();
|
||||
let kind = match self.tok() {
|
||||
Tok::Punct(";") => {
|
||||
self.i += 1;
|
||||
S::Empty
|
||||
}
|
||||
Tok::Punct("{") => S::Block(self.block()?),
|
||||
Tok::Name(w) => match w.as_str() {
|
||||
"import" => {
|
||||
self.i += 1;
|
||||
self.name("a package name after `import`")?;
|
||||
while self.eat(".") {
|
||||
if !self.eat("*") {
|
||||
self.name("a name")?;
|
||||
}
|
||||
}
|
||||
self.end()?;
|
||||
S::Import
|
||||
}
|
||||
"function" if matches!(self.tok_at(1), Tok::Name(_)) => {
|
||||
self.i += 1;
|
||||
S::Function(self.function(pos, true)?)
|
||||
}
|
||||
"var" | "const" => {
|
||||
let w = if w == "var" { "var" } else { "const" };
|
||||
self.i += 1;
|
||||
loop {
|
||||
self.name("a variable name")?;
|
||||
self.annotation()?;
|
||||
if self.eat("=") {
|
||||
self.assign()?;
|
||||
}
|
||||
if !self.eat(",") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.end()?;
|
||||
S::Var(w)
|
||||
}
|
||||
"if" => {
|
||||
self.i += 1;
|
||||
self.expect("(", "after `if`")?;
|
||||
let c = self.expr()?;
|
||||
self.expect(")", "after the condition")?;
|
||||
let then = self.body()?;
|
||||
let other = if self.eat_word("else") { self.body()? } else { Vec::new() };
|
||||
S::If(c, then, other)
|
||||
}
|
||||
"return" => {
|
||||
self.i += 1;
|
||||
let e = if self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl() { None } else { Some(self.expr()?) };
|
||||
self.end()?;
|
||||
S::Return(e)
|
||||
}
|
||||
"for" => {
|
||||
self.i += 1;
|
||||
self.eat_word("each");
|
||||
self.skip_group()?;
|
||||
S::Other("for", self.body()?)
|
||||
}
|
||||
"while" => {
|
||||
self.i += 1;
|
||||
self.skip_group()?;
|
||||
S::Other("while", self.body()?)
|
||||
}
|
||||
"do" => {
|
||||
self.i += 1;
|
||||
let b = self.body()?;
|
||||
if !self.eat_word("while") {
|
||||
return Err(self.unexpected("`while` after the `do` body"));
|
||||
}
|
||||
self.skip_group()?;
|
||||
self.end()?;
|
||||
S::Other("do", b)
|
||||
}
|
||||
"with" => {
|
||||
self.i += 1;
|
||||
self.skip_group()?;
|
||||
S::Other("with", self.body()?)
|
||||
}
|
||||
"switch" => {
|
||||
self.i += 1;
|
||||
self.skip_group()?;
|
||||
self.skip_group()?;
|
||||
S::Other("switch", Vec::new())
|
||||
}
|
||||
"try" => {
|
||||
self.i += 1;
|
||||
let mut inner = self.block()?;
|
||||
let mut any = false;
|
||||
while self.eat_word("catch") {
|
||||
any = true;
|
||||
self.skip_group()?;
|
||||
inner.extend(self.block()?);
|
||||
}
|
||||
if self.eat_word("finally") {
|
||||
any = true;
|
||||
inner.extend(self.block()?);
|
||||
}
|
||||
if !any {
|
||||
return Err(self.unexpected("`catch` or `finally` after the `try` block"));
|
||||
}
|
||||
S::Other("try", inner)
|
||||
}
|
||||
"break" | "continue" | "throw" => {
|
||||
let w = match w.as_str() {
|
||||
"break" => "break",
|
||||
"continue" => "continue",
|
||||
_ => "throw",
|
||||
};
|
||||
self.i += 1;
|
||||
if !(self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl()) {
|
||||
self.expr()?;
|
||||
}
|
||||
self.end()?;
|
||||
S::Other(w, Vec::new())
|
||||
}
|
||||
// Applications, not timeline scripts (ADR 0013 tier 3).
|
||||
"package" | "class" | "interface" | "namespace" | "use" | "include" | "default" => {
|
||||
let w = w.clone();
|
||||
return Err(Problem::at(pos, format!("`{w}` belongs to class files and isn't supported in frame scripts")));
|
||||
}
|
||||
a if ATTRIBUTES.contains(&a) && matches!(self.tok_at(1), Tok::Name(_)) => {
|
||||
let a = a.to_string();
|
||||
return Err(Problem::at(pos, format!("`{a}` declarations belong to classes and aren't supported in frame scripts")));
|
||||
}
|
||||
_ => {
|
||||
let e = self.expr()?;
|
||||
if self.is(":") {
|
||||
return Err(Problem::at(pos, "statement labels aren't supported"));
|
||||
}
|
||||
self.end()?;
|
||||
S::Expr(e)
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
let e = self.expr()?;
|
||||
self.end()?;
|
||||
S::Expr(e)
|
||||
}
|
||||
};
|
||||
Ok(Stmt { pos, kind })
|
||||
}
|
||||
|
||||
/// After `function`: an optional name, the parameters, the result type and the body.
|
||||
fn function(&mut self, pos: Pos, named: bool) -> R<Func> {
|
||||
let name = if named || matches!(self.tok(), Tok::Name(n) if !reserved(n)) { Some(self.name("a function name")?.0) } else { None };
|
||||
// Getters and setters are class members.
|
||||
if matches!(name.as_deref(), Some("get" | "set")) && matches!(self.tok(), Tok::Name(_)) {
|
||||
return Err(Problem::at(pos, "getters and setters belong to classes and aren't supported in frame scripts"));
|
||||
}
|
||||
self.expect("(", "to open the parameter list")?;
|
||||
let mut params = Vec::new();
|
||||
if !self.eat(")") {
|
||||
loop {
|
||||
let rest = self.eat("...");
|
||||
let (n, p) = self.name("a parameter name")?;
|
||||
self.annotation()?;
|
||||
let default = self.eat("=");
|
||||
if default {
|
||||
self.assign()?;
|
||||
}
|
||||
params.push(Param { name: n, pos: p, default, rest });
|
||||
if self.eat(")") {
|
||||
break;
|
||||
}
|
||||
self.expect(",", "or `)` after the parameter")?;
|
||||
}
|
||||
}
|
||||
self.annotation()?;
|
||||
let body = self.block()?;
|
||||
Ok(Func { name, pos, params, body })
|
||||
}
|
||||
|
||||
/// An expression (`a, b` included).
|
||||
fn expr(&mut self) -> R<Expr> {
|
||||
let first = self.assign()?;
|
||||
if !self.is(",") {
|
||||
return Ok(first);
|
||||
}
|
||||
let pos = first.pos;
|
||||
let mut list = vec![first];
|
||||
while self.eat(",") {
|
||||
list.push(self.assign()?);
|
||||
}
|
||||
Ok(Expr { pos, kind: E::Comma(list) })
|
||||
}
|
||||
|
||||
fn assign(&mut self) -> R<Expr> {
|
||||
self.deeper()?;
|
||||
let r = self.assign_inner();
|
||||
self.depth -= 1;
|
||||
r
|
||||
}
|
||||
|
||||
fn assign_inner(&mut self) -> R<Expr> {
|
||||
let lhs = self.conditional()?;
|
||||
let op = match self.tok() {
|
||||
Tok::Punct(p @ ("=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "&=" | "|=" | "^=" | "&&=" | "||=")) => *p,
|
||||
_ => return Ok(lhs),
|
||||
};
|
||||
let pos = self.pos();
|
||||
if !matches!(lhs.kind, E::Name(_) | E::Member(..) | E::Index(..)) {
|
||||
return Err(Problem::at(pos, "the left side of this assignment can't be assigned to"));
|
||||
}
|
||||
self.i += 1;
|
||||
let rhs = self.assign()?;
|
||||
Ok(Expr { pos: lhs.pos, kind: E::Assign(op, Box::new(lhs), Box::new(rhs)) })
|
||||
}
|
||||
|
||||
fn conditional(&mut self) -> R<Expr> {
|
||||
let c = self.binary(0)?;
|
||||
if !self.eat("?") {
|
||||
return Ok(c);
|
||||
}
|
||||
let a = self.assign()?;
|
||||
self.expect(":", "in the `? :` expression")?;
|
||||
let b = self.assign()?;
|
||||
Ok(Expr { pos: c.pos, kind: E::Cond(Box::new(c), Box::new(a), Box::new(b)) })
|
||||
}
|
||||
|
||||
/// Binary operators by precedence level (0 = `||`, loosest).
|
||||
fn binary(&mut self, level: usize) -> R<Expr> {
|
||||
const LEVELS: [&[&str]; 10] = [
|
||||
&["||"],
|
||||
&["&&"],
|
||||
&["|"],
|
||||
&["^"],
|
||||
&["&"],
|
||||
&["==", "!=", "===", "!=="],
|
||||
&["<", ">", "<=", ">=", "instanceof", "is", "as", "in"],
|
||||
&["<<", ">>", ">>>"],
|
||||
&["+", "-"],
|
||||
&["*", "/", "%"],
|
||||
];
|
||||
let Some(ops) = LEVELS.get(level) else { return self.unary() };
|
||||
let mut lhs = self.binary(level + 1)?;
|
||||
loop {
|
||||
let op = match self.tok() {
|
||||
Tok::Punct(p) if ops.contains(p) => ops.iter().find(|o| *o == p).copied(),
|
||||
Tok::Name(n) if ops.contains(&n.as_str()) => ops.iter().find(|o| **o == n.as_str()).copied(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(op) = op else { return Ok(lhs) };
|
||||
self.i += 1;
|
||||
// The right side of `as` and `is` is a type.
|
||||
let rhs = if matches!(op, "as" | "is") {
|
||||
let pos = self.pos();
|
||||
let start = self.i;
|
||||
self.type_name()?;
|
||||
let name = match self.toks.get(start..self.i) {
|
||||
Some([Token { tok: Tok::Name(n), .. }]) => n.clone(),
|
||||
_ => "*".into(),
|
||||
};
|
||||
Expr { pos, kind: E::Name(name) }
|
||||
} else {
|
||||
self.binary(level + 1)?
|
||||
};
|
||||
lhs = Expr { pos: lhs.pos, kind: E::Binary(op, Box::new(lhs), Box::new(rhs)) };
|
||||
}
|
||||
}
|
||||
|
||||
fn unary(&mut self) -> R<Expr> {
|
||||
self.deeper()?;
|
||||
let r = self.unary_inner();
|
||||
self.depth -= 1;
|
||||
r
|
||||
}
|
||||
|
||||
fn unary_inner(&mut self) -> R<Expr> {
|
||||
let pos = self.pos();
|
||||
let op = match self.tok() {
|
||||
Tok::Punct(p @ ("!" | "~" | "-" | "+" | "++" | "--")) => Some(*p),
|
||||
Tok::Name(n) if matches!(n.as_str(), "typeof" | "void" | "delete") => Some(match n.as_str() {
|
||||
"typeof" => "typeof",
|
||||
"void" => "void",
|
||||
_ => "delete",
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(op) = op {
|
||||
self.i += 1;
|
||||
let e = self.unary()?;
|
||||
return Ok(Expr { pos, kind: E::Unary(op, Box::new(e)) });
|
||||
}
|
||||
let e = self.postfix()?;
|
||||
if !self.nl()
|
||||
&& let Tok::Punct(p @ ("++" | "--")) = self.tok()
|
||||
{
|
||||
self.i += 1;
|
||||
return Ok(Expr { pos, kind: E::Postfix(p, Box::new(e)) });
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
|
||||
/// A primary expression with its member accesses, indexes and calls.
|
||||
fn postfix(&mut self) -> R<Expr> {
|
||||
let mut e = if self.is_word("new") { self.new_expr()? } else { self.primary()? };
|
||||
loop {
|
||||
let pos = self.pos();
|
||||
if self.eat(".") {
|
||||
let n = match self.next() {
|
||||
// Any word can follow a dot (`e.default` is a property).
|
||||
Tok::Name(n) => n.clone(),
|
||||
Tok::Punct("(") => {
|
||||
return Err(Problem::at(pos, "XML filters aren't supported"));
|
||||
}
|
||||
t => return Err(Problem::at(pos, format!("expected a property name after `.`, found {}", shown(t)))),
|
||||
};
|
||||
e = Expr { pos: e.pos, kind: E::Member(Box::new(e), n) };
|
||||
} else if self.is("..") || self.is("::") || self.is(".<") {
|
||||
let what = match self.next() {
|
||||
Tok::Punct("..") => "XML descendant access (`..`)",
|
||||
Tok::Punct("::") => "namespace-qualified names (`::`)",
|
||||
_ => "typed vectors (`Vector.<T>`)",
|
||||
};
|
||||
return Err(Problem::at(pos, format!("{what} isn't supported")));
|
||||
} else if self.is("[") {
|
||||
self.i += 1;
|
||||
let ix = self.expr()?;
|
||||
self.expect("]", "to close the index")?;
|
||||
e = Expr { pos: e.pos, kind: E::Index(Box::new(e), Box::new(ix)) };
|
||||
} else if self.is("(") {
|
||||
let args = self.arguments()?;
|
||||
e = Expr { pos: e.pos, kind: E::Call(Box::new(e), args) };
|
||||
} else {
|
||||
return Ok(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn new_expr(&mut self) -> R<Expr> {
|
||||
let pos = self.pos();
|
||||
self.i += 1;
|
||||
self.deeper()?;
|
||||
// `new X.Y(args)`: the constructor is a name path (or another `new`).
|
||||
let mut callee = if self.is_word("new") { self.new_expr()? } else { self.primary()? };
|
||||
while self.eat(".") {
|
||||
let (n, _) = match self.tok() {
|
||||
Tok::Name(n) => (n.clone(), self.pos()),
|
||||
_ => return Err(self.unexpected("a name after `.`")),
|
||||
};
|
||||
self.i += 1;
|
||||
callee = Expr { pos: callee.pos, kind: E::Member(Box::new(callee), n) };
|
||||
}
|
||||
if self.is(".<") {
|
||||
return Err(Problem::at(self.pos(), "typed vectors (`Vector.<T>`) aren't supported"));
|
||||
}
|
||||
let args = if self.is("(") { self.arguments()? } else { Vec::new() };
|
||||
self.depth -= 1;
|
||||
Ok(Expr { pos, kind: E::New(Box::new(callee), args) })
|
||||
}
|
||||
|
||||
fn arguments(&mut self) -> R<Vec<Expr>> {
|
||||
self.expect("(", "")?;
|
||||
let mut args = Vec::new();
|
||||
if self.eat(")") {
|
||||
return Ok(args);
|
||||
}
|
||||
loop {
|
||||
if self.eat("...") {
|
||||
return Err(Problem::at(self.pos(), "spreading arguments (`...`) isn't supported"));
|
||||
}
|
||||
args.push(self.assign()?);
|
||||
if self.eat(")") {
|
||||
return Ok(args);
|
||||
}
|
||||
self.expect(",", "or `)` after the argument")?;
|
||||
}
|
||||
}
|
||||
|
||||
fn primary(&mut self) -> R<Expr> {
|
||||
let pos = self.pos();
|
||||
let kind = match self.next() {
|
||||
Tok::Num(n) => E::Num(*n),
|
||||
Tok::Str(s) => E::Str(s.clone()),
|
||||
Tok::Name(n) => match n.as_str() {
|
||||
"true" => E::Bool(true),
|
||||
"false" => E::Bool(false),
|
||||
"null" => E::Null,
|
||||
"this" => E::This,
|
||||
"function" => E::Function(Box::new(self.function(pos, false)?)),
|
||||
"super" => return Err(Problem::at(pos, "`super` belongs to classes and isn't supported in frame scripts")),
|
||||
w if reserved(w) => return Err(Problem::at(pos, format!("expected an expression, found `{w}`"))),
|
||||
_ => E::Name(n.clone()),
|
||||
},
|
||||
Tok::Punct("(") => {
|
||||
let e = self.expr()?;
|
||||
self.expect(")", "to close the parenthesis")?;
|
||||
// Parentheses only group; the inner expression keeps its own position.
|
||||
return Ok(e);
|
||||
}
|
||||
Tok::Punct("[") => {
|
||||
let mut items = Vec::new();
|
||||
while !self.eat("]") {
|
||||
if self.eat(",") {
|
||||
continue;
|
||||
}
|
||||
items.push(self.assign()?);
|
||||
if !self.is("]") {
|
||||
self.expect(",", "or `]` in the array")?;
|
||||
}
|
||||
}
|
||||
E::Array(items)
|
||||
}
|
||||
Tok::Punct("{") => {
|
||||
let mut fields = Vec::new();
|
||||
while !self.eat("}") {
|
||||
let key = match self.next() {
|
||||
Tok::Name(n) => n.clone(),
|
||||
Tok::Str(s) => s.clone(),
|
||||
Tok::Num(n) => format!("{n}"),
|
||||
_ => return Err(Problem::at(self.pos(), "expected a field name in the object")),
|
||||
};
|
||||
self.expect(":", "after the field name")?;
|
||||
fields.push((key, self.assign()?));
|
||||
if !self.is("}") {
|
||||
self.expect(",", "or `}` in the object")?;
|
||||
}
|
||||
}
|
||||
E::Object(fields)
|
||||
}
|
||||
Tok::Punct("/" | "/=") => return Err(Problem::at(pos, "regular expressions aren't supported")),
|
||||
Tok::Punct("<") => return Err(Problem::at(pos, "XML literals aren't supported")),
|
||||
t => {
|
||||
self.i = self.i.saturating_sub(1);
|
||||
return Err(Problem::at(pos, format!("expected an expression, found {}", shown(t))));
|
||||
}
|
||||
};
|
||||
Ok(Expr { pos, kind })
|
||||
}
|
||||
}
|
||||
|
||||
/// The statements of a script.
|
||||
pub fn parse(toks: &[Token]) -> Result<Vec<Stmt>, Problem> {
|
||||
Parser { toks, i: 0, depth: 0 }.program()
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
use super::*;
|
||||
use crate::{Action, ButtonEvent, FrameRef, Property, Target};
|
||||
|
||||
fn ok(src: &str) -> Compiled {
|
||||
compile(src).unwrap_or_else(|p| panic!("{src:?} didn't compile: {p:?}"))
|
||||
}
|
||||
|
||||
fn actions(src: &str) -> Vec<Action> {
|
||||
ok(src)
|
||||
.ops
|
||||
.into_iter()
|
||||
.map(|o| match o {
|
||||
ScriptOp::Action(a) => a,
|
||||
ScriptOp::Listen(l) => panic!("unexpected listener {l:?}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The first problem: (line, column, message).
|
||||
fn err(src: &str) -> (u32, u32, String) {
|
||||
match compile(src) {
|
||||
Ok(c) => panic!("{src:?} compiled to {c:?}"),
|
||||
Err(p) => {
|
||||
let f = p.first().cloned().unwrap_or_else(|| Problem::whole("none"));
|
||||
(f.line, f.column, f.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn t(s: &str) -> Target {
|
||||
Target::new(s)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeline_calls_lower_to_actions() {
|
||||
let a = actions("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();");
|
||||
assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }, Action::NextFrame { target: t("") }, Action::PrevFrame { target: t("") }, Action::NextScene, Action::PrevScene]);
|
||||
// Frames are 1-based in ActionScript, 0-based in the IR; strings are labels.
|
||||
let a = actions(r#"gotoAndStop(1); gotoAndPlay("run"); gotoAndPlay(12, "Scene 2"); gotoAndStop('end', null); gotoAndStop(2 + 3);"#);
|
||||
assert_eq!(
|
||||
a,
|
||||
vec![
|
||||
Action::GotoAndStop { target: t(""), frame: FrameRef::Number(0), scene: None },
|
||||
Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("run".into()), scene: None },
|
||||
Action::GotoAndPlay { target: t(""), frame: FrameRef::Number(11), scene: Some("Scene 2".into()) },
|
||||
Action::GotoAndStop { target: t(""), frame: FrameRef::Label("end".into()), scene: None },
|
||||
Action::GotoAndStop { target: t(""), frame: FrameRef::Number(4), scene: None },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_paths_become_targets() {
|
||||
let a = actions("hero_mc.gotoAndStop(\"run\");\nthis.hero_mc.arm_mc.play();\nMovieClip(parent).stop();\nMovieClip(this.parent.parent).nextFrame();\nMovieClip(root).menu.play();\n(root as MovieClip).stop();\nhero_mc.root.stop();\nObject(parent).door.prevFrame();");
|
||||
let targets: Vec<String> = a.iter().map(|a| a.target().map(|t| t.0.clone()).unwrap_or_default()).collect();
|
||||
assert_eq!(targets, ["hero_mc", "hero_mc.arm_mc", "parent", "parent.parent", "root.menu", "root", "root", "parent.door"]);
|
||||
assert!(a.iter().all(|x| x.check().is_ok()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_are_set_to_values() {
|
||||
let a = actions("hero_mc.x = 100;\nhero_mc.y = -20.5;\nhero_mc.alpha = .5;\nhero_mc.visible = false;\ndoor.rotation = 45;\ndoor.scaleX = 2; door.scaleY = 1.5\nalpha = 0.25;");
|
||||
assert_eq!(
|
||||
a,
|
||||
vec![
|
||||
Action::SetProperty { target: t("hero_mc"), property: Property::X, value: 100.0 },
|
||||
Action::SetProperty { target: t("hero_mc"), property: Property::Y, value: -20.5 },
|
||||
Action::SetProperty { target: t("hero_mc"), property: Property::Alpha, value: 0.5 },
|
||||
Action::SetProperty { target: t("hero_mc"), property: Property::Visible, value: 0.0 },
|
||||
Action::SetProperty { target: t("door"), property: Property::Rotation, value: 45.0 },
|
||||
Action::SetProperty { target: t("door"), property: Property::ScaleX, value: 2.0 },
|
||||
Action::SetProperty { target: t("door"), property: Property::ScaleY, value: 1.5 },
|
||||
Action::SetProperty { target: t(""), property: Property::Alpha, value: 0.25 },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_writes_literals_and_their_sums_as_actionscript_does() {
|
||||
let msgs: Vec<String> = actions(r#"trace("hello"); trace('a' + 1 + 2); trace(1 + 2 + "a"); trace(0.1, true, null, undefined); trace(1e21, 1e-7, -0, 5 / 2, 7 % 4); trace(); trace("tab\there é \x41");"#)
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
Action::Trace { message } => message,
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(msgs, ["hello", "a12", "3a", "0.1 true null undefined", "1e+21 1e-7 0 2.5 3", "", "tab\there é A"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_lower_to_handlers_with_their_bodies() {
|
||||
let src = "import flash.events.MouseEvent;\n\nstop();\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(e:MouseEvent):void {\n\tgotoAndPlay(\"walk\"); // on\n\ttrace(\"go\");\n}\nmenu.btn.addEventListener(MouseEvent.ROLL_OVER, function (event:MouseEvent):void { MovieClip(event.currentTarget).gotoAndStop(2); });\naddEventListener(\"mouseDown\", onPlay);";
|
||||
let c = ok(src);
|
||||
assert_eq!(c.ops.len(), 4);
|
||||
assert_eq!(c.ops[0], ScriptOp::Action(Action::Stop { target: t("") }));
|
||||
let ScriptOp::Listen(l) = &c.ops[1] else { panic!("{:?}", c.ops[1]) };
|
||||
assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("play_btn", ButtonEvent::Click, "onPlay"));
|
||||
assert_eq!(*l.actions, vec![Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("walk".into()), scene: None }, Action::Trace { message: "go".into() }]);
|
||||
let ScriptOp::Listen(l) = &c.ops[2] else { panic!() };
|
||||
// `currentTarget` is the instance listened to, named from the script's timeline.
|
||||
assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("menu.btn", ButtonEvent::Over, "function at line 10"));
|
||||
assert_eq!(*l.actions, vec![Action::GotoAndStop { target: t("menu.btn"), frame: FrameRef::Number(1), scene: None }]);
|
||||
let ScriptOp::Listen(l) = &c.ops[3] else { panic!() };
|
||||
assert_eq!((l.target.is_this(), l.event), (true, ButtonEvent::Press));
|
||||
assert!(l.describe().starts_with("On press (this): Go to “walk” and play"), "{}", l.describe());
|
||||
for (k, e) in [("MOUSE_UP", ButtonEvent::Release), ("ROLL_OUT", ButtonEvent::Out), ("MOUSE_OVER", ButtonEvent::Over), ("MOUSE_OUT", ButtonEvent::Out)] {
|
||||
let c = ok(&format!("b.addEventListener(MouseEvent.{k}, f, false, 0, true); function f(e) {{}}"));
|
||||
assert!(matches!(&c.ops[0], ScriptOp::Listen(l) if l.event == e), "{k}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_functions_run_where_they_are_called() {
|
||||
let a = actions("function go(n:int = 1):void { gotoAndStop(3); return; trace(\"never\"); }\ngo();\nfunction twice() { go(); go(); }\ntwice();");
|
||||
assert_eq!(a.len(), 3, "{a:?}");
|
||||
assert!(a.iter().all(|x| matches!(x, Action::GotoAndStop { frame: FrameRef::Number(2), .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_outside_the_movie_are_ignored_and_noted() {
|
||||
let c = ok("navigateToURL(new URLRequest(\"https://example.com\"), \"_blank\");\nflash.net.navigateToURL(x);\nExternalInterface.call(\"f\");\nfscommand(\"quit\");\nbtn.buttonMode = true;\nstop();");
|
||||
assert_eq!(c.ops, vec![ScriptOp::Action(Action::Stop { target: t("") })]);
|
||||
let lines: Vec<u32> = c.notes.iter().map(|n| n.line).collect();
|
||||
assert_eq!(lines, [1, 2, 3, 4, 5]);
|
||||
assert!(c.notes[0].message.contains("navigateToURL") && c.notes[0].message.contains("ignored"), "{:?}", c.notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_white_space_and_semicolons_are_read_as_actionscript_does() {
|
||||
// Line and block comments, CR LF line ends, no semicolons, a BOM, empty statements.
|
||||
let a = actions("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\"");
|
||||
assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }]);
|
||||
assert_eq!(err("stop() play()"), (1, 8, "expected `;` or a new line, found `play`".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_problem_says_where_it_is() {
|
||||
let cases: &[(&str, u32, u32, &str)] = &[
|
||||
("stop();\nif (x) { play(); }", 2, 1, "`if` statements aren't supported yet"),
|
||||
("var n:int = 0;", 1, 1, "variables (`var`) aren't supported yet"),
|
||||
(" for (var i = 0; i < 3; i++) {}", 1, 3, "`for` loops aren't supported yet"),
|
||||
("while (true) stop();", 1, 1, "`while` loops aren't supported yet"),
|
||||
("switch (x) { case 1: stop(); }", 1, 1, "`switch` statements aren't supported yet"),
|
||||
("hero.x += 5;", 1, 1, "`+=` reads a value first"),
|
||||
("hero.width = 5;", 1, 1, "setting `width` isn't supported yet"),
|
||||
("score = 5;", 1, 1, "setting `score` isn't supported: variables"),
|
||||
("foo();", 1, 1, "`foo` isn't declared in this frame script"),
|
||||
("hero.addChild(x);", 1, 1, "calling `addChild` isn't supported"),
|
||||
("gotoAndStop(0);", 1, 13, "a frame number is a whole number from 1"),
|
||||
("gotoAndStop(1.5);", 1, 13, "a frame number is a whole number"),
|
||||
("gotoAndStop(frame);", 1, 13, "reading `frame` isn't supported"),
|
||||
("gotoAndStop();", 1, 1, "`gotoAndStop` takes a frame"),
|
||||
("stop(1);", 1, 1, "`stop()` takes no arguments"),
|
||||
("hero.nextScene();", 1, 1, "call `nextScene()` in the main timeline's own script"),
|
||||
("trace(hero.x);", 1, 7, "reading properties isn't supported"),
|
||||
("trace([1]);", 1, 7, "only values written out"),
|
||||
("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "the stage isn't supported"),
|
||||
("b.addEventListener(Event.ENTER_FRAME, f); function f(e) {}", 1, 20, "listening for Event.ENTER_FRAME isn't supported yet"),
|
||||
("b.addEventListener(MouseEvent.CLICK, nope);", 1, 38, "`nope` isn't a function declared"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f() { stop(); }", 1, 42, "a listener function takes the event"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f, true); function f(e) {}", 1, 41, "capture-phase listeners"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { trace(e.target.name); }", 1, 64, "reading the event `e`"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { e.target.play(); }", 1, 58, "`target` can be a part inside"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { c.addEventListener(MouseEvent.CLICK, f); }", 1, 58, "adding a listener from inside a listener"),
|
||||
("b.removeEventListener(MouseEvent.CLICK, f);", 1, 1, "removing listeners isn't supported yet"),
|
||||
("function f() { f(); } f();", 1, 16, "`f` calls itself"),
|
||||
("function stop() {}", 1, 1, "a function named `stop` would hide"),
|
||||
("function f() {} function f() {}", 1, 17, "`f` is declared twice"),
|
||||
("function f() { function g() {} } f();", 1, 16, "functions declared inside functions"),
|
||||
("function f(n) { n.play(); } f(1);", 1, 17, "reading the parameter `n`"),
|
||||
("hero_mc[\"arm\"].play();", 1, 1, "this isn't an instance"),
|
||||
("hero_mc.x = \"10\";", 1, 13, "`x` is set to a number"),
|
||||
("hero_mc.x = 1 / 0;", 1, 13, "the value must be a finite number"),
|
||||
("package { }", 1, 1, "`package` belongs to class files"),
|
||||
("class Hero {}", 1, 1, "`class` belongs to class files"),
|
||||
("public function f() {}", 1, 1, "`public` declarations belong to classes"),
|
||||
("stop(;", 1, 6, "expected an expression, found `;`"),
|
||||
("stop(", 1, 6, "expected an expression, found the end of the script"),
|
||||
("{ stop();", 1, 10, "expected `}` to close the block"),
|
||||
("trace(\"open);", 1, 7, "this string is never closed"),
|
||||
("/* never", 1, 1, "this comment is never closed"),
|
||||
("trace(3x);", 1, 8, "a number can't run straight into a name"),
|
||||
("stop(); #", 1, 9, "unexpected character '#'"),
|
||||
("var re = /ab+c/;", 1, 10, "regular expressions aren't supported"),
|
||||
("1 = 2;", 1, 3, "the left side of this assignment can't be assigned to"),
|
||||
("x++;", 1, 1, "`++` and `--` read a value first"),
|
||||
("é.play();", 1, 1, "`é` isn't an instance name AniCraft can address"),
|
||||
("\tstop();\n\t\tif (a) {}", 2, 3, "`if` statements"),
|
||||
];
|
||||
for (src, line, col, msg) in cases {
|
||||
let (l, c, m) = err(src);
|
||||
assert!(m.starts_with(msg) && (l, c) == (*line, *col), "{src:?}: got {l}:{c} {m:?}, want {line}:{col} {msg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_problem_is_listed_and_nothing_half_runs() {
|
||||
let p = compile("stop();\nvar a = 1;\nif (a) {}\nplay();\nhero.width = 3;").unwrap_err();
|
||||
let at: Vec<(u32, u32)> = p.iter().map(|p| (p.line, p.column)).collect();
|
||||
assert_eq!(at, [(2, 1), (3, 1), (5, 1)]);
|
||||
assert_eq!(p[0].to_string(), "line 2, column 1: variables (`var`) aren't supported yet");
|
||||
let many: String = (0..200).map(|i| format!("var v{i} = {i};\n")).collect();
|
||||
assert_eq!(compile(&many).unwrap_err().len(), MAX_PROBLEMS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_text_matches_actionscript() {
|
||||
for (n, s) in [(0.0, "0"), (-0.0, "0"), (5.0, "5"), (-3.25, "-3.25"), (0.1 + 0.2, "0.30000000000000004"), (1e21, "1e+21"), (1.5e-7, "1.5e-7"), (123456789012.0, "123456789012"), (f64::NAN, "NaN"), (f64::NEG_INFINITY, "-Infinity"), (0.000001, "0.000001")] {
|
||||
assert_eq!(lower::number_text(n), s, "{n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_are_problems_not_crashes() {
|
||||
let deep = format!("trace({}1{});", "(".repeat(10_000), ")".repeat(10_000));
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
let deep = format!("{}stop();{}", "{".repeat(10_000), "}".repeat(10_000));
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
let deep = format!("trace({}1);", "-".repeat(100_000));
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
let deep = format!("{}1;", "a = ".repeat(10_000));
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
let deep = format!("b.addEventListener(\"click\", {}", "function (e) { ".repeat(5_000));
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
let long = "stop();".repeat(MAX_RUN_BYTES / 7 + 1);
|
||||
assert!(err(&long).2.contains("longer than 256 KiB"));
|
||||
let tokens = ";".repeat(MAX_TOKENS + 1);
|
||||
assert!(err(&tokens).2.contains("tokens"));
|
||||
let steps = "stop();".repeat(crate::MAX_ACTIONS + 1);
|
||||
assert!(err(&steps).2.contains("at most 256 steps"));
|
||||
// Calls that fan out are bounded, however deep they could go.
|
||||
let mut src = String::from("function f0() { stop(); }\n");
|
||||
for i in 1..16 {
|
||||
src.push_str(&format!("function f{i}() {{ {} }}\n", format!("f{}(); ", i - 1).repeat(8)));
|
||||
}
|
||||
src.push_str("f15();");
|
||||
let t0 = std::time::Instant::now();
|
||||
assert!(compile(&src).is_err());
|
||||
assert!(t0.elapsed().as_secs_f32() < 5.0);
|
||||
}
|
||||
|
||||
/// A small deterministic generator (no clock, no randomness crate).
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
fn pick<'a>(&mut self, v: &[&'a str]) -> &'a str {
|
||||
v.get(self.next() as usize % v.len()).copied().unwrap_or("")
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_never_panics_and_ends_quickly() {
|
||||
const PIECES: [&str; 64] = [
|
||||
"stop", "play", "gotoAndStop", "(", ")", "{", "}", "[", "]", ";", ",", ".", "\n", " ", "\"a", "\"", "'", "\\", "/*", "*/", "//", "1", "0x", "1e", ".5", "e", "function", "f", "e:MouseEvent", ":void", "addEventListener", "MouseEvent.CLICK", "=", "+", "-", "!", "?", ":", "if", "else", "var", "for", "new", "this", "parent", "root", "MovieClip", "as", "trace", "x", "alpha", "é", "\u{0}", "\r", "\t", "<", ">", "...", "::", "..", ".<", "return", "import", "@",
|
||||
];
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let t0 = std::time::Instant::now();
|
||||
let mut compiled = 0;
|
||||
for _ in 0..4_000 {
|
||||
let n = rng.next() as usize % 80;
|
||||
let src: String = (0..n).map(|_| rng.pick(&PIECES)).collect();
|
||||
if compile(&src).is_ok() {
|
||||
compiled += 1;
|
||||
}
|
||||
}
|
||||
// Raw bytes as text, too.
|
||||
for _ in 0..1_000 {
|
||||
let n = rng.next() as usize % 200;
|
||||
let bytes: Vec<u8> = (0..n).map(|_| rng.next() as u8).collect();
|
||||
let _ = compile(&String::from_utf8_lossy(&bytes));
|
||||
}
|
||||
assert!(compiled > 0, "some soup should compile (empty scripts at least)");
|
||||
assert!(t0.elapsed().as_secs_f32() < 20.0, "fuzzing took {:?}", t0.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compiles_once_per_script() {
|
||||
let s = crate::SourceScript::new(crate::Language::ActionScript3, "stop();");
|
||||
let a: *const crate::CompileResult = s.compiled();
|
||||
let b: *const crate::CompileResult = s.compiled();
|
||||
assert!(std::ptr::eq(a, b));
|
||||
assert!(s.runs());
|
||||
// A copy compiles on its own (its text may change); equality ignores the cache.
|
||||
let c = s.clone();
|
||||
assert_eq!(c, s);
|
||||
assert!(!crate::SourceScript::new(crate::Language::ActionScript1or2, "stop();").runs());
|
||||
}
|
||||
@@ -5,17 +5,20 @@
|
||||
//! instance by its instance-name path, react to button events, write `trace` output and set a
|
||||
//! few instance properties. Every front end speaks it: frame actions edited in the Actions
|
||||
//! panel, WebAssembly frame scripts (which emit actions through the plug-in ABI) and, later, the
|
||||
//! ActionScript subset and the HTML canvas exporter. The player in `anicraft-doc` runs it.
|
||||
//! Scripts in another language that AniCraft keeps but doesn't run yet ([`SourceScript`], ADR
|
||||
//! 0013 tier 1) sit beside the actions in [`FrameScript`].
|
||||
//! ActionScript subset ([`as3`], ADR 0013 tier 2) and the HTML canvas exporter. The player in
|
||||
//! `anicraft-doc` runs it. Scripts kept as written ([`SourceScript`], ADR 0013 tier 1) sit beside
|
||||
//! the actions in [`FrameScript`]; those in the ActionScript 3.0 subset compile to actions once
|
||||
//! and run.
|
||||
//!
|
||||
//! This crate knows nothing about documents: targets are name paths and frames are numbers or
|
||||
//! labels, resolved by the player when an action runs. Frames are 0-based, as everywhere in
|
||||
//! the engine (the app shows them 1-based).
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod as3;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// Most actions in one list (a keyframe's, or one event handler's).
|
||||
pub const MAX_ACTIONS: usize = 256;
|
||||
@@ -544,18 +547,67 @@ impl Language {
|
||||
}
|
||||
|
||||
/// A script kept verbatim with the document (ADR 0013 tier 1): its text exactly as written,
|
||||
/// and its language. AniCraft shows and edits it; nothing runs it yet.
|
||||
/// and its language. AniCraft shows and edits it, and runs it when it is in the ActionScript 3.0
|
||||
/// subset ([`SourceScript::compiled`], tier 2).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SourceScript {
|
||||
#[serde(default)]
|
||||
pub language: Language,
|
||||
#[serde(default)]
|
||||
pub text: String,
|
||||
/// The script compiled, made the first time it is asked for. A pure function of the
|
||||
/// language and text, so it is never saved and never compared.
|
||||
#[serde(skip)]
|
||||
compiled: CompileCache,
|
||||
}
|
||||
|
||||
/// What [`SourceScript::compiled`] gives: the script's steps, or why it doesn't run.
|
||||
pub type CompileResult = Result<as3::Compiled, Vec<as3::Problem>>;
|
||||
|
||||
/// A lazily filled slot. Cloning gives an empty one, so a copy whose text is then changed
|
||||
/// compiles afresh; comparing ignores it.
|
||||
#[derive(Default)]
|
||||
struct CompileCache(OnceLock<CompileResult>);
|
||||
|
||||
impl Clone for CompileCache {
|
||||
fn clone(&self) -> Self {
|
||||
CompileCache::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CompileCache {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for CompileCache {}
|
||||
|
||||
impl std::fmt::Debug for CompileCache {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(if self.0.get().is_some() { "compiled" } else { "not compiled" })
|
||||
}
|
||||
}
|
||||
|
||||
impl SourceScript {
|
||||
pub fn new(language: Language, text: impl Into<String>) -> SourceScript {
|
||||
SourceScript { language, text: text.into() }
|
||||
SourceScript { language, text: text.into(), compiled: CompileCache::default() }
|
||||
}
|
||||
|
||||
/// The script compiled to actions (ADR 0013 tier 2), or the problems that keep it from
|
||||
/// running. Compiled once per script: the document shares scripts by `Arc`, so undo
|
||||
/// snapshots, the render thread and Test Movie all reuse it.
|
||||
pub fn compiled(&self) -> &CompileResult {
|
||||
self.compiled.0.get_or_init(|| match self.language {
|
||||
Language::ActionScript3 => as3::compile(&self.text),
|
||||
Language::ActionScript1or2 => Err(vec![as3::Problem::whole("ActionScript 1.0 and 2.0 don't run; AniCraft runs a subset of ActionScript 3.0")]),
|
||||
Language::Other => Err(vec![as3::Problem::whole("scripts in other languages don't run; AniCraft runs a subset of ActionScript 3.0")]),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether it runs (it compiled).
|
||||
pub fn runs(&self) -> bool {
|
||||
self.compiled().is_ok()
|
||||
}
|
||||
pub fn check(&self) -> Result<(), String> {
|
||||
if self.text.trim().is_empty() {
|
||||
@@ -573,8 +625,8 @@ impl SourceScript {
|
||||
}
|
||||
|
||||
/// What runs when the playhead enters a keyframe: a list of actions, a plug-in's entry point
|
||||
/// (a frame script), or a script kept verbatim that doesn't run yet (ADR 0013 tier 1). One
|
||||
/// field keeps "one of these" true by construction.
|
||||
/// (a frame script), or a script kept verbatim (ADR 0013 tier 1), which runs when it is in the
|
||||
/// ActionScript 3.0 subset (tier 2). One field keeps "one of these" true by construction.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FrameScript {
|
||||
@@ -626,7 +678,8 @@ impl FrameScript {
|
||||
FrameScript::Plugin(p) => format!("Frame script {} · {}", p.id, p.entry),
|
||||
FrameScript::Source(s) => {
|
||||
let n = s.lines();
|
||||
format!("Script in {} ({n} {}), kept, not run", s.language.label(), if n == 1 { "line" } else { "lines" })
|
||||
let state = if s.runs() { "runs" } else { "kept, not run" };
|
||||
format!("Script in {} ({n} {}), {state}", s.language.label(), if n == 1 { "line" } else { "lines" })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -754,7 +807,9 @@ mod tests {
|
||||
let back: FrameScript = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(back, s);
|
||||
assert_eq!(back.source().unwrap().text, text, "byte for byte");
|
||||
assert_eq!(s.describe(), "Script in ActionScript 3.0 (3 lines), kept, not run");
|
||||
assert_eq!(s.describe(), "Script in ActionScript 3.0 (3 lines), runs");
|
||||
let other = FrameScript::Source(Arc::new(SourceScript::new(Language::ActionScript1or2, "stop();")));
|
||||
assert_eq!(other.describe(), "Script in ActionScript 1.0 & 2.0 (1 line), kept, not run");
|
||||
assert!(s.actions().is_empty() && !s.needs_repair());
|
||||
// The language defaults to ActionScript 3.0; unknown ones are refused.
|
||||
let d: SourceScript = serde_json::from_value(json!({"text": "x"})).unwrap();
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
//! Armatures (ADR 0043): bones that join symbol instances on an armature layer, poses that
|
||||
//! turn them, and inverse kinematics that finds a pose from a dragged bone end.
|
||||
//!
|
||||
//! An armature is a tree of [`Bone`]s on a [`LayerKind::Armature`](crate::LayerKind) layer.
|
||||
//! Each bone starts at a **joint** on its *parent* instance (its head) and ends on its *child*
|
||||
//! instance (its tail); the child turns about the joint, carrying everything below it. An
|
||||
//! instance is the child of at most one bone, and the instance no bone ends in is the root: it
|
||||
//! keeps its own transform, so moving it moves the whole armature.
|
||||
//!
|
||||
//! A **pose** is a joint angle per bone ([`Pose`]), stored on each keyframe of the armature
|
||||
//! layer and tweened between keyframes with the keyframe's easing. Angles are relative: 0 is the
|
||||
//! bone as it was drawn, measured against its parent, so turning a parent carries its children.
|
||||
//! Forward kinematics ([`place`]) turns a pose into the instances' transforms; it is pure, and
|
||||
//! [`crate::evaluate_layer_elements`] applies it, so every renderer, export and the player see
|
||||
//! the posed instances.
|
||||
//!
|
||||
//! Inverse kinematics ([`solve`]) is cyclic coordinate descent (CCD): sweeping from the dragged
|
||||
//! bone up its chain, each joint turns so the effector points at the target, clamped to the
|
||||
//! joint's limits. It works on joint angles directly, so limits are a clamp per step and the
|
||||
//! result is a pose by construction.
|
||||
|
||||
use crate::{Element, ElementId, Keyframe, Layer};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Most bones in one armature.
|
||||
pub const MAX_BONES: usize = 256;
|
||||
/// Longest bone name kept (bytes).
|
||||
pub const MAX_NAME: usize = 256;
|
||||
/// Joint limits stay within a turn either way (radians).
|
||||
pub const MAX_LIMIT: f32 = std::f32::consts::TAU;
|
||||
/// Largest joint angle kept (radians): many turns, never infinity.
|
||||
pub const MAX_ANGLE: f32 = 64.0 * std::f32::consts::TAU;
|
||||
/// IK stops once the effector is this close to its target (layer units, pixels).
|
||||
pub const IK_TOLERANCE: f32 = 0.01;
|
||||
/// Most CCD sweeps one solve takes.
|
||||
pub const IK_SWEEPS: usize = 2048;
|
||||
/// How often a stalled solve bends its joints to get going again, and by how much (radians).
|
||||
const IK_KICKS: usize = 4;
|
||||
const IK_KICK: f32 = 0.3;
|
||||
|
||||
/// Unique id of a bone within a document (from the document's id counter).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct BoneId(pub u64);
|
||||
|
||||
/// How far a joint may turn either way from where the bone was drawn (radians, `min ≤ 0 ≤ max`
|
||||
/// is usual but not required).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Limits {
|
||||
pub min: f32,
|
||||
pub max: f32,
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
/// `a` kept inside the limits.
|
||||
pub fn clamp(&self, a: f32) -> f32 {
|
||||
a.clamp(self.min, self.max)
|
||||
}
|
||||
|
||||
/// Finite, ordered and within [`MAX_LIMIT`]; `None` when nothing sane is left.
|
||||
pub fn sanitized(self) -> Option<Limits> {
|
||||
if !(self.min.is_finite() && self.max.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = (self.min.clamp(-MAX_LIMIT, MAX_LIMIT), self.max.clamp(-MAX_LIMIT, MAX_LIMIT));
|
||||
Some(Limits { min: a.min(b), max: a.max(b) })
|
||||
}
|
||||
}
|
||||
|
||||
/// A bone: from a joint on its parent instance to its child instance, which it turns.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Bone {
|
||||
pub id: BoneId,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub name: String,
|
||||
/// The instance the bone starts on (the joint is a point on it).
|
||||
pub parent: ElementId,
|
||||
/// The instance the bone moves.
|
||||
pub child: ElementId,
|
||||
/// The joint, in the parent instance's local space: the child turns about it.
|
||||
pub head: Vec2,
|
||||
/// The bone's end, in the child instance's local space (where a drag pulls it).
|
||||
pub tail: Vec2,
|
||||
/// The child's transform in the parent's local space at joint angle 0 (as it was drawn).
|
||||
pub rest: Affine,
|
||||
/// How far the joint may turn; `None`: freely.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub limits: Option<Limits>,
|
||||
/// Pinned: inverse kinematics never turns it (nor the bones it hangs from), so its end stays
|
||||
/// where it is while the rest of the armature follows a drag.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub pinned: bool,
|
||||
}
|
||||
|
||||
impl Bone {
|
||||
/// `a` as this joint allows it (finite, within its limits).
|
||||
pub fn allow(&self, a: f32) -> f32 {
|
||||
let a = if a.is_finite() { a.clamp(-MAX_ANGLE, MAX_ANGLE) } else { 0.0 };
|
||||
self.limits.map_or(a, |l| l.clamp(a))
|
||||
}
|
||||
|
||||
fn is_sane(&self) -> bool {
|
||||
self.parent != self.child && self.head.x.is_finite() && self.head.y.is_finite() && self.tail.x.is_finite() && self.tail.y.is_finite() && self.rest.is_finite() && self.rest.inverse().is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// The bones of an armature layer, each listed after the bone it hangs from.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Armature {
|
||||
#[serde(default)]
|
||||
pub bones: Vec<Bone>,
|
||||
}
|
||||
|
||||
impl Armature {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.bones.is_empty()
|
||||
}
|
||||
|
||||
pub fn bone(&self, id: BoneId) -> Option<&Bone> {
|
||||
self.bones.iter().find(|b| b.id == id)
|
||||
}
|
||||
|
||||
pub fn bone_mut(&mut self, id: BoneId) -> Option<&mut Bone> {
|
||||
self.bones.iter_mut().find(|b| b.id == id)
|
||||
}
|
||||
|
||||
/// The bone that moves instance `el` (ends in it), if any.
|
||||
pub fn bone_into(&self, el: ElementId) -> Option<&Bone> {
|
||||
self.bones.iter().find(|b| b.child == el)
|
||||
}
|
||||
|
||||
/// The bone `b` hangs from: the one that moves its parent instance.
|
||||
pub fn parent_bone(&self, b: &Bone) -> Option<&Bone> {
|
||||
self.bone_into(b.parent)
|
||||
}
|
||||
|
||||
/// Whether instance `el` is part of the armature.
|
||||
pub fn contains(&self, el: ElementId) -> bool {
|
||||
self.bones.iter().any(|b| b.parent == el || b.child == el)
|
||||
}
|
||||
|
||||
/// Every instance in the armature, roots first.
|
||||
pub fn members(&self) -> Vec<ElementId> {
|
||||
let mut out: Vec<ElementId> = self.roots();
|
||||
for b in &self.bones {
|
||||
if !out.contains(&b.child) {
|
||||
out.push(b.child);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The instances no bone moves (one for an armature made with the Bone tool).
|
||||
pub fn roots(&self) -> Vec<ElementId> {
|
||||
let mut out = Vec::new();
|
||||
for b in &self.bones {
|
||||
if self.bone_into(b.parent).is_none() && !out.contains(&b.parent) {
|
||||
out.push(b.parent);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Bone `id` and every bone below it, in armature order.
|
||||
pub fn subtree(&self, id: BoneId) -> Vec<BoneId> {
|
||||
let mut inside: HashSet<ElementId> = HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for b in &self.bones {
|
||||
if b.id == id || inside.contains(&b.parent) {
|
||||
inside.insert(b.child);
|
||||
out.push(b.id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The chain from bone `id` up to its root, `id` first (bounded by the bone count).
|
||||
pub fn chain(&self, id: BoneId) -> Vec<&Bone> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = self.bone(id);
|
||||
while let Some(b) = cur {
|
||||
if out.len() >= self.bones.len() || out.iter().any(|o: &&Bone| o.id == b.id) {
|
||||
break;
|
||||
}
|
||||
out.push(b);
|
||||
cur = self.parent_bone(b);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Repairs a loaded armature: drops bones with non-finite numbers, repeated ids, a second
|
||||
/// bone into one instance and bones in cycles; keeps every bone after its parent; keeps at
|
||||
/// most [`MAX_BONES`]. Returns whether anything changed.
|
||||
pub fn sanitize(&mut self) -> bool {
|
||||
let before = self.bones.clone();
|
||||
let mut seen_id = HashSet::new();
|
||||
let mut seen_child = HashSet::new();
|
||||
let mut kept: Vec<Bone> = Vec::new();
|
||||
for mut b in std::mem::take(&mut self.bones) {
|
||||
if !b.is_sane() || !seen_id.insert(b.id) || !seen_child.insert(b.child) {
|
||||
continue;
|
||||
}
|
||||
b.limits = b.limits.and_then(Limits::sanitized);
|
||||
if b.name.len() > MAX_NAME {
|
||||
let cut = (0..=MAX_NAME).rev().find(|&i| b.name.is_char_boundary(i)).unwrap_or(0);
|
||||
b.name.truncate(cut);
|
||||
}
|
||||
kept.push(b);
|
||||
}
|
||||
// Order: a bone after the bone moving its parent. What never gets placed is a cycle.
|
||||
let children: HashSet<ElementId> = kept.iter().map(|b| b.child).collect();
|
||||
let mut placed: HashSet<ElementId> = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect();
|
||||
let mut ordered = Vec::with_capacity(kept.len());
|
||||
let mut rest = kept;
|
||||
loop {
|
||||
let (ready, wait): (Vec<Bone>, Vec<Bone>) = rest.into_iter().partition(|b| placed.contains(&b.parent));
|
||||
if ready.is_empty() {
|
||||
break;
|
||||
}
|
||||
for b in ready {
|
||||
placed.insert(b.child);
|
||||
ordered.push(b);
|
||||
}
|
||||
rest = wait;
|
||||
}
|
||||
ordered.truncate(MAX_BONES);
|
||||
self.bones = ordered;
|
||||
self.bones != before
|
||||
}
|
||||
}
|
||||
|
||||
/// One joint's angle in a pose (radians, 0 as drawn).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct JointAngle {
|
||||
pub bone: BoneId,
|
||||
pub angle: f32,
|
||||
}
|
||||
|
||||
/// A pose: joint angles by bone. A bone it doesn't list is as drawn (angle 0).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Pose(pub Vec<JointAngle>);
|
||||
|
||||
impl Pose {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// The angle of bone `b` (0 when the pose doesn't list it).
|
||||
pub fn angle(&self, b: BoneId) -> f32 {
|
||||
self.0.iter().find(|j| j.bone == b).map_or(0.0, |j| j.angle)
|
||||
}
|
||||
|
||||
pub fn set(&mut self, b: BoneId, angle: f32) {
|
||||
match self.0.iter_mut().find(|j| j.bone == b) {
|
||||
Some(j) => j.angle = angle,
|
||||
None => self.0.push(JointAngle { bone: b, angle }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps only the bones in `keep`.
|
||||
pub fn retain(&mut self, keep: impl Fn(BoneId) -> bool) {
|
||||
self.0.retain(|j| keep(j.bone));
|
||||
}
|
||||
|
||||
/// Every bone of `arm` at the angle its joint allows: the pose as it shows.
|
||||
pub fn allowed(&self, arm: &Armature) -> Pose {
|
||||
Pose(arm.bones.iter().map(|b| JointAngle { bone: b.id, angle: b.allow(self.angle(b.id)) }).collect())
|
||||
}
|
||||
|
||||
/// The pose `t` of the way to `o`, joint by joint (angles blend linearly, so a joint that
|
||||
/// turned a whole way round between keys turns that way in the tween).
|
||||
pub fn lerp(&self, o: &Pose, t: f32, arm: &Armature) -> Pose {
|
||||
Pose(arm.bones.iter().map(|b| JointAngle { bone: b.id, angle: b.allow(anicraft_geom::lerp(self.angle(b.id), o.angle(b.id), t)) }).collect())
|
||||
}
|
||||
|
||||
/// Repairs a loaded pose: finite angles in range, one per bone, at most [`MAX_BONES`].
|
||||
/// Returns whether anything changed.
|
||||
pub fn sanitize(&mut self) -> bool {
|
||||
let before = self.0.len();
|
||||
let mut changed = false;
|
||||
let mut seen = HashSet::new();
|
||||
self.0.retain(|j| seen.insert(j.bone));
|
||||
self.0.truncate(MAX_BONES);
|
||||
for j in &mut self.0 {
|
||||
let a = if j.angle.is_finite() { j.angle.clamp(-MAX_ANGLE, MAX_ANGLE) } else { 0.0 };
|
||||
if a.to_bits() != j.angle.to_bits() {
|
||||
j.angle = a;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed || self.0.len() != before
|
||||
}
|
||||
}
|
||||
|
||||
/// `R(angle)` about point `j`.
|
||||
fn turn_about(j: Vec2, angle: f32) -> Affine {
|
||||
Affine::translate(j.x, j.y).mul(&Affine::rotate(angle)).mul(&Affine::translate(-j.x, -j.y))
|
||||
}
|
||||
|
||||
/// Forward kinematics: the transform (in the layer's space) of every instance in `elements`
|
||||
/// once `pose` turns the armature's joints. A root keeps its own transform; a child is placed
|
||||
/// from its parent: `R_joint(angle) · parent · rest`. An instance whose parent isn't on the
|
||||
/// keyframe keeps its own transform.
|
||||
pub fn place(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> HashMap<ElementId, Affine> {
|
||||
let mut world: HashMap<ElementId, Affine> = elements.iter().map(|e| (e.id, e.transform)).collect();
|
||||
for b in &arm.bones {
|
||||
let Some(wp) = world.get(&b.parent).copied() else { continue };
|
||||
if !world.contains_key(&b.child) {
|
||||
continue;
|
||||
}
|
||||
let j = wp.apply(b.head);
|
||||
let wc = turn_about(j, b.allow(pose.angle(b.id))).mul(&wp.mul(&b.rest));
|
||||
if wc.is_finite() {
|
||||
world.insert(b.child, wc);
|
||||
}
|
||||
}
|
||||
world
|
||||
}
|
||||
|
||||
/// Puts the instances of `elements` where `pose` has them (copy-on-write: only instances that
|
||||
/// move are cloned). Returns whether any moved.
|
||||
pub fn apply(arm: &Armature, elements: &mut [Arc<Element>], pose: &Pose) -> bool {
|
||||
if arm.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let world = place(arm, elements, pose);
|
||||
let mut moved = false;
|
||||
for e in elements.iter_mut() {
|
||||
if arm.bone_into(e.id).is_none() {
|
||||
continue;
|
||||
}
|
||||
if let Some(m) = world.get(&e.id)
|
||||
&& *m != e.transform
|
||||
{
|
||||
Arc::make_mut(e).transform = *m;
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
moved
|
||||
}
|
||||
|
||||
/// The pose layer `layer` has at `frame`: its covering keyframe's, or, inside a tween, the pose
|
||||
/// between that keyframe's and the next one's at the tween's eased time. Exact at keyframes.
|
||||
/// `None` without an armature or on an empty frame.
|
||||
pub fn pose_at(layer: &Layer, frame: u32) -> Option<Pose> {
|
||||
let arm = layer.armature.as_deref().filter(|_| layer.kind == crate::LayerKind::Armature)?;
|
||||
let idx = layer.keyframe_index_at(frame)?;
|
||||
let kf: &Keyframe = layer.keyframes.get(idx)?;
|
||||
let here = kf.pose.allowed(arm);
|
||||
let (Some(tween), None) = (kf.tween, &kf.motion) else { return Some(here) };
|
||||
let Some(next) = layer.keyframes.get(idx + 1) else { return Some(here) };
|
||||
if next.start != kf.end() || frame == kf.start {
|
||||
return Some(here);
|
||||
}
|
||||
let t = tween.easing.apply((frame - kf.start) as f32 / kf.duration.max(1) as f32);
|
||||
Some(kf.pose.lerp(&next.pose, t, arm))
|
||||
}
|
||||
|
||||
/// Where a bone is drawn: its joint (head) and end (tail), in the layer's space.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct BoneAt {
|
||||
pub id: BoneId,
|
||||
pub head: Vec2,
|
||||
pub tail: Vec2,
|
||||
/// The joint angle (radians, as the joint allows it).
|
||||
pub angle: f32,
|
||||
}
|
||||
|
||||
/// Every bone's joint and end with the instances in `elements` placed as they show (posed:
|
||||
/// what [`crate::evaluate_layer_elements`] gives on an armature layer).
|
||||
pub fn bones_at(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> Vec<BoneAt> {
|
||||
let world: HashMap<ElementId, Affine> = elements.iter().map(|e| (e.id, e.transform)).collect();
|
||||
arm.bones
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
let (wp, wc) = (world.get(&b.parent)?, world.get(&b.child)?);
|
||||
Some(BoneAt { id: b.id, head: wp.apply(b.head), tail: wc.apply(b.tail), angle: b.allow(pose.angle(b.id)) })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a solve came to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Solved {
|
||||
/// The new pose (every bone of the armature).
|
||||
pub pose: Pose,
|
||||
/// How far the effector ended from the target.
|
||||
pub error: f32,
|
||||
/// How many bones the drag could turn (0: the bone is pinned, or hangs from a pinned one).
|
||||
pub chain: usize,
|
||||
}
|
||||
|
||||
/// The bones a drag of bone `id` may turn: `id` and the bones it hangs from, up to the first
|
||||
/// that must stay put: a pinned bone, or one a pinned bone hangs from (turning it would move
|
||||
/// the pinned bone).
|
||||
pub fn movable_chain(arm: &Armature, id: BoneId) -> Vec<&Bone> {
|
||||
let frozen: HashSet<BoneId> = arm.bones.iter().filter(|b| b.pinned).flat_map(|p| arm.chain(p.id)).map(|b| b.id).collect();
|
||||
arm.chain(id).into_iter().take_while(|b| !frozen.contains(&b.id)).collect()
|
||||
}
|
||||
|
||||
/// Inverse kinematics: the pose that brings point `local` of bone `id`'s child instance (its
|
||||
/// local space; the bone's tail when dragging the bone end) to `target` (layer space), turning
|
||||
/// only the bones [`movable_chain`] allows. `elements` are the keyframe's instances (the roots
|
||||
/// at their own transforms), `pose` the pose to start from. Cyclic coordinate descent: each
|
||||
/// sweep turns the joints from the dragged bone upward so the effector points at the target,
|
||||
/// each clamped to its limits, until the effector is within [`IK_TOLERANCE`] or stops moving.
|
||||
/// An unreachable target leaves the chain stretched straight toward it, the root where it was.
|
||||
/// `None` when the armature has no bone `id` or its instances aren't on the keyframe.
|
||||
pub fn solve(arm: &Armature, elements: &[Arc<Element>], pose: &Pose, id: BoneId, local: Vec2, target: Vec2) -> Option<Solved> {
|
||||
let bone = arm.bone(id)?;
|
||||
if !(local.x.is_finite() && local.y.is_finite() && target.x.is_finite() && target.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let chain: Vec<(BoneId, ElementId, Vec2)> = movable_chain(arm, id).iter().map(|b| (b.id, b.parent, b.head)).collect();
|
||||
let mut pose = pose.allowed(arm);
|
||||
let effector = |pose: &Pose| -> Option<(HashMap<ElementId, Affine>, Vec2)> {
|
||||
let world = place(arm, elements, pose);
|
||||
let e = world.get(&bone.child)?.apply(local);
|
||||
Some((world, e))
|
||||
};
|
||||
let (_, start) = effector(&pose)?;
|
||||
let mut error = start.distance(target);
|
||||
let mut best = (pose.clone(), error);
|
||||
let mut kicks = 0;
|
||||
for _ in 0..IK_SWEEPS {
|
||||
if error < best.1 {
|
||||
best = (pose.clone(), error);
|
||||
}
|
||||
if error <= IK_TOLERANCE || chain.is_empty() {
|
||||
break;
|
||||
}
|
||||
let Some((world, mut e)) = effector(&pose) else { break };
|
||||
let mut turned = 0.0f32;
|
||||
// From the dragged bone up: turning a joint moves only what is below it, so the joints
|
||||
// above keep the places this sweep began with.
|
||||
for &(b, parent, head) in &chain {
|
||||
let Some(wp) = world.get(&parent) else { continue };
|
||||
let Some(joint) = arm.bone(b) else { continue };
|
||||
let j = wp.apply(head);
|
||||
let (u, v) = (e - j, target - j);
|
||||
if u.length() < 1e-6 || v.length() < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let want = u.cross(v).atan2(u.dot(v));
|
||||
let cur = pose.angle(b);
|
||||
let next = joint.allow(cur + want);
|
||||
let by = next - cur;
|
||||
if by != 0.0 {
|
||||
pose.set(b, next);
|
||||
e = turn_about(j, by).apply(e);
|
||||
turned = turned.max(by.abs());
|
||||
}
|
||||
}
|
||||
let Some((_, e)) = effector(&pose) else { break };
|
||||
let was = error;
|
||||
error = e.distance(target);
|
||||
// Stuck: limits, a chain stretched straight at an unreachable target, or CCD's blind
|
||||
// spot, a straight chain whose target lies on its own line (every joint sees angle 0).
|
||||
// A few kicks bend the joints a little and descent goes on; the best pose seen wins.
|
||||
if turned < 1e-7 || ((was - error).abs() < 1e-6 * was.max(1.0) && turned < 1e-4) {
|
||||
if error < best.1 {
|
||||
best = (pose.clone(), error);
|
||||
}
|
||||
if kicks >= IK_KICKS {
|
||||
break;
|
||||
}
|
||||
kicks += 1;
|
||||
for (i, &(b, _, _)) in chain.iter().enumerate() {
|
||||
let Some(joint) = arm.bone(b) else { continue };
|
||||
let cur = pose.angle(b);
|
||||
let kick = IK_KICK * if (i + kicks) % 2 == 0 { 1.0 } else { -1.0 };
|
||||
let next = joint.allow(cur + kick);
|
||||
pose.set(b, if next != cur { next } else { joint.allow(cur - kick) });
|
||||
}
|
||||
error = effector(&pose).map_or(error, |(_, e)| e.distance(target));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if error < best.1 {
|
||||
best = (pose, error);
|
||||
}
|
||||
Some(Solved { pose: best.0, error: best.1, chain: chain.len() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "armature_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Armatures, poses and inverse kinematics (ADR 0043).
|
||||
|
||||
use super::*;
|
||||
use crate::{BlendMode, ColorEffect, Document, Easing, ElementKind, Keyframe, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Symbol, SymbolId, SymbolKind, Timeline, Tween, evaluate, evaluate_layer_elements};
|
||||
use anicraft_geom::Path;
|
||||
use std::f32::consts::FRAC_PI_2;
|
||||
|
||||
const ROOT: ElementId = ElementId(10);
|
||||
const ARM: ElementId = ElementId(11);
|
||||
const HAND: ElementId = ElementId(12);
|
||||
const B1: BoneId = BoneId(20);
|
||||
const B2: BoneId = BoneId(21);
|
||||
const SEG: SymbolId = SymbolId(1);
|
||||
|
||||
fn instance(id: ElementId, x: f32, y: f32) -> Arc<Element> {
|
||||
let kind = ElementKind::Symbol { symbol: SEG, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() };
|
||||
Arc::new(Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind })
|
||||
}
|
||||
|
||||
fn bone(id: BoneId, parent: ElementId, child: ElementId) -> Bone {
|
||||
// Every segment is 100 px long from its registration point; bones join end to start.
|
||||
Bone { id, name: String::new(), parent, child, head: Vec2::new(100.0, 0.0), tail: Vec2::new(100.0, 0.0), rest: Affine::translate(100.0, 0.0), limits: None, pinned: false }
|
||||
}
|
||||
|
||||
/// A three-segment chain lying along y = 100: the root from x = 100, the arm from 200 (its
|
||||
/// joint), the hand from 300; the hand's end at 400. The arm and hand reach 200 px from the
|
||||
/// shoulder joint at (200, 100).
|
||||
fn chain() -> (Armature, Vec<Arc<Element>>) {
|
||||
let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)] };
|
||||
(arm, vec![instance(ROOT, 100.0, 100.0), instance(ARM, 200.0, 100.0), instance(HAND, 300.0, 100.0)])
|
||||
}
|
||||
|
||||
fn hand_end(arm: &Armature, els: &[Arc<Element>], pose: &Pose) -> Vec2 {
|
||||
place(arm, els, pose)[&HAND].apply(Vec2::new(100.0, 0.0))
|
||||
}
|
||||
|
||||
fn close(a: Vec2, b: Vec2, tol: f32) -> bool {
|
||||
a.distance(b) <= tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forward_kinematics_turns_children_about_their_joints() {
|
||||
let (arm, els) = chain();
|
||||
let rest = place(&arm, &els, &Pose::default());
|
||||
assert!(close(rest[&HAND].translation(), Vec2::new(300.0, 100.0), 1e-4), "the rest pose is the drawing");
|
||||
let mut pose = Pose::default();
|
||||
pose.set(B1, FRAC_PI_2);
|
||||
let w = place(&arm, &els, &pose);
|
||||
// The arm turns a quarter clockwise about the shoulder (200, 100): it now points down.
|
||||
assert!(close(w[&ARM].translation(), Vec2::new(200.0, 100.0), 1e-4));
|
||||
assert!(close(w[&HAND].translation(), Vec2::new(200.0, 200.0), 1e-3), "{:?}", w[&HAND]);
|
||||
assert!(close(hand_end(&arm, &els, &pose), Vec2::new(200.0, 300.0), 1e-3));
|
||||
// The elbow turns relative to the arm: a quarter back makes the hand point right again.
|
||||
pose.set(B2, -FRAC_PI_2);
|
||||
assert!(close(hand_end(&arm, &els, &pose), Vec2::new(300.0, 200.0), 1e-3));
|
||||
// The root keeps its own transform.
|
||||
assert_eq!(place(&arm, &els, &pose)[&ROOT], Affine::translate(100.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ik_reaches_a_reachable_target_within_half_a_pixel() {
|
||||
let (arm, els) = chain();
|
||||
for target in [Vec2::new(300.0, 180.0), Vec2::new(150.0, 200.0), Vec2::new(250.0, 20.0), Vec2::new(390.0, 110.0), Vec2::new(210.0, 120.0)] {
|
||||
let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), target).unwrap();
|
||||
let end = hand_end(&arm, &els, &s.pose);
|
||||
assert!(close(end, target, 0.5), "{target:?}: ended at {end:?} ({} px off)", s.error);
|
||||
assert!((s.error - end.distance(target)).abs() < 1e-3);
|
||||
assert_eq!(s.chain, 2);
|
||||
// The root never moves.
|
||||
assert_eq!(place(&arm, &els, &s.pose)[&ROOT], Affine::translate(100.0, 100.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ik_respects_joint_limits() {
|
||||
let (mut arm, els) = chain();
|
||||
let lim = Limits { min: -10f32.to_radians(), max: 10f32.to_radians() };
|
||||
arm.bone_mut(B2).unwrap().limits = Some(lim);
|
||||
// A target that needs a sharp elbow: the elbow stops at its limit.
|
||||
let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(200.0, 160.0)).unwrap();
|
||||
let a = s.pose.angle(B2);
|
||||
assert!((lim.min..=lim.max).contains(&a), "elbow at {}°", a.to_degrees());
|
||||
// Evaluation clamps too, whatever a file says.
|
||||
let mut wild = Pose::default();
|
||||
wild.set(B2, 3.0);
|
||||
assert_eq!(wild.allowed(&arm).angle(B2), lim.max);
|
||||
// A joint that may not turn at all keeps its angle.
|
||||
arm.bone_mut(B1).unwrap().limits = Some(Limits { min: 0.0, max: 0.0 });
|
||||
let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(300.0, 300.0)).unwrap();
|
||||
assert_eq!(s.pose.angle(B1), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreachable_target_stretches_the_chain_straight_and_the_root_stays() {
|
||||
let (arm, els) = chain();
|
||||
let target = Vec2::new(700.0, 500.0);
|
||||
let mut start = Pose::default();
|
||||
start.set(B1, 0.7);
|
||||
start.set(B2, -1.2);
|
||||
let s = solve(&arm, &els, &start, B2, Vec2::new(100.0, 0.0), target).unwrap();
|
||||
let w = place(&arm, &els, &s.pose);
|
||||
let (shoulder, elbow, end) = (Vec2::new(200.0, 100.0), w[&HAND].translation(), hand_end(&arm, &els, &s.pose));
|
||||
let (d1, d2, dt) = ((elbow - shoulder).normalized(), (end - elbow).normalized(), (target - shoulder).normalized());
|
||||
assert!(d1.cross(d2).abs() < 1e-3 && d1.dot(d2) > 0.999, "straight: {d1:?} {d2:?}");
|
||||
assert!(d1.dot(dt) > 0.999, "pointing at the target");
|
||||
assert!((s.error - (target.distance(shoulder) - 200.0)).abs() < 0.05, "{}", s.error);
|
||||
assert_eq!(w[&ROOT], Affine::translate(100.0, 100.0), "the root stays put");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_bones_stay_put() {
|
||||
let (mut arm, els) = chain();
|
||||
arm.bone_mut(B1).unwrap().pinned = true;
|
||||
let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(250.0, 180.0)).unwrap();
|
||||
assert_eq!(s.pose.angle(B1), 0.0, "the pinned shoulder never turns");
|
||||
assert_eq!(s.chain, 1);
|
||||
// Dragging the pinned bone itself moves nothing.
|
||||
let s = solve(&arm, &els, &Pose::default(), B1, Vec2::new(100.0, 0.0), Vec2::new(0.0, 0.0)).unwrap();
|
||||
assert_eq!((s.chain, s.pose.angle(B1)), (0, 0.0));
|
||||
// A pin locks the bones it hangs from too.
|
||||
arm.bone_mut(B1).unwrap().pinned = false;
|
||||
arm.bone_mut(B2).unwrap().pinned = true;
|
||||
assert!(movable_chain(&arm, B1).is_empty(), "turning the shoulder would move the pinned hand");
|
||||
assert!(movable_chain(&arm, B2).is_empty());
|
||||
}
|
||||
|
||||
/// An armature layer: the chain at frame 0 posed straight, at frame 10 with the shoulder a
|
||||
/// quarter turned, tweened with `easing`.
|
||||
fn armature_layer(easing: Easing) -> Layer {
|
||||
let (arm, els) = chain();
|
||||
let mut l = Layer::new(LayerId(1), "Armature_1");
|
||||
l.kind = LayerKind::Armature;
|
||||
l.armature = Some(Arc::new(arm));
|
||||
let mut a = Keyframe::new(0, 10);
|
||||
a.elements = els.clone();
|
||||
a.tween = Some(Tween { easing, ..Tween::default() });
|
||||
let mut b = Keyframe::new(10, 5);
|
||||
b.elements = els;
|
||||
b.pose.set(B1, FRAC_PI_2);
|
||||
l.keyframes = vec![Arc::new(a), Arc::new(b)];
|
||||
l
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poses_tween_and_are_exact_at_keyframes() {
|
||||
let l = armature_layer(Easing::Linear);
|
||||
assert_eq!(pose_at(&l, 0).unwrap().angle(B1), 0.0);
|
||||
assert_eq!(pose_at(&l, 10).unwrap().angle(B1), FRAC_PI_2, "exact at the key");
|
||||
assert_eq!(pose_at(&l, 14).unwrap().angle(B1), FRAC_PI_2, "held after the last key");
|
||||
assert!((pose_at(&l, 5).unwrap().angle(B1) - FRAC_PI_2 * 0.5).abs() < 1e-6);
|
||||
// The existing easing shapes the tween.
|
||||
let eased = armature_layer(Easing::QuadIn);
|
||||
assert!((pose_at(&eased, 5).unwrap().angle(B1) - FRAC_PI_2 * 0.25).abs() < 1e-6);
|
||||
// Evaluation places the instances by the pose: at the key, exactly forward kinematics.
|
||||
let (_, els) = evaluate_layer_elements(&l, 10).unwrap();
|
||||
let hand = els.iter().find(|e| e.id == HAND).unwrap();
|
||||
assert!(close(hand.transform.translation(), Vec2::new(200.0, 200.0), 1e-3));
|
||||
// Half way the hand has swung through 45° about the shoulder.
|
||||
let (_, els) = evaluate_layer_elements(&l, 5).unwrap();
|
||||
let hand = els.iter().find(|e| e.id == HAND).unwrap();
|
||||
let r = std::f32::consts::FRAC_1_SQRT_2 * 100.0;
|
||||
assert!(close(hand.transform.translation(), Vec2::new(200.0 + r, 100.0 + r), 1e-3), "{:?}", hand.transform);
|
||||
// Without the tween the first pose holds.
|
||||
let mut held = armature_layer(Easing::Linear);
|
||||
Arc::make_mut(&mut held.keyframes[0]).tween = None;
|
||||
assert_eq!(pose_at(&held, 9).unwrap().angle(B1), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_export_sees_the_pose() {
|
||||
let mut d = Document::default();
|
||||
let mut seg = Layer::new(LayerId(2), "seg");
|
||||
let mut k = Keyframe::new(0, 1);
|
||||
k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) }));
|
||||
seg.keyframes = vec![Arc::new(k)];
|
||||
d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(seg)] } }));
|
||||
d.timeline_mut(0).layers = vec![Arc::new(armature_layer(Easing::Linear))];
|
||||
d.sanitize();
|
||||
let dl = evaluate(&d, 10);
|
||||
let hand = dl.items.iter().find(|i| i.element == HAND).unwrap();
|
||||
assert!(close(hand.transform.apply(Vec2::new(100.0, 0.0)), Vec2::new(200.0, 300.0), 1e-3), "the display list draws the posed hand");
|
||||
// The file keeps the armature and poses.
|
||||
let back: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
|
||||
assert_eq!(back, d);
|
||||
assert_eq!(back.timeline(0).layers[0].keyframes[1].pose.angle(B1), FRAC_PI_2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_repairs_hostile_armatures() {
|
||||
let (mut arm, _) = chain();
|
||||
// Listed child first, a cycle, a second bone into the hand, a bone into itself, NaN.
|
||||
let mut cyc = bone(BoneId(30), ElementId(40), ElementId(41));
|
||||
cyc.head = Vec2::new(0.0, 0.0);
|
||||
let back = bone(BoneId(31), ElementId(41), ElementId(40));
|
||||
let twice = bone(BoneId(32), ROOT, HAND);
|
||||
let selfie = bone(BoneId(33), ROOT, ROOT);
|
||||
let mut nan = bone(BoneId(34), HAND, ElementId(50));
|
||||
nan.rest = Affine { m: [f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0] };
|
||||
let mut wide = bone(BoneId(35), HAND, ElementId(51));
|
||||
wide.limits = Some(Limits { min: 100.0, max: f32::NEG_INFINITY });
|
||||
let mut limited = bone(BoneId(36), HAND, ElementId(52));
|
||||
limited.limits = Some(Limits { min: 1.0, max: -1.0 });
|
||||
arm.bones.reverse();
|
||||
arm.bones.extend([cyc, back, twice, selfie, nan, wide, limited]);
|
||||
assert!(arm.sanitize());
|
||||
let ids: Vec<u64> = arm.bones.iter().map(|b| b.id.0).collect();
|
||||
assert_eq!(ids, vec![20, 21, 35, 36], "ordered parent first; cycles, repeats and NaN gone");
|
||||
assert_eq!(arm.bone(BoneId(35)).unwrap().limits, None);
|
||||
assert_eq!(arm.bone(BoneId(36)).unwrap().limits, Some(Limits { min: -1.0, max: 1.0 }));
|
||||
assert!(!arm.sanitize(), "sanitizing twice changes nothing");
|
||||
let mut p = Pose(vec![JointAngle { bone: B1, angle: f32::NAN }, JointAngle { bone: B1, angle: 1.0 }, JointAngle { bone: B2, angle: 1e30 }]);
|
||||
assert!(p.sanitize());
|
||||
assert_eq!(p.0.len(), 2);
|
||||
assert_eq!((p.angle(B1), p.angle(B2)), (0.0, MAX_ANGLE));
|
||||
// Hostile solves return nothing rather than panicking.
|
||||
let (arm, els) = chain();
|
||||
assert!(solve(&arm, &els, &Pose::default(), BoneId(999), Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)).is_none());
|
||||
assert!(solve(&arm, &els, &Pose::default(), B2, Vec2::new(f32::NAN, 0.0), Vec2::new(1.0, 1.0)).is_none());
|
||||
assert!(solve(&arm, &[], &Pose::default(), B2, Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_queries() {
|
||||
let (arm, _) = chain();
|
||||
assert_eq!(arm.roots(), vec![ROOT]);
|
||||
assert_eq!(arm.members(), vec![ROOT, ARM, HAND]);
|
||||
assert_eq!(arm.subtree(B1), vec![B1, B2]);
|
||||
assert_eq!(arm.subtree(B2), vec![B2]);
|
||||
assert_eq!(arm.chain(B2).iter().map(|b| b.id).collect::<Vec<_>>(), vec![B2, B1]);
|
||||
assert_eq!(arm.bone_into(HAND).map(|b| b.id), Some(B2));
|
||||
assert!(arm.contains(ROOT) && !arm.contains(ElementId(99)));
|
||||
}
|
||||
|
||||
/// Long chains and targets on a straight chain's own line (CCD's blind spot) still converge.
|
||||
#[test]
|
||||
fn long_chains_and_collinear_targets_converge() {
|
||||
for n in [2usize, 10, 64] {
|
||||
let mut bones = Vec::new();
|
||||
let mut els = vec![instance(ElementId(1000), 0.0, 0.0)];
|
||||
for i in 0..n {
|
||||
let (p, c) = (ElementId(1000 + i as u64), ElementId(1001 + i as u64));
|
||||
bones.push(Bone { id: BoneId(5000 + i as u64), ..bone(BoneId(0), p, c) });
|
||||
els.push(instance(c, 100.0 * (i + 1) as f32, 0.0));
|
||||
}
|
||||
let arm = Armature { bones };
|
||||
let last = BoneId(5000 + n as u64 - 1);
|
||||
let reach = 100.0 * n as f32;
|
||||
for k in 0..12 {
|
||||
// k = 0: straight ahead along the chain.
|
||||
let a = k as f32 * 0.55;
|
||||
let target = Vec2::new(100.0 + reach * 0.6 * a.cos(), reach * 0.6 * a.sin());
|
||||
let s = solve(&arm, &els, &Pose::default(), last, Vec2::new(100.0, 0.0), target).unwrap();
|
||||
assert!(s.error <= 0.5, "{n} bones to {target:?}: {} px off", s.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -183,7 +183,19 @@ pub fn evaluate_layer_elements(layer: &Layer, frame: u32) -> Option<(u32, Cow<'_
|
||||
/// [`evaluate_layer_elements`] with a motion guide: tweened elements travel along `guide` (in
|
||||
/// the layer's own space) from the point nearest their start to the point nearest their end,
|
||||
/// turning with it when the tween orients to the path.
|
||||
///
|
||||
/// On an armature layer (ADR 0043) the instances are then placed by the pose at the frame
|
||||
/// (tweened between pose keyframes): forward kinematics from the root's own transform.
|
||||
pub fn evaluate_guided<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
|
||||
let (start, els) = evaluate_tweened(layer, frame, guide)?;
|
||||
let Some(arm) = layer.armature.as_deref().filter(|a| layer.kind == crate::LayerKind::Armature && !a.is_empty()) else { return Some((start, els)) };
|
||||
let pose = crate::armature::pose_at(layer, frame).unwrap_or_default();
|
||||
let mut els = els.into_owned();
|
||||
crate::armature::apply(arm, &mut els, &pose);
|
||||
Some((start, Cow::Owned(els)))
|
||||
}
|
||||
|
||||
fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
|
||||
let idx = layer.keyframe_index_at(frame)?;
|
||||
let kf = layer.keyframes.get(idx)?;
|
||||
// A motion tween: its target follows the property curves (and its motion path, ADR 0030);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
pub use anicraft_audio as audio;
|
||||
pub use anicraft_actions as actions;
|
||||
|
||||
pub mod armature;
|
||||
mod bitmap;
|
||||
pub mod camera;
|
||||
mod filter;
|
||||
@@ -16,6 +17,7 @@ mod hints;
|
||||
pub mod motion;
|
||||
pub mod path_table;
|
||||
pub mod width;
|
||||
pub mod stroke_style;
|
||||
pub mod player;
|
||||
pub mod sample;
|
||||
pub mod sound;
|
||||
@@ -24,10 +26,12 @@ pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST
|
||||
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png};
|
||||
pub use easing::Easing;
|
||||
pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre};
|
||||
pub use motion::{MotionTween, OnPath, Property, PropertyKey, Props, Track, motion_path};
|
||||
pub use motion::{MotionTween, OnPath, Pin, PinError, Property, PropertyKey, Props, Track, motion_path};
|
||||
pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync};
|
||||
pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile};
|
||||
pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle};
|
||||
pub use camera::Camera;
|
||||
pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose};
|
||||
pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, guide_walk, instance_start};
|
||||
pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript};
|
||||
|
||||
@@ -157,7 +161,8 @@ impl Paint {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stroke style: round joins and caps, one width or a width profile (ADR 0018).
|
||||
/// A line: colour, width, an optional width profile (ADR 0018) and its style: caps, joins,
|
||||
/// miter limit, dashes (ADR 0046).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(from = "StrokeFile")]
|
||||
pub struct Stroke {
|
||||
@@ -167,40 +172,60 @@ pub struct Stroke {
|
||||
/// How the width varies along each subpath (`None`: the same everywhere). Never uniform.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub profile: Option<WidthProfile>,
|
||||
/// Caps, joins and dashes. The default (round, solid) is written as nothing, so strokes
|
||||
/// without a style are stored as before.
|
||||
#[serde(default, skip_serializing_if = "StrokeStyle::is_default")]
|
||||
pub style: StrokeStyle,
|
||||
}
|
||||
|
||||
/// What a file may hold for a stroke (a uniform profile is dropped on load).
|
||||
/// What a file may hold for a stroke (a uniform profile is dropped on load, the style is
|
||||
/// sanitized).
|
||||
#[derive(Deserialize)]
|
||||
struct StrokeFile {
|
||||
color: Rgba,
|
||||
width: f32,
|
||||
#[serde(default)]
|
||||
profile: Option<WidthProfile>,
|
||||
#[serde(default)]
|
||||
style: StrokeStyle,
|
||||
}
|
||||
|
||||
impl From<StrokeFile> for Stroke {
|
||||
fn from(f: StrokeFile) -> Stroke {
|
||||
Stroke { color: f.color, width: f.width, profile: f.profile.filter(|p| !p.is_uniform()) }
|
||||
Stroke { color: f.color, width: f.width, profile: f.profile.filter(|p| !p.is_uniform()), style: f.style.sanitized() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Stroke {
|
||||
/// A stroke of one width.
|
||||
/// A solid stroke of one width with round caps and joins.
|
||||
pub fn new(color: Rgba, width: f32) -> Stroke {
|
||||
Stroke { color, width, profile: None }
|
||||
Stroke { color, width, profile: None, style: StrokeStyle::default() }
|
||||
}
|
||||
pub fn with_profile(self, profile: Option<WidthProfile>) -> Stroke {
|
||||
Stroke { profile: profile.filter(|p| !p.is_uniform()), ..self }
|
||||
}
|
||||
/// The same stroke with caps, joins and dashes from `style` (sanitized).
|
||||
pub fn with_style(self, style: StrokeStyle) -> Stroke {
|
||||
Stroke { style: style.sanitized(), ..self }
|
||||
}
|
||||
/// The farthest the stroke reaches from its path (local units): half its nominal width
|
||||
/// times the profile's widest factor.
|
||||
/// times the profile's widest factor, times what miter corners and square caps add.
|
||||
pub fn reach(&self) -> f32 {
|
||||
let w = if self.width.is_finite() { self.width.max(0.0) } else { 0.0 };
|
||||
w * 0.5 * self.profile.as_ref().map_or(1.0, WidthProfile::max_factor)
|
||||
w * 0.5 * self.profile.as_ref().map_or(1.0, WidthProfile::max_factor) * self.style.reach_factor()
|
||||
}
|
||||
/// The stroke `t` of the way to `o` (shape tweens): colour, width and profile blend.
|
||||
/// The stroke of a shape scaled by `k` (mean scale): the width and the dashes scale.
|
||||
pub fn scaled(&self, k: f32) -> Stroke {
|
||||
Stroke { width: self.width * k, style: self.style.scaled(k), ..self.clone() }
|
||||
}
|
||||
/// The stroke `t` of the way to `o` (shape tweens): colour, width, profile and style blend.
|
||||
pub fn lerp(&self, o: &Stroke, t: f32) -> Stroke {
|
||||
Stroke { color: self.color.lerp(o.color, t), width: anicraft_geom::lerp(self.width, o.width, t), profile: WidthProfile::lerp(self.profile.as_ref(), o.profile.as_ref(), t) }
|
||||
Stroke {
|
||||
color: self.color.lerp(o.color, t),
|
||||
width: anicraft_geom::lerp(self.width, o.width, t),
|
||||
profile: WidthProfile::lerp(self.profile.as_ref(), o.profile.as_ref(), t),
|
||||
style: self.style.lerp(&o.style, t),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -586,17 +611,20 @@ pub struct Keyframe {
|
||||
/// script (ADR 0024). Rendering and exports ignore it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub script: Option<FrameScript>,
|
||||
/// On an armature layer: the joint angles this keyframe poses the armature with (ADR 0043).
|
||||
#[serde(default, skip_serializing_if = "Pose::is_empty")]
|
||||
pub pose: Pose,
|
||||
}
|
||||
|
||||
impl PartialEq for Keyframe {
|
||||
fn eq(&self, o: &Keyframe) -> bool {
|
||||
self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.hints == o.hints && self.label == o.label && self.sound == o.sound && self.script == o.script && arcs_eq(&self.elements, &o.elements)
|
||||
self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.hints == o.hints && self.label == o.label && self.sound == o.sound && self.script == o.script && self.pose == o.pose && arcs_eq(&self.elements, &o.elements)
|
||||
}
|
||||
}
|
||||
|
||||
impl Keyframe {
|
||||
pub fn new(start: u32, duration: u32) -> Self {
|
||||
Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, hints: Vec::new(), label: String::new(), sound: None, script: None }
|
||||
Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, hints: Vec::new(), label: String::new(), sound: None, script: None, pose: Pose::default() }
|
||||
}
|
||||
/// Mutable access to the elements whose ids satisfy `pick`, cloning only those.
|
||||
pub fn elements_mut_where(&mut self, mut pick: impl FnMut(ElementId) -> bool) -> Vec<&mut Element> {
|
||||
@@ -625,6 +653,9 @@ pub enum LayerKind {
|
||||
/// The camera (ADR 0027): at most one per scene timeline, always the top layer; its
|
||||
/// keyframes hold the camera, which views every other layer. Draws nothing itself.
|
||||
Camera,
|
||||
/// An armature (ADR 0043): symbol instances joined by bones ([`Layer::armature`]), posed
|
||||
/// on each keyframe ([`Keyframe::pose`]) and tweened between poses.
|
||||
Armature,
|
||||
}
|
||||
|
||||
/// Deepest nesting of folders (and a mask inside them) that is kept.
|
||||
@@ -662,6 +693,9 @@ pub struct Layer {
|
||||
/// The layer's sounds are silent (in playback and every export).
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub muted: bool,
|
||||
/// An armature layer's bones (ADR 0043); `None` on every other kind of layer.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub armature: Option<Arc<Armature>>,
|
||||
}
|
||||
|
||||
fn is_zero(v: &f32) -> bool {
|
||||
@@ -687,6 +721,10 @@ impl PartialEq for Layer {
|
||||
&& self.depth.to_bits() == o.depth.to_bits()
|
||||
&& self.volume.to_bits() == o.volume.to_bits()
|
||||
&& self.muted == o.muted
|
||||
&& match (&self.armature, &o.armature) {
|
||||
(Some(a), Some(b)) => arc_eq(a, b),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
}
|
||||
&& arcs_eq(&self.keyframes, &o.keyframes)
|
||||
}
|
||||
}
|
||||
@@ -713,6 +751,7 @@ impl Layer {
|
||||
depth: 0.0,
|
||||
volume: 1.0,
|
||||
muted: false,
|
||||
armature: None,
|
||||
}
|
||||
}
|
||||
/// The gain this layer gives its sounds: its volume, or silence when muted.
|
||||
@@ -1185,6 +1224,9 @@ impl Document {
|
||||
let mut max_id = 0u64;
|
||||
let scan = |l: &Layer, max_id: &mut u64| {
|
||||
*max_id = (*max_id).max(l.id.0);
|
||||
for b in l.armature.iter().flat_map(|a| &a.bones) {
|
||||
*max_id = (*max_id).max(b.id.0);
|
||||
}
|
||||
for k in &l.keyframes {
|
||||
for e in &k.elements {
|
||||
*max_id = (*max_id).max(e.id.0);
|
||||
@@ -1204,6 +1246,7 @@ impl Document {
|
||||
Arc::make_mut(l).normalize();
|
||||
sanitize_scripts(l);
|
||||
sanitize_depth(l);
|
||||
sanitize_armature(l);
|
||||
scan(l, &mut max_id);
|
||||
}
|
||||
tl.repair_masks();
|
||||
@@ -1226,6 +1269,7 @@ impl Document {
|
||||
Arc::make_mut(l).kind = LayerKind::Normal;
|
||||
}
|
||||
sanitize_depth(l);
|
||||
sanitize_armature(l);
|
||||
scan(l, &mut max_id);
|
||||
}
|
||||
tl.repair_masks();
|
||||
@@ -1248,6 +1292,36 @@ fn sanitize_depth(layer: &mut Arc<Layer>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Repairs a loaded layer's armature (ADR 0043): only an armature layer has one, its bones are
|
||||
/// sane and ordered, and its keyframes' poses are finite. Touches only what needs it.
|
||||
fn sanitize_armature(layer: &mut Arc<Layer>) {
|
||||
let is_armature = layer.kind == LayerKind::Armature;
|
||||
// (A pose on another layer's keyframe, pasted from an armature, is kept and plays no part.)
|
||||
if !is_armature {
|
||||
if layer.armature.is_some() {
|
||||
Arc::make_mut(layer).armature = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(a) = &layer.armature {
|
||||
let mut fixed = (**a).clone();
|
||||
if fixed.sanitize() {
|
||||
Arc::make_mut(layer).armature = Some(Arc::new(fixed));
|
||||
}
|
||||
}
|
||||
let bad = |k: &Keyframe| {
|
||||
let mut p = k.pose.clone();
|
||||
p.sanitize()
|
||||
};
|
||||
if layer.keyframes.iter().any(|k| bad(k)) {
|
||||
for k in &mut Arc::make_mut(layer).keyframes {
|
||||
if bad(k) {
|
||||
Arc::make_mut(k).pose.sanitize();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Repairs a loaded layer's frame scripts and instance event handlers (ADR 0024). Touches (and
|
||||
/// so un-shares) only keyframes that need it.
|
||||
fn sanitize_scripts(layer: &mut Arc<Layer>) {
|
||||
|
||||
@@ -13,8 +13,16 @@
|
||||
//! *when* it gets where: the share of the way along the path at a frame is the share of the
|
||||
//! distance the X/Y curves have covered by then. With *orient to path* the object also turns
|
||||
//! as the path turns. Without a path the X/Y curves place the object, as before.
|
||||
//!
|
||||
//! Anchors of the path may be *pinned* to frames (ADR 0049): the object passes a pinned anchor
|
||||
//! exactly on its frame, and the X/Y keys there hold the anchor's place. The ends are always
|
||||
//! pinned, to the first and last position keys. Pins cut the motion into legs; on each leg the
|
||||
//! X/Y curves time the object along the stretch of path between its two pinned anchors, as they
|
||||
//! time the whole path when only the ends are pinned. Anchors that aren't pinned shape the path
|
||||
//! only.
|
||||
|
||||
use crate::{Element, ElementId, Easing};
|
||||
use anicraft_geom::edit::ANCHOR;
|
||||
use anicraft_geom::walk::CurveWalk;
|
||||
use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -258,6 +266,36 @@ impl Track {
|
||||
}
|
||||
}
|
||||
|
||||
/// A motion path anchor pinned to a frame (ADR 0049): the object passes the anchor exactly
|
||||
/// then. Only anchors between the ends are stored; the ends are pinned to the first and last
|
||||
/// position keys.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Pin {
|
||||
/// Frames from the span's first frame.
|
||||
pub frame: u32,
|
||||
/// The anchor: path command `anchor` (0 is the start).
|
||||
pub anchor: u32,
|
||||
}
|
||||
|
||||
/// Why an anchor can't be pinned (or a pin added) where asked.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PinError {
|
||||
/// The tween has no motion path.
|
||||
NoPath,
|
||||
/// No such anchor on the path.
|
||||
NoAnchor,
|
||||
/// An end: always pinned to the first or last position key.
|
||||
End,
|
||||
/// The frame isn't strictly between the first and last position keys (these frames).
|
||||
Outside(u32, u32),
|
||||
/// Pins keep the path's order (a later frame on a later anchor); this one is in the way.
|
||||
Order(Pin),
|
||||
/// The object is off the path at that frame (an ease overshooting an end).
|
||||
OffPath,
|
||||
/// The path holds as many segments as it may.
|
||||
Full,
|
||||
}
|
||||
|
||||
/// A motion tween on a keyframe span (see the module docs).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MotionTween {
|
||||
@@ -275,6 +313,10 @@ pub struct MotionTween {
|
||||
/// Orient to path: the object turns as the path turns (relative to its turn at the start).
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub orient: bool,
|
||||
/// Anchors between the ends pinned to frames (ADR 0049), by frame; both frames and anchors
|
||||
/// increase. Files from before pins have none: only the ends are pinned.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub pins: Vec<Pin>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
@@ -350,6 +392,9 @@ pub struct OnPath<'a> {
|
||||
keys: Vec<(f32, Vec2)>,
|
||||
/// `cum[i]`: chord length from the first position key to key `i`.
|
||||
cum: Vec<f32>,
|
||||
/// Where the legs start and end: the first position key, each pin and the last position key,
|
||||
/// as an index into `keys` and the distance along the path of the anchor pinned there.
|
||||
stations: Vec<(usize, f32)>,
|
||||
/// Direction of travel at the start, radians.
|
||||
start_angle: f32,
|
||||
}
|
||||
@@ -359,34 +404,46 @@ impl OnPath<'_> {
|
||||
&self.walk
|
||||
}
|
||||
|
||||
/// The share of the path covered `frame` frames into the span: 0 up to the first position
|
||||
/// key (and without two), 1 from the last; an overshooting ease may leave 0..1 in between.
|
||||
/// Where the chords add up to nothing (a path back to its start) the object keeps an even
|
||||
/// pace between the first and last position keys.
|
||||
/// The share of the path covered `frame` frames into the span (see [`OnPath::distance`]).
|
||||
pub fn progress(&self, frame: f32) -> f32 {
|
||||
let l = self.walk.length();
|
||||
if l > 0.0 { self.distance(frame) / l } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Distance along the path at `frame`: 0 up to the first position key (and without two), the
|
||||
/// whole length from the last; an overshooting ease may go beyond in between.
|
||||
///
|
||||
/// The pins cut the span into legs, each from one pinned anchor to the next. On a leg, the
|
||||
/// position keys inside it split it again; on each of those pieces the X/Y curves run from
|
||||
/// one key's position to the next, and how far along that chord they are (signed) is how far
|
||||
/// along the piece's share of the leg's stretch of path the object is, the shares being the
|
||||
/// chords' lengths. Where a leg's chords add up to nothing (a loop) the object keeps an even
|
||||
/// pace across it. With only the ends pinned this is ADR 0030's timing, number for number.
|
||||
pub fn distance(&self, frame: f32) -> f32 {
|
||||
let l = self.walk.length();
|
||||
let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else { return 0.0 };
|
||||
if !frame.is_finite() || frame <= first.0 || last.0 <= first.0 {
|
||||
return 0.0;
|
||||
}
|
||||
if frame >= last.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let total = self.cum.last().copied().unwrap_or(0.0);
|
||||
if total <= 1e-4 {
|
||||
return (frame - first.0) / (last.0 - first.0);
|
||||
return l;
|
||||
}
|
||||
let i = self.keys.partition_point(|k| k.0 <= frame).saturating_sub(1);
|
||||
let (Some(a), Some(b)) = (self.keys.get(i), self.keys.get(i + 1)) else { return 1.0 };
|
||||
let chord = b.1 - a.1;
|
||||
let len = chord.length();
|
||||
let along = if len > 1e-6 { (self.tween.trace_at(&self.base, frame) - a.1).dot(chord) / len } else { 0.0 };
|
||||
let p = (self.cum.get(i).copied().unwrap_or(0.0) + along) / total;
|
||||
if p.is_finite() { p } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Distance along the path at `frame` (beyond the ends while an ease overshoots them).
|
||||
pub fn distance(&self, frame: f32) -> f32 {
|
||||
self.progress(frame) * self.walk.length()
|
||||
let leg = self.stations.partition_point(|st| st.0 <= i).saturating_sub(1);
|
||||
let (Some(&(ka, sa)), Some(&(kb, sb))) = (self.stations.get(leg), self.stations.get(leg + 1)) else { return l };
|
||||
let (Some(a), Some(b), Some(fa), Some(fb)) = (self.keys.get(i), self.keys.get(i + 1), self.keys.get(ka), self.keys.get(kb)) else { return l };
|
||||
let c0 = self.cum.get(ka).copied().unwrap_or(0.0);
|
||||
let total = self.cum.get(kb).copied().unwrap_or(0.0) - c0;
|
||||
let p = if total <= 1e-4 {
|
||||
(frame - fa.0) / (fb.0 - fa.0)
|
||||
} else {
|
||||
let chord = b.1 - a.1;
|
||||
let len = chord.length();
|
||||
let along = if len > 1e-6 { (self.tween.trace_at(&self.base, frame) - a.1).dot(chord) / len } else { 0.0 };
|
||||
(self.cum.get(i).copied().unwrap_or(0.0) - c0 + along) / total
|
||||
};
|
||||
let p = if p.is_finite() { p } else { 0.0 };
|
||||
sa + p * (sb - sa)
|
||||
}
|
||||
|
||||
/// The registration point at `frame`. Overshooting an end carries on along the path's
|
||||
@@ -414,7 +471,7 @@ impl OnPath<'_> {
|
||||
|
||||
impl MotionTween {
|
||||
pub fn new(target: ElementId) -> MotionTween {
|
||||
MotionTween { target, tracks: Vec::new(), path: None, orient: false }
|
||||
MotionTween { target, tracks: Vec::new(), path: None, orient: false, pins: Vec::new() }
|
||||
}
|
||||
|
||||
/// The first and last frames holding an X or Y key.
|
||||
@@ -433,18 +490,32 @@ impl MotionTween {
|
||||
/// path.
|
||||
pub fn on_path(&self, base: &Props) -> Option<OnPath<'_>> {
|
||||
let walk = CurveWalk::new(self.path.as_ref()?)?;
|
||||
let pins = self.live_pins();
|
||||
let mut frames: Vec<u32> = [Property::X, Property::Y].into_iter().filter_map(|p| self.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect();
|
||||
// A pin's frame holds X/Y keys (commands see to it); a leg ends there all the same.
|
||||
frames.extend(pins.iter().map(|p| p.frame));
|
||||
frames.sort_unstable();
|
||||
frames.dedup();
|
||||
let keys: Vec<(f32, Vec2)> = frames.into_iter().map(|f| (f as f32, self.trace_at(base, f as f32))).collect();
|
||||
let keys: Vec<(f32, Vec2)> = frames.iter().map(|&f| (f as f32, self.trace_at(base, f as f32))).collect();
|
||||
let mut cum = Vec::with_capacity(keys.len());
|
||||
let mut d = 0.0f32;
|
||||
for (i, k) in keys.iter().enumerate() {
|
||||
d += i.checked_sub(1).and_then(|p| keys.get(p)).map_or(0.0, |p| p.1.distance(k.1));
|
||||
cum.push(d);
|
||||
}
|
||||
let mut stations = vec![(0usize, 0.0f32)];
|
||||
for pin in &pins {
|
||||
if let (Ok(i), Some(s)) = (frames.binary_search(&pin.frame), walk.anchor_distance(pin.anchor as usize))
|
||||
&& stations.last().is_some_and(|l| l.0 < i)
|
||||
{
|
||||
stations.push((i, s));
|
||||
}
|
||||
}
|
||||
if keys.len() > 1 {
|
||||
stations.push((keys.len() - 1, walk.length()));
|
||||
}
|
||||
let t = walk.tangent(0.0);
|
||||
Some(OnPath { tween: self, base: *base, start_angle: t.y.atan2(t.x), walk, keys, cum })
|
||||
Some(OnPath { tween: self, base: *base, start_angle: t.y.atan2(t.x), walk, keys, cum, stations })
|
||||
}
|
||||
|
||||
/// The registration point on each of the span's first `frames` frames (at most a day of
|
||||
@@ -460,13 +531,21 @@ impl MotionTween {
|
||||
/// A motion path through the X/Y curves' positions at their keys, as straight segments:
|
||||
/// the path a tween without one shows, made editable. `None` when the object doesn't move.
|
||||
pub fn path_from_tracks(&self, base: &Props) -> Option<Path> {
|
||||
self.path_and_pins_from_tracks(base).map(|(p, _)| p)
|
||||
}
|
||||
|
||||
/// [`MotionTween::path_from_tracks`] with the position keys between the ends pinned to the
|
||||
/// anchors they made (the first key at a place, where the object holds still a while).
|
||||
pub fn path_and_pins_from_tracks(&self, base: &Props) -> Option<(Path, Vec<Pin>)> {
|
||||
let mut frames: Vec<u32> = [Property::X, Property::Y].into_iter().filter_map(|p| self.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect();
|
||||
frames.sort_unstable();
|
||||
frames.dedup();
|
||||
let mut pts: Vec<Vec2> = Vec::new();
|
||||
let mut pins = Vec::new();
|
||||
for f in frames.into_iter().take(MAX_PATH_SEGMENTS + 1) {
|
||||
let q = self.trace_at(base, f as f32);
|
||||
if pts.last().is_none_or(|l| l.distance(q) > 1e-3) {
|
||||
pins.push(Pin { frame: f, anchor: pts.len() as u32 });
|
||||
pts.push(q);
|
||||
}
|
||||
}
|
||||
@@ -476,16 +555,64 @@ impl MotionTween {
|
||||
for q in rest {
|
||||
p.line_to(*q);
|
||||
}
|
||||
motion_path(&p)
|
||||
let path = motion_path(&p)?;
|
||||
let n = path.cmds.len();
|
||||
pins.retain(|p| p.anchor > 0 && (p.anchor as usize) + 1 < n);
|
||||
Some((path, pins))
|
||||
}
|
||||
|
||||
/// The pins in force: between the ends in both frame and anchor, frames and anchors
|
||||
/// increasing. Others are ignored (and dropped when a file is loaded).
|
||||
pub fn live_pins(&self) -> Vec<Pin> {
|
||||
let (Some(path), Some((f0, f1))) = (&self.path, self.position_range()) else { return Vec::new() };
|
||||
let n = path.cmds.len();
|
||||
let mut out: Vec<Pin> = Vec::new();
|
||||
for p in &self.pins {
|
||||
let inside = p.frame > f0 && p.frame < f1 && p.anchor > 0 && (p.anchor as usize).saturating_add(1) < n;
|
||||
if inside && out.last().is_none_or(|q| q.frame < p.frame && q.anchor < p.anchor) {
|
||||
out.push(*p);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every anchor tied to a frame, in order: the start at the first position key, the pins,
|
||||
/// and the end at the last. A tween without a path of its own gives those of the straight
|
||||
/// path its X/Y curves trace. Empty while the object doesn't move.
|
||||
pub fn pinned_anchors(&self, base: &Props) -> Vec<Pin> {
|
||||
let Some((f0, f1)) = self.position_range().filter(|(a, b)| b > a) else { return Vec::new() };
|
||||
let (n, pins) = match &self.path {
|
||||
Some(p) => (p.cmds.len(), self.live_pins()),
|
||||
None => match self.path_and_pins_from_tracks(base) {
|
||||
Some((p, pins)) => (p.cmds.len(), pins),
|
||||
None => return Vec::new(),
|
||||
},
|
||||
};
|
||||
let mut v = Vec::with_capacity(pins.len() + 2);
|
||||
v.push(Pin { frame: f0, anchor: 0 });
|
||||
v.extend(pins);
|
||||
v.push(Pin { frame: f1, anchor: n.saturating_sub(1) as u32 });
|
||||
v
|
||||
}
|
||||
|
||||
/// Gives the tween motion path `path` (made a [`motion_path`]; false when nothing usable
|
||||
/// is left). Its ends become the X/Y keys at the first and last position keys, or at the
|
||||
/// span's first frame and frame `last` when there are none, so the curves start and end
|
||||
/// where the path does.
|
||||
/// where the path does; each pinned anchor's place becomes the X/Y keys on its frame.
|
||||
///
|
||||
/// A tween without a path of its own shows the straight one through its position keys,
|
||||
/// which are pinned to its anchors: a path with as many anchors is that one edited, and
|
||||
/// keeps them pinned. Pins on anchors the new path doesn't have are let go, with their keys.
|
||||
pub fn set_path(&mut self, path: &Path, base: &Props, last: u32) -> bool {
|
||||
let Some(p) = motion_path(path) else { return false };
|
||||
let Some((a, b)) = path_ends(&p) else { return false };
|
||||
if self.path.is_none()
|
||||
&& self.pins.is_empty()
|
||||
&& let Some((implied, pins)) = self.path_and_pins_from_tracks(base)
|
||||
&& implied.cmds.len() == p.cmds.len()
|
||||
{
|
||||
self.pins = pins;
|
||||
}
|
||||
let (f0, f1) = match self.position_range() {
|
||||
Some((f0, f1)) if f1 > f0 => (f0, f1),
|
||||
_ if last > 0 => (0, last),
|
||||
@@ -501,7 +628,184 @@ impl MotionTween {
|
||||
self.set_key(prop, f1, v1, base.get(prop));
|
||||
}
|
||||
}
|
||||
let n = p.cmds.len();
|
||||
self.path = Some(p);
|
||||
let (keep, gone): (Vec<Pin>, Vec<Pin>) = self.pins.iter().partition(|q| q.anchor > 0 && (q.anchor as usize).saturating_add(1) < n);
|
||||
self.pins = keep;
|
||||
for q in gone {
|
||||
self.remove_pin_keys(q.frame);
|
||||
}
|
||||
self.sync_pins(base);
|
||||
true
|
||||
}
|
||||
|
||||
/// Writes each pinned anchor's place as the X/Y keys on its frame (leaving keys alone that
|
||||
/// already hold it, so editing elsewhere keeps the timing exactly).
|
||||
fn sync_pins(&mut self, base: &Props) {
|
||||
let Some(path) = self.path.clone() else { return };
|
||||
for pin in self.live_pins() {
|
||||
let Some(q) = path.point(pin.anchor as usize, ANCHOR) else { continue };
|
||||
for (prop, v) in [(Property::X, q.x), (Property::Y, q.y)] {
|
||||
let holds = self.track(prop).and_then(|t| t.key_at(pin.frame).and_then(|i| t.keys.get(i))).is_some_and(|k| k.value == v);
|
||||
if !holds {
|
||||
self.set_key(prop, pin.frame, v, base.get(prop));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the X/Y keys a pin held on `frame`, unless that frame is an end's.
|
||||
fn remove_pin_keys(&mut self, frame: u32) {
|
||||
if self.position_range().is_some_and(|(f0, f1)| f0 < frame && frame < f1) {
|
||||
self.remove_track_key(Property::X, frame);
|
||||
self.remove_track_key(Property::Y, frame);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins anchor `anchor` to `frame`: the object passes it exactly then, and the X/Y keys on
|
||||
/// that frame hold its place. A pin already on that frame, or that anchor's pin on another
|
||||
/// frame, gives way.
|
||||
pub fn pin(&mut self, anchor: usize, frame: u32, base: &Props) -> Result<(), PinError> {
|
||||
let Some(path) = &self.path else { return Err(PinError::NoPath) };
|
||||
let n = path.cmds.len();
|
||||
if anchor >= n {
|
||||
return Err(PinError::NoAnchor);
|
||||
}
|
||||
if anchor == 0 || anchor + 1 == n {
|
||||
return Err(PinError::End);
|
||||
}
|
||||
let (f0, f1) = self.position_range().unwrap_or((0, 0));
|
||||
if !(f0 < frame && frame < f1) {
|
||||
return Err(PinError::Outside(f0, f1));
|
||||
}
|
||||
let Some(q) = path.point(anchor, ANCHOR) else { return Err(PinError::NoAnchor) };
|
||||
let a = anchor as u32;
|
||||
let live = self.live_pins();
|
||||
if let Some(p) = live.iter().find(|p| p.frame != frame && p.anchor != a && (p.frame < frame) != (p.anchor < a)) {
|
||||
return Err(PinError::Order(*p));
|
||||
}
|
||||
self.pins = live;
|
||||
if let Some(old) = self.pins.iter().find(|p| p.anchor == a && p.frame != frame).copied() {
|
||||
self.unpin(old.frame);
|
||||
}
|
||||
self.pins.retain(|p| p.frame != frame);
|
||||
let i = self.pins.partition_point(|p| p.frame < frame);
|
||||
self.pins.insert(i, Pin { frame, anchor: a });
|
||||
for (prop, v) in [(Property::X, q.x), (Property::Y, q.y)] {
|
||||
self.set_key(prop, frame, v, base.get(prop));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pins the path where the object is on `frame`: on the anchor there, or on a new one (the
|
||||
/// path's shape unchanged). The anchor pinned.
|
||||
pub fn pin_here(&mut self, frame: u32, base: &Props) -> Result<usize, PinError> {
|
||||
if self.path.is_none() {
|
||||
return Err(PinError::NoPath);
|
||||
}
|
||||
let (f0, f1) = self.position_range().unwrap_or((0, 0));
|
||||
if !(f0 < frame && frame < f1) {
|
||||
return Err(PinError::Outside(f0, f1));
|
||||
}
|
||||
if let Some(p) = self.live_pins().into_iter().find(|p| p.frame == frame) {
|
||||
return Ok(p.anchor as usize);
|
||||
}
|
||||
let (s, l, (cmd, t)) = {
|
||||
let op = self.on_path(base).ok_or(PinError::NoPath)?;
|
||||
let s = op.distance(frame as f32);
|
||||
(s, op.walk().length(), op.walk().locate(s))
|
||||
};
|
||||
if !(0.0..=l).contains(&s) {
|
||||
return Err(PinError::OffPath);
|
||||
}
|
||||
let mut trial = self.clone();
|
||||
let anchor = if t <= 1e-3 {
|
||||
cmd.saturating_sub(1)
|
||||
} else if t >= 1.0 - 1e-3 {
|
||||
cmd
|
||||
} else {
|
||||
if self.path.as_ref().is_some_and(|p| p.cmds.len() > MAX_PATH_SEGMENTS) {
|
||||
return Err(PinError::Full);
|
||||
}
|
||||
if !trial.split_path(cmd, t) {
|
||||
return Err(PinError::OffPath);
|
||||
}
|
||||
cmd
|
||||
};
|
||||
trial.pin(anchor, frame, base)?;
|
||||
*self = trial;
|
||||
Ok(anchor)
|
||||
}
|
||||
|
||||
/// Splits the path's segment `cmd` at curve parameter `t` (the curve unchanged; the new
|
||||
/// anchor is `cmd`). Pins after it stay on their anchors. False when there is no such
|
||||
/// segment.
|
||||
pub fn split_path(&mut self, cmd: usize, t: f32) -> bool {
|
||||
let Some(path) = self.path.as_mut() else { return false };
|
||||
if !path.split_segment(cmd, t) {
|
||||
return false;
|
||||
}
|
||||
for p in &mut self.pins {
|
||||
if p.anchor as usize >= cmd {
|
||||
p.anchor = p.anchor.saturating_add(1);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Deletes anchor `i` between the ends, refitting the two segments around it as one
|
||||
/// ([`Path::merge_at`]). A pin on it goes, with its keys; later pins stay on their anchors.
|
||||
/// False when it can't be deleted (an end, or no such anchor).
|
||||
pub fn delete_anchor(&mut self, i: usize) -> bool {
|
||||
let Some(path) = self.path.as_mut() else { return false };
|
||||
if !path.merge_at(i) {
|
||||
return false;
|
||||
}
|
||||
if let Some(frame) = self.pins.iter().find(|p| p.anchor as usize == i).map(|p| p.frame) {
|
||||
self.unpin(frame);
|
||||
}
|
||||
for p in &mut self.pins {
|
||||
if p.anchor as usize > i {
|
||||
p.anchor -= 1;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Lets the pin on `frame` go: its X/Y keys go with it and its anchor shapes the path only
|
||||
/// (ADR 0038's behaviour). The pin, if there was one.
|
||||
pub fn unpin(&mut self, frame: u32) -> Option<Pin> {
|
||||
let i = self.pins.iter().position(|p| p.frame == frame)?;
|
||||
let pin = self.pins.remove(i);
|
||||
self.remove_pin_keys(frame);
|
||||
Some(pin)
|
||||
}
|
||||
|
||||
/// Moves anchor `anchor` (its handles with it) by `d`; an end or a pin takes its keys along.
|
||||
pub fn move_anchor(&mut self, anchor: usize, d: Vec2, base: &Props, last: u32) -> bool {
|
||||
let Some(mut path) = self.path.clone() else { return false };
|
||||
path.move_anchor(anchor, d) && self.set_path(&path, base, last)
|
||||
}
|
||||
|
||||
/// Carries the path on from its end to `to`, reached on `frame` after the last position key:
|
||||
/// the old end stays pinned to its frame and the new straight stretch ends the motion. False
|
||||
/// (nothing changed) when the path is full or `frame` isn't after the last position key.
|
||||
pub fn extend_to(&mut self, frame: u32, to: Vec2, base: &Props) -> bool {
|
||||
let (Some(path), Some((f0, f1))) = (&self.path, self.position_range()) else { return false };
|
||||
if frame <= f1 || f1 <= f0 || path.cmds.len() > MAX_PATH_SEGMENTS {
|
||||
return false;
|
||||
}
|
||||
let n = path.cmds.len();
|
||||
let mut longer = path.clone();
|
||||
longer.line_to(to);
|
||||
let Some(longer) = motion_path(&longer).filter(|p| p.cmds.len() == n + 1) else { return false };
|
||||
let mut pins = self.live_pins();
|
||||
pins.push(Pin { frame: f1, anchor: (n - 1) as u32 });
|
||||
self.set_key(Property::X, frame, to.x, base.get(Property::X));
|
||||
self.set_key(Property::Y, frame, to.y, base.get(Property::Y));
|
||||
self.path = Some(longer);
|
||||
self.pins = pins;
|
||||
self.sync_pins(base);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -614,8 +918,25 @@ impl MotionTween {
|
||||
}
|
||||
|
||||
/// Removes property `p`'s key at `frame`; a track left with no keys goes. Whether a key was
|
||||
/// there.
|
||||
/// there. Removing the X or Y key of a pinned frame lets the pin go (with both keys).
|
||||
pub fn remove_key(&mut self, p: Property, frame: u32) -> bool {
|
||||
if !matches!(p, Property::X | Property::Y) {
|
||||
return self.remove_track_key(p, frame);
|
||||
}
|
||||
// Only pins in force count (removing an end's keys can leave one outside the motion).
|
||||
self.pins = self.live_pins();
|
||||
if self.pins.iter().any(|q| q.frame == frame) {
|
||||
let had = self.track(p).is_some_and(|t| t.key_at(frame).is_some());
|
||||
self.unpin(frame);
|
||||
return had;
|
||||
}
|
||||
let had = self.remove_track_key(p, frame);
|
||||
// An end's key gone may leave pins outside the motion: they go, never to come back.
|
||||
self.pins = self.live_pins();
|
||||
had
|
||||
}
|
||||
|
||||
fn remove_track_key(&mut self, p: Property, frame: u32) -> bool {
|
||||
let Some(t) = self.track_mut(p) else { return false };
|
||||
let Some(i) = t.key_at(frame) else { return false };
|
||||
t.keys.remove(i);
|
||||
@@ -647,12 +968,17 @@ impl MotionTween {
|
||||
Some(Track { property: t.property, keys })
|
||||
})
|
||||
.collect();
|
||||
let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient };
|
||||
let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new() };
|
||||
let Some(op) = self.on_path(base) else { return tail };
|
||||
let f = frame as f32;
|
||||
match op.walk().tail(op.distance(f)) {
|
||||
// The cut path starts where the object is; the X/Y keys go on timing it.
|
||||
Some(p) => tail.path = Some(p),
|
||||
// The cut path starts where the object is; the X/Y keys go on timing it, and the
|
||||
// pins after the cut stay on their anchors (the cut segment's end is anchor 1).
|
||||
Some(p) => {
|
||||
let (cmd, _) = op.walk().locate(op.distance(f));
|
||||
tail.pins = self.live_pins().into_iter().filter(|q| q.frame > frame && q.anchor as usize >= cmd).map(|q| Pin { frame: q.frame - frame, anchor: q.anchor + 1 - cmd as u32 }).collect();
|
||||
tail.path = Some(p);
|
||||
}
|
||||
// Past the path's end: the object holds where the path ended.
|
||||
None => {
|
||||
let p = op.point(f);
|
||||
@@ -677,6 +1003,7 @@ impl MotionTween {
|
||||
/// duplicate or empty tracks).
|
||||
pub fn is_sane(&self) -> bool {
|
||||
self.path.as_ref().is_none_or(|p| motion_path(p).as_ref() == Some(p))
|
||||
&& self.pins == self.live_pins()
|
||||
&& self.tracks.iter().all(|t| !t.keys.is_empty() && t.is_sane()) && self.tracks.windows(2).all(|w| matches!(w, [a, b] if a.property.index() < b.property.index()))
|
||||
}
|
||||
|
||||
@@ -689,6 +1016,10 @@ impl MotionTween {
|
||||
self.tracks.retain(|t| !t.keys.is_empty());
|
||||
self.tracks.sort_by_key(|t| t.property.index());
|
||||
self.tracks.dedup_by_key(|t| t.property);
|
||||
self.pins.truncate(MAX_PATH_SEGMENTS);
|
||||
self.pins.sort_by_key(|p| p.frame);
|
||||
self.pins.dedup_by_key(|p| p.frame);
|
||||
self.pins = self.live_pins();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1051,4 +1382,274 @@ mod tests {
|
||||
m.sanitize();
|
||||
assert!(m.path.is_none());
|
||||
}
|
||||
|
||||
// ----- anchors pinned to frames (ADR 0049) ----------------------------------------------
|
||||
|
||||
/// An S through three anchors: (0, 0), (100, 0) and (200, 0), over a hump and under a dip.
|
||||
fn s_path() -> Path {
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(40.0, -60.0), Vec2::new(60.0, -60.0), Vec2::new(100.0, 0.0)).cubic_to(Vec2::new(140.0, 60.0), Vec2::new(160.0, 60.0), Vec2::new(200.0, 0.0));
|
||||
p
|
||||
}
|
||||
|
||||
/// X 0 → 200 over frames 0..20 with `ease`, Y still: the S travelled left to right.
|
||||
fn along_s(ease: Easing) -> (MotionTween, Element) {
|
||||
let base = el(1, 0.0, 0.0);
|
||||
let mut m = MotionTween::new(ElementId(1));
|
||||
m.tracks = vec![track(Property::X, &[(0, 0.0, ease), (20, 200.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, Easing::Linear), (20, 0.0, Easing::Linear)])];
|
||||
assert!(m.set_path(&s_path(), &Props::of(&base), 20));
|
||||
(m, base)
|
||||
}
|
||||
|
||||
fn anchor_at(m: &MotionTween, i: usize) -> Vec2 {
|
||||
m.path.as_ref().and_then(|p| p.point(i, ANCHOR)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_object_passes_each_pinned_anchor_on_its_frame() {
|
||||
let (mut m, base) = along_s(Easing::QuadIn);
|
||||
let props = Props::of(&base);
|
||||
assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) > 10.0, "unpinned, the middle anchor is passed when the timing says");
|
||||
assert_eq!(m.pin(1, 6, &props), Ok(()));
|
||||
assert_eq!(m.pins, vec![Pin { frame: 6, anchor: 1 }]);
|
||||
assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) < 1e-3, "{:?}", at(&m, &base, 6.0));
|
||||
assert!(at(&m, &base, 0.0).distance(Vec2::ZERO) < 1e-3 && at(&m, &base, 20.0).distance(Vec2::new(200.0, 0.0)) < 1e-3, "the ends stay pinned");
|
||||
// Pinning where the object is adds an anchor there and moves nothing on that frame.
|
||||
let was = at(&m, &base, 14.0);
|
||||
assert_eq!(m.pin_here(14, &props), Ok(2));
|
||||
assert_eq!(m.path.as_ref().map(|p| p.cmds.len()), Some(4));
|
||||
assert_eq!(m.pins, vec![Pin { frame: 6, anchor: 1 }, Pin { frame: 14, anchor: 2 }]);
|
||||
assert!(at(&m, &base, 14.0).distance(was) < 0.01, "{:?} vs {was:?}", at(&m, &base, 14.0));
|
||||
assert_eq!(m.pin_here(14, &props), Ok(2), "already pinned there");
|
||||
// Moving a pinned anchor takes the object with it on that frame, and its keys follow.
|
||||
assert!(m.move_anchor(2, Vec2::new(0.0, 50.0), &props, 20));
|
||||
let a2 = anchor_at(&m, 2);
|
||||
assert!(at(&m, &base, 14.0).distance(a2) < 1e-3);
|
||||
assert_eq!(m.track(Property::Y).and_then(|t| t.key_at(14).map(|i| t.keys[i].value)), Some(a2.y));
|
||||
assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) < 1e-3, "the other pin holds");
|
||||
// What can't be pinned says why, and changes nothing.
|
||||
let before = m.clone();
|
||||
assert_eq!(m.pin(1, 16, &props), Err(PinError::Order(Pin { frame: 14, anchor: 2 })));
|
||||
assert_eq!(m.pin(0, 5, &props), Err(PinError::End));
|
||||
assert_eq!(m.pin(3, 5, &props), Err(PinError::End));
|
||||
assert_eq!(m.pin(9, 5, &props), Err(PinError::NoAnchor));
|
||||
assert_eq!(m.pin(1, 25, &props), Err(PinError::Outside(0, 20)));
|
||||
assert_eq!(m.pin_here(0, &props), Err(PinError::Outside(0, 20)));
|
||||
assert_eq!(m, before);
|
||||
// Re-pinning an anchor to another frame retimes it.
|
||||
assert_eq!(m.pin(1, 4, &props), Ok(()));
|
||||
assert_eq!(m.pins, vec![Pin { frame: 4, anchor: 1 }, Pin { frame: 14, anchor: 2 }]);
|
||||
assert!(at(&m, &base, 4.0).distance(Vec2::new(100.0, 0.0)) < 1e-3);
|
||||
assert!(m.track(Property::X).is_some_and(|t| t.key_at(6).is_none()), "the old frame's keys went with the pin");
|
||||
assert!(m.is_sane());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn between_pins_the_eases_time_the_object_as_before() {
|
||||
// A straight path with an anchor at x = 30 pinned to frame 10: it reproduces the X curve
|
||||
// exactly, eases and overshoot included, on both legs.
|
||||
let base = el(1, 0.0, 0.0);
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(30.0, 0.0)).line_to(Vec2::new(100.0, 0.0));
|
||||
for second in [Easing::QuadIn, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3)] {
|
||||
let mut m = MotionTween::new(ElementId(1));
|
||||
m.tracks = vec![track(Property::X, &[(0, 0.0, Easing::QuadIn), (20, 100.0, Easing::Linear)])];
|
||||
assert!(m.set_path(&p, &Props::of(&base), 20));
|
||||
assert_eq!(m.pin(1, 10, &Props::of(&base)), Ok(()));
|
||||
if let Some(t) = m.track_mut(Property::X) {
|
||||
t.keys[1].ease = second;
|
||||
}
|
||||
let x = m.track(Property::X).cloned().unwrap();
|
||||
for i in 0..=80 {
|
||||
let f = i as f32 / 4.0;
|
||||
let q = at(&m, &base, f);
|
||||
assert!((q.x - x.value_at(f).unwrap()).abs() < 2e-3 && q.y.abs() < 1e-3, "{second:?} frame {f}: {q:?} vs {:?}", x.value_at(f));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpinning_gives_back_the_unpinned_motion() {
|
||||
let (m, base) = along_s(Easing::CubicOut);
|
||||
let props = Props::of(&base);
|
||||
let mut pinned = m.clone();
|
||||
assert_eq!(pinned.pin(1, 8, &props), Ok(()));
|
||||
assert!(at(&pinned, &base, 5.0).distance(at(&m, &base, 5.0)) > 1.0, "pinning retimes");
|
||||
assert_eq!(pinned.unpin(8), Some(Pin { frame: 8, anchor: 1 }));
|
||||
assert_eq!(pinned, m, "pin then unpin: the same tween, keys and all");
|
||||
assert_eq!(pinned.unpin(8), None);
|
||||
// A pin added where the object was leaves its anchor behind, shaping only: the motion
|
||||
// is ADR 0038's again (the split curve is the same curve).
|
||||
let mut here = m.clone();
|
||||
assert!(here.pin_here(12, &props).is_ok());
|
||||
assert!(here.unpin(12).is_some());
|
||||
assert_eq!(here.path.as_ref().map(|p| p.cmds.len()), Some(4));
|
||||
for f in 0..=20 {
|
||||
assert!(at(&here, &base, f as f32).distance(at(&m, &base, f as f32)) < 0.01, "frame {f}");
|
||||
}
|
||||
// Removing the X (or Y) key of a pinned frame lets the pin go, with both keys.
|
||||
assert_eq!(pinned.pin(1, 8, &props), Ok(()));
|
||||
assert!(pinned.remove_key(Property::X, 8));
|
||||
assert!(pinned.pins.is_empty() && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_none()));
|
||||
assert_eq!(pinned, m);
|
||||
// Removing the end's keys lets a pin that is no longer between the ends go; its keys
|
||||
// stay as plain keys, removed one by one.
|
||||
assert_eq!(pinned.pin(1, 8, &props), Ok(()));
|
||||
assert!(pinned.remove_key(Property::X, 20) && pinned.remove_key(Property::Y, 20));
|
||||
assert!(pinned.pins.is_empty(), "frame 8 is the last position key now: an end");
|
||||
assert!(pinned.remove_key(Property::X, 8));
|
||||
assert!(pinned.track(Property::X).is_some_and(|t| t.key_at(8).is_none()) && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_some()));
|
||||
assert!(pinned.is_sane());
|
||||
}
|
||||
|
||||
/// ADR 0030's timing as it was before pins: what files without pins must still give.
|
||||
fn legacy_point(m: &MotionTween, base: &Props, frame: f32) -> Vec2 {
|
||||
let walk = CurveWalk::new(m.path.as_ref().unwrap()).unwrap();
|
||||
let mut frames: Vec<u32> = [Property::X, Property::Y].into_iter().filter_map(|p| m.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect();
|
||||
frames.sort_unstable();
|
||||
frames.dedup();
|
||||
let keys: Vec<(f32, Vec2)> = frames.into_iter().map(|f| (f as f32, m.trace_at(base, f as f32))).collect();
|
||||
let mut cum = Vec::new();
|
||||
let mut d = 0.0f32;
|
||||
for (i, k) in keys.iter().enumerate() {
|
||||
d += i.checked_sub(1).and_then(|p| keys.get(p)).map_or(0.0, |p| p.1.distance(k.1));
|
||||
cum.push(d);
|
||||
}
|
||||
let progress = (|| {
|
||||
let (first, last) = (keys.first()?, keys.last()?);
|
||||
if !frame.is_finite() || frame <= first.0 || last.0 <= first.0 {
|
||||
return Some(0.0);
|
||||
}
|
||||
if frame >= last.0 {
|
||||
return Some(1.0);
|
||||
}
|
||||
let total = *cum.last()?;
|
||||
if total <= 1e-4 {
|
||||
return Some((frame - first.0) / (last.0 - first.0));
|
||||
}
|
||||
let i = keys.partition_point(|k| k.0 <= frame).saturating_sub(1);
|
||||
let (a, b) = (keys.get(i)?, keys.get(i + 1)?);
|
||||
let chord = b.1 - a.1;
|
||||
let len = chord.length();
|
||||
let along = if len > 1e-6 { (m.trace_at(base, frame) - a.1).dot(chord) / len } else { 0.0 };
|
||||
let p = (cum[i] + along) / total;
|
||||
Some(if p.is_finite() { p } else { 0.0 })
|
||||
})()
|
||||
.unwrap_or(1.0);
|
||||
let (s, l) = (progress * walk.length(), walk.length());
|
||||
if s < 0.0 {
|
||||
walk.at(0.0) + walk.tangent(0.0) * s
|
||||
} else if s > l {
|
||||
walk.at(l) + walk.tangent(l) * (s - l)
|
||||
} else {
|
||||
walk.at(s)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tweens_without_pins_evaluate_exactly_as_before() {
|
||||
let base = el(1, 0.0, 0.0);
|
||||
let props = Props::of(&base);
|
||||
let mut cases = Vec::new();
|
||||
for ease in [Easing::Linear, Easing::QuadOut, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3), Easing::CubicBezier(0.5, -0.6, 0.5, 1.6)] {
|
||||
let mut m = diagonal(ease);
|
||||
assert!(m.set_path(&quarter(100.0), &props, 20));
|
||||
cases.push(m.clone());
|
||||
// Position keys in the middle are timing keys, not pins, in ADR 0030 files.
|
||||
m.set_key(Property::Y, 8, 30.0, 0.0);
|
||||
m.set_key(Property::X, 13, 70.0, 0.0);
|
||||
cases.push(m.clone());
|
||||
let mut s = along_s(ease).0;
|
||||
s.set_key(Property::X, 5, 20.0, 0.0);
|
||||
cases.push(s);
|
||||
}
|
||||
let mut ring = Path::new();
|
||||
ring.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(40.0, 0.0)).line_to(Vec2::new(40.0, 40.0)).line_to(Vec2::new(0.0, 40.0)).close();
|
||||
let mut l = MotionTween::new(ElementId(1));
|
||||
assert!(l.set_path(&ring, &props, 16));
|
||||
cases.push(l);
|
||||
for m in &cases {
|
||||
assert!(m.pins.is_empty() && m.is_sane());
|
||||
let op = m.on_path(&props).unwrap();
|
||||
for i in -4..=120 {
|
||||
let f = i as f32 / 4.0;
|
||||
assert_eq!(op.point(f), legacy_point(m, &props, f), "frame {f}");
|
||||
}
|
||||
let json = serde_json::to_string(m).unwrap();
|
||||
assert!(!json.contains("pins"), "nothing new is written for them");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_made_from_the_tracks_keeps_their_keys_pinned() {
|
||||
// Right 100 over 10 frames, then down 100: no path yet, but an anchor at the corner.
|
||||
let base = el(1, 0.0, 0.0);
|
||||
let props = Props::of(&base);
|
||||
let mut m = MotionTween::new(ElementId(1));
|
||||
m.tracks = vec![track(Property::X, &[(0, 0.0, Easing::Linear), (10, 100.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, Easing::Linear), (10, 0.0, Easing::Linear), (20, 100.0, Easing::Linear)])];
|
||||
let (mut path, pins) = m.path_and_pins_from_tracks(&props).unwrap();
|
||||
assert_eq!(pins, vec![Pin { frame: 10, anchor: 1 }]);
|
||||
assert_eq!(m.pinned_anchors(&props), vec![Pin { frame: 0, anchor: 0 }, Pin { frame: 10, anchor: 1 }, Pin { frame: 20, anchor: 2 }], "shown pinned before it is a path");
|
||||
// Dragging the corner up edits that path: the corner stays pinned to frame 10.
|
||||
assert!(path.move_anchor(1, Vec2::new(0.0, -40.0)));
|
||||
assert!(m.set_path(&path, &props, 20));
|
||||
assert_eq!(m.pins, pins);
|
||||
assert!(at(&m, &base, 10.0).distance(Vec2::new(100.0, -40.0)) < 1e-3);
|
||||
// A path of another shape is a new path: only its ends are pinned.
|
||||
let mut fresh = m.clone();
|
||||
fresh.path = None;
|
||||
fresh.pins.clear();
|
||||
assert!(fresh.set_path(&line((0.0, 0.0), (100.0, 100.0)), &props, 20));
|
||||
assert!(fresh.pins.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splitting_keeps_the_pins_after_the_cut() {
|
||||
let (mut m, base) = along_s(Easing::Linear);
|
||||
let props = Props::of(&base);
|
||||
assert_eq!(m.pin(1, 6, &props), Ok(()));
|
||||
for cut in [3u32, 6, 10] {
|
||||
let tail = m.split_at(&props, cut);
|
||||
let tail_base = m.apply(&base, cut as f32);
|
||||
assert_eq!(tail.pins.len(), usize::from(cut < 6), "cut {cut}");
|
||||
for f in cut..=24 {
|
||||
let (a, b) = (at(&m, &base, f as f32), at(&tail, &tail_base, (f - cut) as f32));
|
||||
assert!(a.distance(b) < 0.05, "cut {cut} frame {f}: {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_on_past_the_end_carries_the_path_on() {
|
||||
let (mut m, base) = along_s(Easing::Linear);
|
||||
let props = Props::of(&base);
|
||||
let before: Vec<Vec2> = (0..=20).map(|f| at(&m, &base, f as f32)).collect();
|
||||
assert!(!m.extend_to(20, Vec2::new(250.0, 50.0), &props), "only after the last position key");
|
||||
assert!(m.extend_to(28, Vec2::new(250.0, 50.0), &props));
|
||||
assert_eq!(m.position_range(), Some((0, 28)));
|
||||
assert_eq!(m.pins, vec![Pin { frame: 20, anchor: 2 }], "the old end stays pinned to its frame");
|
||||
assert!(at(&m, &base, 28.0).distance(Vec2::new(250.0, 50.0)) < 1e-3);
|
||||
assert!(at(&m, &base, 24.0).distance(Vec2::new(225.0, 25.0)) < 1e-2, "on to the new end in a straight line");
|
||||
for (f, b) in before.iter().enumerate() {
|
||||
assert!(at(&m, &base, f as f32).distance(*b) < 1e-2, "frame {f}: as it was");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_drops_pins_that_cannot_hold() {
|
||||
let (mut m, _) = along_s(Easing::Linear);
|
||||
m.pins = vec![Pin { frame: 5, anchor: 9 }, Pin { frame: 3, anchor: 1 }, Pin { frame: 3, anchor: 1 }, Pin { frame: 25, anchor: 1 }, Pin { frame: 0, anchor: 1 }];
|
||||
assert!(!m.is_sane());
|
||||
m.sanitize();
|
||||
assert!(m.is_sane());
|
||||
assert_eq!(m.pins, vec![Pin { frame: 3, anchor: 1 }]);
|
||||
let json = serde_json::to_string(&m).unwrap();
|
||||
assert!(json.contains("\"pins\""));
|
||||
assert_eq!(serde_json::from_str::<MotionTween>(&json).unwrap(), m);
|
||||
// Without a path nothing is pinned.
|
||||
m.path = None;
|
||||
assert!(!m.is_sane());
|
||||
m.sanitize();
|
||||
assert!(m.pins.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,9 @@
|
||||
//! [`PlayerState`] holds what changes while a movie plays: the main timeline's scene, frame and
|
||||
//! playing flag, each movie clip instance's playhead, the properties actions have set, and the
|
||||
//! pointer. [`step`] advances it by one frame: every playing timeline moves on, the actions on
|
||||
//! the keyframes they enter run, then that frame's pointer events go to the buttons under the
|
||||
//! pointer and run their handlers. [`crate::evaluate_player`] draws a state.
|
||||
//! the keyframes they enter run (and kept ActionScript in the subset that compiles, ADR 0013
|
||||
//! tier 2, with the mouse listeners it adds), then that frame's pointer events go to the buttons
|
||||
//! under the pointer and run their handlers. [`crate::evaluate_player`] draws a state.
|
||||
//!
|
||||
//! Nothing here changes the document, so the authoring stage and every export stay
|
||||
//! script-free; and nothing reads a clock or a random source, so the same document, state and
|
||||
@@ -13,12 +14,14 @@
|
||||
//! frames entered, instances walked, output lines), so a `goto` loop ends in a message instead
|
||||
//! of a hang.
|
||||
|
||||
use crate::actions::as3::{Listener, ScriptOp};
|
||||
use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target};
|
||||
use crate::eval::{Play, evaluate_guided, evaluate_symbol, guide_walk};
|
||||
use crate::sound::Started;
|
||||
use crate::{Document, Element, ElementId, ElementKind, LayerKind, MAX_SYMBOL_DEPTH, SymbolId, SymbolKind, Timeline};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// An instance's place in the movie: the element ids from the main timeline down to it (empty
|
||||
/// for the main timeline itself). Element ids stay the same across keyframes that hold the same
|
||||
@@ -35,6 +38,8 @@ pub const MAX_NODES: usize = 10_000;
|
||||
pub const MAX_OUTPUT_PER_STEP: usize = 1_000;
|
||||
/// Most pointer events one step handles.
|
||||
pub const MAX_EVENTS_PER_STEP: usize = 256;
|
||||
/// Most listeners scripts add to one instance.
|
||||
pub const MAX_LISTENERS_PER_INSTANCE: usize = 16;
|
||||
|
||||
/// A timeline's playhead.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -103,6 +108,18 @@ impl Overrides {
|
||||
}
|
||||
}
|
||||
|
||||
/// A mouse listener a script added to an instance (ADR 0013 tier 2): it lives while the
|
||||
/// instance (and the script's timeline) stay on the stage.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Listening {
|
||||
pub event: ButtonEvent,
|
||||
/// The timeline whose script added it: the actions run there.
|
||||
pub owner: InstancePath,
|
||||
/// The function's name: the same function for the same event is added once.
|
||||
pub function: String,
|
||||
pub actions: Arc<Vec<Action>>,
|
||||
}
|
||||
|
||||
/// Everything that changes while a movie plays.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct PlayerState {
|
||||
@@ -113,6 +130,8 @@ pub struct PlayerState {
|
||||
pub clips: BTreeMap<InstancePath, ClipState>,
|
||||
/// Properties actions have set, per instance.
|
||||
pub props: BTreeMap<InstancePath, Overrides>,
|
||||
/// Mouse listeners scripts added, per instance, in the order added.
|
||||
pub listeners: BTreeMap<InstancePath, Vec<Listening>>,
|
||||
/// The pointer in stage space (`None` when it is outside the movie), and whether it is down.
|
||||
pub pointer: Option<Vec2>,
|
||||
pub down: bool,
|
||||
@@ -350,7 +369,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
|
||||
|
||||
fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2) -> Option<InstancePath> {
|
||||
for n in nodes.iter().rev() {
|
||||
let interactive = n.kind == NodeKind::Button || (n.kind == NodeKind::MovieClip && !n.events.is_empty());
|
||||
let interactive = n.kind == NodeKind::Button || (n.kind == NodeKind::MovieClip && (!n.events.is_empty() || st.listeners.contains_key(&n.path)));
|
||||
if !n.hittable || !interactive {
|
||||
continue;
|
||||
}
|
||||
@@ -468,6 +487,11 @@ impl<'a, 'h> Run<'a, 'h> {
|
||||
}
|
||||
let all: std::collections::BTreeSet<&InstancePath> = self.nodes.iter().map(|n| &n.path).collect();
|
||||
self.st.props.retain(|p, _| all.contains(p));
|
||||
// A listener goes with its instance, and with the timeline whose script added it.
|
||||
self.st.listeners.retain(|p, list| {
|
||||
list.retain(|l| all.contains(&l.owner));
|
||||
all.contains(p) && !list.is_empty()
|
||||
});
|
||||
for slot in [&mut self.st.hover, &mut self.st.pressed] {
|
||||
if slot.as_ref().is_some_and(|p| !all.contains(p)) {
|
||||
*slot = None;
|
||||
@@ -559,7 +583,7 @@ impl<'a, 'h> Run<'a, 'h> {
|
||||
let scripts: Vec<&'a FrameScript> = tl.layers.iter().enumerate().filter(|(ix, _)| plays(tl, *ix)).filter_map(|(_, l)| l.keyframe_starting_at(frame).and_then(|k| l.keyframes.get(k))).filter_map(|k| k.script.as_ref()).collect();
|
||||
for script in scripts {
|
||||
match script {
|
||||
FrameScript::Actions(list) => self.run_list(path, list),
|
||||
FrameScript::Actions(list) => self.run_list(path, list, false),
|
||||
FrameScript::Plugin(p) => {
|
||||
let Some(i) = self.index_of(path) else { return };
|
||||
let label = label_at(tl, frame);
|
||||
@@ -569,27 +593,80 @@ impl<'a, 'h> Run<'a, 'h> {
|
||||
self.out(line);
|
||||
}
|
||||
let list: Vec<Action> = run.actions.into_iter().take(crate::actions::MAX_ACTIONS).collect();
|
||||
self.run_list(path, &list);
|
||||
self.run_list(path, &list, false);
|
||||
}
|
||||
// ActionScript in the subset runs, whole (ADR 0013 tier 2); a script outside it
|
||||
// doesn't run at all. Test Movie lists which is which once, at the start, rather
|
||||
// than a line every time the playhead passes.
|
||||
FrameScript::Source(src) => {
|
||||
if let Ok(c) = src.compiled() {
|
||||
self.run_ops(path, &c.ops);
|
||||
}
|
||||
}
|
||||
// Kept with the document, not run (ADR 0013 tier 1). The Test Movie window says
|
||||
// so once, rather than a line every time the playhead passes.
|
||||
FrameScript::Source(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_list(&mut self, owner: &[ElementId], list: &[Action]) {
|
||||
for a in list {
|
||||
if self.halted {
|
||||
return;
|
||||
}
|
||||
self.actions += 1;
|
||||
if self.actions > MAX_ACTIONS_PER_STEP {
|
||||
self.halt(&format!("more than {MAX_ACTIONS_PER_STEP} actions"));
|
||||
return;
|
||||
}
|
||||
self.exec(owner, a);
|
||||
/// Counts one action against the step's budget; `false` when nothing more may run.
|
||||
fn budget(&mut self) -> bool {
|
||||
if self.halted {
|
||||
return false;
|
||||
}
|
||||
self.actions += 1;
|
||||
if self.actions > MAX_ACTIONS_PER_STEP {
|
||||
self.halt(&format!("more than {MAX_ACTIONS_PER_STEP} actions"));
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Runs a list of actions from timeline `owner`; `script`: they come from ActionScript.
|
||||
fn run_list(&mut self, owner: &[ElementId], list: &[Action], script: bool) {
|
||||
for a in list {
|
||||
if !self.budget() {
|
||||
return;
|
||||
}
|
||||
self.exec(owner, a, script);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a compiled script's steps (ADR 0013 tier 2), each one action of the budget.
|
||||
fn run_ops(&mut self, owner: &[ElementId], ops: &[ScriptOp]) {
|
||||
for op in ops {
|
||||
if !self.budget() {
|
||||
return;
|
||||
}
|
||||
match op {
|
||||
ScriptOp::Action(a) => self.exec(owner, a, true),
|
||||
ScriptOp::Listen(l) => self.listen(owner, l),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `addEventListener`: the instance the listener's target names gets it (once per
|
||||
/// function and event).
|
||||
fn listen(&mut self, owner: &[ElementId], l: &Listener) {
|
||||
self.refresh();
|
||||
let Some(from) = self.index_of(owner) else { return };
|
||||
let what = format!("Listen for {} ({})", l.event.key(), l.target);
|
||||
let i = match self.resolve(from, &l.target) {
|
||||
Ok(i) => i,
|
||||
Err(e) => return self.out(format!("{what}: {e}")),
|
||||
};
|
||||
let Some(node) = self.nodes.get(i) else { return };
|
||||
if !matches!(node.kind, NodeKind::Button | NodeKind::MovieClip) {
|
||||
let why = if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is a graphic; only buttons and movie clips get pointer events", node.name) };
|
||||
return self.out(format!("{what}: {why}"));
|
||||
}
|
||||
let (path, name) = (node.path.clone(), node.name.clone());
|
||||
let list = self.st.listeners.entry(path).or_default();
|
||||
if list.iter().any(|x| x.event == l.event && x.owner == owner && x.function == l.function) {
|
||||
return;
|
||||
}
|
||||
if list.len() >= MAX_LISTENERS_PER_INSTANCE {
|
||||
return self.out(format!("{what}: “{name}” already has {MAX_LISTENERS_PER_INSTANCE} listeners"));
|
||||
}
|
||||
list.push(Listening { event: l.event, owner: owner.to_vec(), function: l.function.clone(), actions: l.actions.clone() });
|
||||
}
|
||||
|
||||
/// The node `target` names, seen from timeline node `from`.
|
||||
@@ -608,11 +685,16 @@ impl<'a, 'h> Run<'a, 'h> {
|
||||
Ok(cur)
|
||||
}
|
||||
|
||||
fn exec(&mut self, owner: &[ElementId], a: &Action) {
|
||||
/// Runs one action from timeline `owner`. `script`: it comes from ActionScript, where
|
||||
/// `nextScene()` on a movie clip's timeline has no other scene to go to.
|
||||
fn exec(&mut self, owner: &[ElementId], a: &Action, script: bool) {
|
||||
self.refresh();
|
||||
let Some(from) = self.index_of(owner) else { return };
|
||||
match a {
|
||||
Action::Trace { message } => self.out(message.clone()),
|
||||
Action::NextScene | Action::PrevScene if script && !owner.is_empty() => {
|
||||
self.out(format!("{}: a movie clip's timeline has one scene; call it in the main timeline's script", a.describe()));
|
||||
}
|
||||
Action::NextScene | Action::PrevScene => {
|
||||
let next = if matches!(a, Action::NextScene) { self.st.scene.checked_add(1) } else { self.st.scene.checked_sub(1) };
|
||||
if let Some(s) = next.filter(|s| *s < self.doc.scenes.len()) {
|
||||
@@ -774,14 +856,23 @@ impl<'a, 'h> Run<'a, 'h> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an instance's handler for `event` (in the timeline the instance is on).
|
||||
/// Runs an instance's handler for `event` (in the timeline the instance is on), then the
|
||||
/// listeners scripts added for it (each in the timeline of its script), in the order added.
|
||||
fn fire(&mut self, path: &[ElementId], event: ButtonEvent) {
|
||||
self.refresh();
|
||||
let Some(n) = self.index_of(path).and_then(|i| self.nodes.get(i)) else { return };
|
||||
let Some(h) = n.events.iter().find(|h| h.event == event) else { return };
|
||||
let (actions, owner) = (h.actions.clone(), n.owner);
|
||||
let Some(owner_path) = self.nodes.get(owner).map(|o| o.path.clone()) else { return };
|
||||
self.run_list(&owner_path, &actions);
|
||||
let handler = n.events.iter().find(|h| h.event == event).map(|h| h.actions.clone());
|
||||
let owner_path = self.nodes.get(n.owner).map(|o| o.path.clone());
|
||||
let listeners: Vec<(InstancePath, Arc<Vec<Action>>)> = self.st.listeners.get(path).map(|l| l.iter().filter(|l| l.event == event).map(|l| (l.owner.clone(), l.actions.clone())).collect()).unwrap_or_default();
|
||||
if handler.is_none() && listeners.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let (Some(actions), Some(owner)) = (handler, owner_path) {
|
||||
self.run_list(&owner, &actions, false);
|
||||
}
|
||||
for (owner, actions) in listeners {
|
||||
self.run_list(&owner, &actions, true);
|
||||
}
|
||||
self.settle();
|
||||
}
|
||||
|
||||
|
||||
@@ -341,3 +341,110 @@ fn entered_keyframes_start_their_sounds_in_clips_and_graphics_with_layer_volumes
|
||||
Arc::make_mut(&mut m.timeline_mut(0).layers[1]).muted = true;
|
||||
assert_eq!(started(&start(&m, &mut NoScripts)), vec![(1, 1.0), (3, 0.0)]);
|
||||
}
|
||||
|
||||
// ----- ActionScript (ADR 0013 tier 2) -----------------------------------------------------------
|
||||
|
||||
/// `k` with a kept ActionScript 3.0 script in place of its actions.
|
||||
fn as3(k: Arc<Keyframe>, src: &str) -> Arc<Keyframe> {
|
||||
let mut k = (*k).clone();
|
||||
k.script = Some(FrameScript::Source(Arc::new(crate::actions::SourceScript::new(crate::actions::Language::ActionScript3, src))));
|
||||
Arc::new(k)
|
||||
}
|
||||
|
||||
/// The state without the listeners scripts add (hand-made actions use handlers instead).
|
||||
fn lean(st: &PlayerState) -> PlayerState {
|
||||
PlayerState { listeners: BTreeMap::new(), ..st.clone() }
|
||||
}
|
||||
|
||||
/// Plays both documents through the same pointer events and asserts the same movie: state and
|
||||
/// output at every step.
|
||||
fn same_movie(a: &Document, b: &Document, events: &[Vec<Event>]) {
|
||||
let (mut x, mut y) = (start(a, &mut NoScripts), start(b, &mut NoScripts));
|
||||
assert_eq!((lean(&x.state), &x.output), (lean(&y.state), &y.output), "start");
|
||||
for (i, ev) in events.iter().enumerate() {
|
||||
x = step(a, &x.state, ev, &mut NoScripts);
|
||||
y = step(b, &y.state, ev, &mut NoScripts);
|
||||
assert_eq!((lean(&x.state), &x.output), (lean(&y.state), &y.output), "step {}", i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actionscript_and_hand_made_actions_play_the_same_movie() {
|
||||
// Nested clips told what to do by instance-name path.
|
||||
let hand = nested();
|
||||
let mut script = nested();
|
||||
{
|
||||
let l = Arc::make_mut(&mut script.timeline_mut(0).layers[0]);
|
||||
l.keyframes[0] = as3(l.keyframes[0].clone(), "hero.gotoAndStop(\"run\");\nthis.hero.arm.gotoAndStop(3);");
|
||||
let arm = Arc::make_mut(&mut script.library[1]);
|
||||
let al = Arc::make_mut(&mut arm.timeline.layers[0]);
|
||||
al.keyframes[1] = as3(al.keyframes[1].clone(), "MovieClip(this.parent.parent).stop();");
|
||||
}
|
||||
same_movie(&hand, &script, &vec![vec![]; 6]);
|
||||
// A button's handlers, and the same as listeners a frame script adds.
|
||||
let hand = button_doc();
|
||||
let mut script = button_doc();
|
||||
{
|
||||
let tl = script.timeline_mut(0);
|
||||
let l0 = Arc::make_mut(&mut tl.layers[0]);
|
||||
l0.keyframes[0] = as3(l0.keyframes[0].clone(), "import flash.events.MouseEvent;\nstop();\ngo.addEventListener(MouseEvent.CLICK, onGo);\ngo.addEventListener(MouseEvent.ROLL_OVER, function (e:MouseEvent):void { trace(\"over\"); });\ngo.addEventListener(MouseEvent.ROLL_OUT, function (e:MouseEvent):void { trace(\"o\" + \"ut\"); });\nfunction onGo(e:MouseEvent):void {\n gotoAndStop(5);\n}\n");
|
||||
let l1 = Arc::make_mut(&mut tl.layers[1]);
|
||||
let k = Arc::make_mut(&mut l1.keyframes[0]);
|
||||
if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind {
|
||||
events.clear();
|
||||
}
|
||||
}
|
||||
let at = |x, y| Vec2::new(x, y);
|
||||
let events = vec![vec![], vec![Event::Move(at(180.0, 180.0))], vec![Event::Down(at(180.0, 180.0))], vec![Event::Up(at(181.0, 181.0))], vec![Event::Move(at(300.0, 300.0))], vec![], vec![Event::Move(at(150.0, 150.0)), Event::Leave]];
|
||||
same_movie(&hand, &script, &events);
|
||||
let s = start(&script, &mut NoScripts);
|
||||
assert_eq!(s.state.listeners.get(&vec![ElementId(3)]).map(Vec::len), Some(3), "three listeners on the button");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_outside_the_subset_does_not_run_at_all() {
|
||||
let d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nif (true) { play(); }")])], vec![]);
|
||||
let s = run(&d, 3);
|
||||
assert!(s.state.root.playing && s.output.is_empty(), "nothing of it ran: {:?}", s.output);
|
||||
assert_eq!(s.state.root.frame, 3);
|
||||
// In ActionScript 1.0 & 2.0 nothing runs either.
|
||||
let mut d2 = doc(vec![layer(1, vec![kf(0, 10, vec![], vec![], "")])], vec![]);
|
||||
Arc::make_mut(&mut Arc::make_mut(&mut d2.timeline_mut(0).layers[0]).keyframes[0]).script = Some(FrameScript::Source(Arc::new(crate::actions::SourceScript::new(crate::actions::Language::ActionScript1or2, "stop();"))));
|
||||
assert!(run(&d2, 2).state.root.playing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_live_with_their_instance_and_are_added_once() {
|
||||
// `pad` is a movie clip with no handlers: a listener makes it clickable. It is on the stage
|
||||
// for frames 0-4; the main timeline loops round 8 frames, adding the listener again each
|
||||
// time it enters frame 1.
|
||||
let pad = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 1, vec![rect(12, 0.0, 0.0, 20.0, 20.0)], vec![], "")])]);
|
||||
let script = "pad.addEventListener(MouseEvent.CLICK, hit);\nfunction hit(e:MouseEvent):void { trace(\"hit\"); }\nghost.addEventListener(MouseEvent.CLICK, hit);";
|
||||
let d = doc(vec![layer(1, vec![as3(kf(0, 8, vec![], vec![], ""), script)]), layer(2, vec![kf(0, 5, vec![inst(3, 100, "pad", 10.0, 10.0, vec![])], vec![], ""), kf(5, 3, vec![], vec![], "")])], vec![pad]);
|
||||
let path = vec![ElementId(3)];
|
||||
let s = start(&d, &mut NoScripts);
|
||||
assert_eq!(s.output, ["Listen for click (ghost): no instance named “ghost” here"]);
|
||||
assert!(hit(&d, &s.state, Vec2::new(15.0, 15.0)).is_some(), "the listener makes the clip clickable");
|
||||
let at = Vec2::new(15.0, 15.0);
|
||||
let s = step(&d, &s.state, &[Event::Move(at), Event::Down(at), Event::Up(at)], &mut NoScripts);
|
||||
assert!(s.output.iter().any(|l| l == "hit"), "{:?}", s.output);
|
||||
let s = run(&d, 5);
|
||||
assert!(s.state.listeners.is_empty(), "pad left the stage, and its listener with it");
|
||||
// Round the loop: the frame-1 script adds the same function again, which changes nothing.
|
||||
let s = run(&d, 8);
|
||||
assert_eq!(s.state.listeners.get(&path).map(Vec::len), Some(1));
|
||||
let s = run(&d, 16);
|
||||
assert_eq!(s.state.listeners.get(&path).map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_scene_in_a_movie_clip_script_stays_in_its_clip() {
|
||||
// A clip's own script calling nextScene(): in ActionScript the clip has one scene, so the
|
||||
// main timeline stays (hand-made Next scene actions do move it, as before).
|
||||
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![as3(kf(0, 2, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], ""), "nextScene();")])]);
|
||||
let mut d = doc(vec![layer(1, vec![kf(0, 4, vec![inst(3, 100, "c", 0.0, 0.0, vec![])], vec![], "")])], vec![clip]);
|
||||
d.scenes.push(Arc::new(crate::Scene::new("Two")));
|
||||
let s = start(&d, &mut NoScripts);
|
||||
assert_eq!(s.state.scene, 0);
|
||||
assert_eq!(s.output, ["Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"]);
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Stroke caps, joins, the miter limit, and dashed and dotted lines (ADR 0046).
|
||||
//!
|
||||
//! A [`StrokeStyle`] sits on every [`crate::Stroke`]. Its default is what every stroke had
|
||||
//! before: round caps, round joins, solid, so a stroke with the default style is written to a
|
||||
//! file exactly as before and older files open unchanged. Dash and dot lengths are in the
|
||||
//! shape's own units, like the stroke width: scaling the shape scales them.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// How an open end of a stroke (and each dash) ends.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Cap {
|
||||
/// Flat, exactly at the end (Animate's "None", SVG's `butt`).
|
||||
Butt,
|
||||
/// A half disc past the end.
|
||||
#[default]
|
||||
Round,
|
||||
/// Flat, half the width past the end.
|
||||
Square,
|
||||
}
|
||||
|
||||
impl Cap {
|
||||
pub const ALL: [Cap; 3] = [Cap::Butt, Cap::Round, Cap::Square];
|
||||
|
||||
/// The name used in commands and files.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Cap::Butt => "butt",
|
||||
Cap::Round => "round",
|
||||
Cap::Square => "square",
|
||||
}
|
||||
}
|
||||
|
||||
/// As Animate's Properties name it.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Cap::Butt => "None",
|
||||
Cap::Round => "Round",
|
||||
Cap::Square => "Square",
|
||||
}
|
||||
}
|
||||
|
||||
/// A cap by name; `none` (Animate's word) is `butt`.
|
||||
pub fn from_key(s: &str) -> Option<Cap> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"butt" | "none" | "flat" => Some(Cap::Butt),
|
||||
"round" => Some(Cap::Round),
|
||||
"square" => Some(Cap::Square),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a stroke turns its corners.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Join {
|
||||
/// Sharp: the outer edges meet in a point, unless that point is farther than the miter limit
|
||||
/// allows, where the corner is bevelled.
|
||||
Miter,
|
||||
#[default]
|
||||
Round,
|
||||
/// Cut straight across the outer corner.
|
||||
Bevel,
|
||||
}
|
||||
|
||||
impl Join {
|
||||
pub const ALL: [Join; 3] = [Join::Miter, Join::Round, Join::Bevel];
|
||||
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Join::Miter => "miter",
|
||||
Join::Round => "round",
|
||||
Join::Bevel => "bevel",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Join::Miter => "Miter",
|
||||
Join::Round => "Round",
|
||||
Join::Bevel => "Bevel",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_key(s: &str) -> Option<Join> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"miter" | "mitre" => Some(Join::Miter),
|
||||
"round" => Some(Join::Round),
|
||||
"bevel" => Some(Join::Bevel),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The miter limit new strokes get (Animate's default). SVG's own default is 4; the SVG
|
||||
/// importer sets that when a file leaves it out.
|
||||
pub const DEFAULT_MITER_LIMIT: f32 = 3.0;
|
||||
/// The miter limit's range: a ratio of the corner's point length to the stroke width.
|
||||
pub const MIN_MITER_LIMIT: f32 = 1.0;
|
||||
pub const MAX_MITER_LIMIT: f32 = 100.0;
|
||||
/// Most on and off lengths in a dash pattern.
|
||||
pub const MAX_DASH_ENTRIES: usize = 16;
|
||||
/// Longest dash, gap or dot spacing (shape units).
|
||||
pub const MAX_DASH_LENGTH: f32 = 10_000.0;
|
||||
/// A pattern shorter than this (shape units) draws solid.
|
||||
const MIN_PERIOD: f32 = 1e-3;
|
||||
|
||||
/// A broken line: dashes, or round dots.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Dash {
|
||||
/// Dashes: lengths that alternate on and off along each subpath, starting with a dash
|
||||
/// (an even count, as SVG's `stroke-dasharray` repeats an odd one), each dash capped with
|
||||
/// the stroke's cap. `offset` is how far into the pattern each subpath starts.
|
||||
Dashed {
|
||||
lengths: Arc<[f32]>,
|
||||
#[serde(default)]
|
||||
offset: f32,
|
||||
},
|
||||
/// Round dots one stroke width across, `spacing` apart edge to edge.
|
||||
Dotted { spacing: f32 },
|
||||
}
|
||||
|
||||
/// The line styles Properties offers.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum DashKind {
|
||||
#[default]
|
||||
Solid,
|
||||
Dashed,
|
||||
Dotted,
|
||||
}
|
||||
|
||||
impl DashKind {
|
||||
pub const ALL: [DashKind; 3] = [DashKind::Solid, DashKind::Dashed, DashKind::Dotted];
|
||||
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
DashKind::Solid => "solid",
|
||||
DashKind::Dashed => "dashed",
|
||||
DashKind::Dotted => "dotted",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
DashKind::Solid => "Solid",
|
||||
DashKind::Dashed => "Dashed",
|
||||
DashKind::Dotted => "Dotted",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_key(s: &str) -> Option<DashKind> {
|
||||
let s = s.trim().to_ascii_lowercase();
|
||||
DashKind::ALL.into_iter().find(|k| k.key() == s)
|
||||
}
|
||||
}
|
||||
|
||||
fn length(v: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(0.0, MAX_DASH_LENGTH) } else { 0.0 }
|
||||
}
|
||||
|
||||
impl Dash {
|
||||
/// Dashes of `on` with gaps of `off` (sanitized; `None` when that draws solid).
|
||||
pub fn dashed(on: f32, off: f32) -> Option<Dash> {
|
||||
Dash::Dashed { lengths: vec![on, off].into(), offset: 0.0 }.sanitized()
|
||||
}
|
||||
|
||||
/// Dots `spacing` apart (sanitized).
|
||||
pub fn dotted(spacing: f32) -> Option<Dash> {
|
||||
Dash::Dotted { spacing }.sanitized()
|
||||
}
|
||||
|
||||
/// The pattern as stored, cleaned up (a file, a command): lengths finite and in range, an
|
||||
/// odd count repeated, at most [`MAX_DASH_ENTRIES`], the offset within one period.
|
||||
/// `None` when it draws solid (no gaps, or nothing at all to repeat).
|
||||
pub fn sanitized(self) -> Option<Dash> {
|
||||
match self {
|
||||
Dash::Dashed { lengths, offset } => {
|
||||
let mut v: Vec<f32> = lengths.iter().take(MAX_DASH_ENTRIES).map(|&x| length(x)).collect();
|
||||
if v.len() % 2 == 1 {
|
||||
let again = v.clone();
|
||||
v.extend(again);
|
||||
v.truncate(MAX_DASH_ENTRIES);
|
||||
}
|
||||
let period: f32 = v.iter().sum();
|
||||
let gaps: f32 = v.iter().skip(1).step_by(2).sum();
|
||||
if period.is_nan() || period <= MIN_PERIOD || gaps <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let offset = if offset.is_finite() { offset.rem_euclid(period) } else { 0.0 };
|
||||
Some(Dash::Dashed { lengths: v.into(), offset })
|
||||
}
|
||||
Dash::Dotted { spacing } => Some(Dash::Dotted { spacing: length(spacing) }),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> DashKind {
|
||||
match self {
|
||||
Dash::Dashed { .. } => DashKind::Dashed,
|
||||
Dash::Dotted { .. } => DashKind::Dotted,
|
||||
}
|
||||
}
|
||||
|
||||
/// The on/off lengths and the start offset for a stroke `width` wide (shape units). Dots are
|
||||
/// zero-length dashes drawn with round caps, one width plus the spacing apart.
|
||||
pub fn pattern(&self, width: f32) -> (Vec<f32>, f32) {
|
||||
match self {
|
||||
Dash::Dashed { lengths, offset } => (lengths.to_vec(), *offset),
|
||||
Dash::Dotted { spacing } => (vec![0.0, length(width) + spacing], 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same pattern `k` times as long (the shape scaled by `k`).
|
||||
pub fn scaled(&self, k: f32) -> Dash {
|
||||
let k = if k.is_finite() && k > 0.0 { k } else { 1.0 };
|
||||
match self {
|
||||
Dash::Dashed { lengths, offset } => Dash::Dashed { lengths: lengths.iter().map(|&x| length(x * k)).collect(), offset: offset * k },
|
||||
Dash::Dotted { spacing } => Dash::Dotted { spacing: length(spacing * k) },
|
||||
}
|
||||
}
|
||||
|
||||
/// `t` of the way to `o` (shape tweens): lengths blend when both are the same kind with
|
||||
/// the same number of lengths; otherwise this pattern holds until the end.
|
||||
pub fn lerp(a: Option<&Dash>, b: Option<&Dash>, t: f32) -> Option<Dash> {
|
||||
let mix = |x: f32, y: f32| x + (y - x) * t;
|
||||
match (a, b) {
|
||||
(Some(Dash::Dashed { lengths: la, offset: oa }), Some(Dash::Dashed { lengths: lb, offset: ob })) if la.len() == lb.len() => {
|
||||
Dash::Dashed { lengths: la.iter().zip(lb.iter()).map(|(&x, &y)| mix(x, y)).collect(), offset: mix(*oa, *ob) }.sanitized()
|
||||
}
|
||||
(Some(Dash::Dotted { spacing: sa }), Some(Dash::Dotted { spacing: sb })) => Some(Dash::Dotted { spacing: mix(*sa, *sb) }),
|
||||
_ => if t >= 1.0 { b.cloned() } else { a.cloned() },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Caps, joins, miter limit and dashes: everything about a stroke's outline but its width.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct StrokeStyle {
|
||||
pub cap: Cap,
|
||||
pub join: Join,
|
||||
/// For miter joins: the longest a corner's point may reach, as a multiple of the stroke
|
||||
/// width ([`MIN_MITER_LIMIT`]..=[`MAX_MITER_LIMIT`]); sharper corners are bevelled.
|
||||
pub miter_limit: f32,
|
||||
/// `None`: a solid line.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dash: Option<Dash>,
|
||||
}
|
||||
|
||||
impl Default for StrokeStyle {
|
||||
fn default() -> Self {
|
||||
StrokeStyle { cap: Cap::Round, join: Join::Round, miter_limit: DEFAULT_MITER_LIMIT, dash: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl StrokeStyle {
|
||||
/// Round caps and joins, solid: how strokes were before styles (written as nothing).
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == StrokeStyle::default()
|
||||
}
|
||||
|
||||
/// Cleaned up for use (a file, a command): the miter limit in range, the dash sanitized.
|
||||
pub fn sanitized(self) -> StrokeStyle {
|
||||
let miter_limit = if self.miter_limit.is_finite() { self.miter_limit.clamp(MIN_MITER_LIMIT, MAX_MITER_LIMIT) } else { DEFAULT_MITER_LIMIT };
|
||||
StrokeStyle { miter_limit, dash: self.dash.and_then(Dash::sanitized), ..self }
|
||||
}
|
||||
|
||||
pub fn dash_kind(&self) -> DashKind {
|
||||
self.dash.as_ref().map_or(DashKind::Solid, Dash::kind)
|
||||
}
|
||||
|
||||
/// The cap the ends of each piece get: dots are always round.
|
||||
pub fn effective_cap(&self) -> Cap {
|
||||
if matches!(self.dash, Some(Dash::Dotted { .. })) { Cap::Round } else { self.cap }
|
||||
}
|
||||
|
||||
/// The farthest the outline reaches from the path, as a multiple of the half-width: miter
|
||||
/// points reach the miter limit, square caps the corner of their square.
|
||||
pub fn reach_factor(&self) -> f32 {
|
||||
let join = if self.join == Join::Miter { self.miter_limit.clamp(MIN_MITER_LIMIT, MAX_MITER_LIMIT) } else { 1.0 };
|
||||
let cap = if self.effective_cap() == Cap::Square { std::f32::consts::SQRT_2 } else { 1.0 };
|
||||
join.max(cap)
|
||||
}
|
||||
|
||||
/// The style of the shape scaled by `k`: dashes scale with it.
|
||||
pub fn scaled(&self, k: f32) -> StrokeStyle {
|
||||
StrokeStyle { dash: self.dash.as_ref().map(|d| d.scaled(k)), ..self.clone() }
|
||||
}
|
||||
|
||||
/// `t` of the way to `o` (shape tweens): the miter limit and the dash lengths blend; the
|
||||
/// caps and joins of the start hold until the end keyframe.
|
||||
pub fn lerp(&self, o: &StrokeStyle, t: f32) -> StrokeStyle {
|
||||
let pick = if t >= 1.0 { o } else { self };
|
||||
StrokeStyle { cap: pick.cap, join: pick.join, miter_limit: self.miter_limit + (o.miter_limit - self.miter_limit) * t, dash: Dash::lerp(self.dash.as_ref(), o.dash.as_ref(), t) }.sanitized()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dash_patterns_are_sanitized() {
|
||||
// An odd count repeats (as in SVG); the offset wraps into one period.
|
||||
let d = Dash::Dashed { lengths: vec![4.0, 2.0, 1.0].into(), offset: 15.0 }.sanitized().unwrap();
|
||||
assert_eq!(d, Dash::Dashed { lengths: vec![4.0, 2.0, 1.0, 4.0, 2.0, 1.0].into(), offset: 1.0 });
|
||||
// No gaps, or nothing at all: solid.
|
||||
assert_eq!(Dash::dashed(5.0, 0.0), None);
|
||||
assert_eq!(Dash::dashed(0.0, 0.0), None);
|
||||
assert_eq!(Dash::Dashed { lengths: vec![].into(), offset: 0.0 }.sanitized(), None);
|
||||
// Junk is clamped, never kept.
|
||||
let d = Dash::Dashed { lengths: vec![f32::NAN, -3.0, 1e30, 2.0].into(), offset: f32::INFINITY }.sanitized().unwrap();
|
||||
assert_eq!(d, Dash::Dashed { lengths: vec![0.0, 0.0, MAX_DASH_LENGTH, 2.0].into(), offset: 0.0 });
|
||||
let long = Dash::Dashed { lengths: vec![1.0; 99].into(), offset: 0.0 }.sanitized().unwrap();
|
||||
assert!(matches!(long, Dash::Dashed { lengths, .. } if lengths.len() == MAX_DASH_ENTRIES));
|
||||
assert_eq!(Dash::dotted(f32::NAN), Some(Dash::Dotted { spacing: 0.0 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dots_are_round_zero_length_dashes() {
|
||||
let st = StrokeStyle { cap: Cap::Butt, dash: Dash::dotted(3.0), ..StrokeStyle::default() };
|
||||
assert_eq!(st.effective_cap(), Cap::Round);
|
||||
assert_eq!(st.dash.as_ref().unwrap().pattern(2.0), (vec![0.0, 5.0], 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_files_round_trip_and_default_to_round() {
|
||||
assert!(StrokeStyle::default().is_default());
|
||||
let st = StrokeStyle { cap: Cap::Square, join: Join::Miter, miter_limit: 6.0, dash: Dash::dashed(6.0, 3.0) };
|
||||
let s = serde_json::to_string(&st).unwrap();
|
||||
assert_eq!(s, r#"{"cap":"square","join":"miter","miter_limit":6.0,"dash":{"kind":"dashed","lengths":[6.0,3.0],"offset":0.0}}"#);
|
||||
assert_eq!(serde_json::from_str::<StrokeStyle>(&s).unwrap(), st);
|
||||
// Missing fields take the defaults.
|
||||
assert_eq!(serde_json::from_str::<StrokeStyle>(r#"{"join":"bevel"}"#).unwrap(), StrokeStyle { join: Join::Bevel, ..StrokeStyle::default() });
|
||||
assert_eq!(Cap::from_key("none"), Some(Cap::Butt));
|
||||
assert_eq!(Join::from_key("Mitre"), Some(Join::Miter));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reach_covers_miters_and_square_caps() {
|
||||
assert_eq!(StrokeStyle::default().reach_factor(), 1.0);
|
||||
assert_eq!(StrokeStyle { join: Join::Miter, miter_limit: 5.0, ..StrokeStyle::default() }.reach_factor(), 5.0);
|
||||
assert!((StrokeStyle { cap: Cap::Square, ..StrokeStyle::default() }.reach_factor() - 2f32.sqrt()).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_blend_in_tweens() {
|
||||
let a = StrokeStyle { dash: Dash::dashed(2.0, 2.0), ..StrokeStyle::default() };
|
||||
let b = StrokeStyle { cap: Cap::Butt, miter_limit: 5.0, dash: Dash::dashed(6.0, 4.0), ..StrokeStyle::default() };
|
||||
let m = a.lerp(&b, 0.5);
|
||||
assert_eq!((m.cap, m.miter_limit, m.dash), (Cap::Round, 4.0, Dash::dashed(4.0, 3.0)));
|
||||
assert_eq!(a.lerp(&b, 1.0).cap, Cap::Butt);
|
||||
// Different kinds hold the start's until the end.
|
||||
let c = StrokeStyle { dash: Dash::dotted(1.0), ..StrokeStyle::default() };
|
||||
assert_eq!(a.lerp(&c, 0.9).dash, a.dash);
|
||||
assert_eq!(a.lerp(&c, 1.0).dash, c.dash);
|
||||
}
|
||||
}
|
||||
@@ -85,19 +85,20 @@ fn parse_actions(p: &Value) -> Result<Vec<Action>> {
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// The symbol instance `element` (or the selected one) on the active layer's keyframe at the
|
||||
/// playhead, for editing.
|
||||
/// The symbol instance `element` on the active layer's keyframe at the playhead (or the selected
|
||||
/// one, on its layer), for editing.
|
||||
fn instance_mut<'a>(s: &'a mut Session, p: &Value) -> Result<&'a mut Element> {
|
||||
let id = match opt_u64(p, "element")? {
|
||||
Some(id) => ElementId(id),
|
||||
None => match s.selection.as_slice() {
|
||||
[one] => *one,
|
||||
[] => return Err(EngineError::State("select a movie clip or button instance, or pass 'element'".into())),
|
||||
let (layer, id) = match opt_u64(p, "element")? {
|
||||
// A selected element is looked for on its own layer.
|
||||
Some(id) => (s.selection.iter().find(|(_, e)| e.0 == id).map_or(s.layer, |(l, _)| l), ElementId(id)),
|
||||
None => match (s.selection.first(), s.selection.len()) {
|
||||
(Some(one), 1) => one,
|
||||
(None, _) => return Err(EngineError::State("select a movie clip or button instance, or pass 'element'".into())),
|
||||
_ => return Err(EngineError::State("select one instance".into())),
|
||||
},
|
||||
};
|
||||
let frame = s.frame;
|
||||
let layer = s.layer_mut(None)?;
|
||||
let layer = s.layer_mut(Some(layer))?;
|
||||
let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?;
|
||||
let k = layer.keyframe_mut(i).ok_or_else(|| EngineError::State("keyframe vanished".into()))?;
|
||||
let e = k.elements.iter_mut().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("no element {} on the active layer at frame {}", id.0, frame + 1)))?;
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
//! Bone commands (ADR 0043): join symbol instances into an armature, take bones away, limit and
|
||||
//! pin joints, pose the armature at a frame by joint angle or by inverse kinematics, and read
|
||||
//! it back.
|
||||
//!
|
||||
//! The armature lives on an armature layer: `bone.add` moves the instances there (making the
|
||||
//! layer for the first bone). Poses go through [`Session::editable_keyframe_in`], so inside a
|
||||
//! pose tween they key the frame with the pose it shows, as editing any tweened object does;
|
||||
//! a drag sends many `bone.solve` calls inside one gesture: one undo step. After every pose
|
||||
//! edit the keyframe's instances are placed by the pose, so the file holds what shows.
|
||||
|
||||
use crate::cmds_timeline::insert_keyframe_at;
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, KeyEdit, MAX_FRAME, Result, Session};
|
||||
use anicraft_doc::armature::{self, Armature, Bone, BoneId, Limits, MAX_BONES, MAX_LIMIT, MAX_NAME};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Rgba, Tween, evaluate_layer_elements};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run };
|
||||
vec![
|
||||
c(
|
||||
"bone.add",
|
||||
"Add Bone",
|
||||
"{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint, stage px; default the end of the bone into `from`, else its registration point), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)",
|
||||
true,
|
||||
add as crate::RunFn,
|
||||
),
|
||||
c("bone.remove", "Remove Bone", "{bone} removes it and the bones below it; the instances they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); asks first when the armature has more than one pose", true, remove),
|
||||
c("bone.set_limits", "Joint Limits", "{bone, constrain?: bool (false: turns freely), min?, max? (°, −360…360, from where it was drawn)} limits how far the joint turns, in every pose", true, set_limits),
|
||||
c("bone.pin", "Pin Bone", "{bone, pinned: bool} a pinned bone (and the bones it hangs from) stays put while dragging bones below it", true, pin),
|
||||
c("bone.pose", "Pose Bone", "{bone?, angle? (°, the joint angle: 0 as drawn), rotate_by? (°), dx?, dy? (moves the whole armature), layer? (the armature layer, when no bone is given), frame?} keys the pose at the frame", true, pose),
|
||||
c("bone.solve", "Drag Bone", "{bone, x, y (stage px: where the bone's end goes), local?: [x, y] (the point dragged, in the bone's instance's space; default its end), frame?} → {reached, error (px), chain}; inverse kinematics turns the bone and the bones above it (limits respected, pinned bones kept)", true, solve),
|
||||
c("bone.info", "Armatures", "{frame?, layer?} → every armature on the scene at the frame: its bones with joint and end (stage px), joint angle and limits (°), pinned", false, info),
|
||||
]
|
||||
}
|
||||
|
||||
/// Where an instance is at the playhead.
|
||||
struct Found {
|
||||
layer: LayerId,
|
||||
index: usize,
|
||||
kind: LayerKind,
|
||||
el: Arc<Element>,
|
||||
}
|
||||
|
||||
/// Instance `id` on the scene at the playhead (as it shows: tweened, posed).
|
||||
fn find_instance(s: &Session, id: ElementId) -> Option<Found> {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
tl.layers.iter().enumerate().find_map(|(index, l)| {
|
||||
let (_, els) = evaluate_layer_elements(l, s.frame)?;
|
||||
let el = els.iter().find(|e| e.id == id)?.clone();
|
||||
Some(Found { layer: l.id, index, kind: l.kind, el })
|
||||
})
|
||||
}
|
||||
|
||||
/// The armature layer holding bone `id`, and its armature.
|
||||
fn find_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc<Armature>)> {
|
||||
s.doc
|
||||
.timeline(s.scene)
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.kind == LayerKind::Armature)
|
||||
.find_map(|l| l.armature.as_ref().filter(|a| a.bone(id).is_some()).map(|a| (l.id, a.clone())))
|
||||
.ok_or_else(|| EngineError::State(format!("no bone with id {} in this scene", id.0)))
|
||||
}
|
||||
|
||||
fn bone_param(p: &Value) -> Result<BoneId> {
|
||||
opt_u64(p, "bone")?.map(BoneId).ok_or_else(|| EngineError::Param("param 'bone' (a bone id; see bone.info) is required".into()))
|
||||
}
|
||||
|
||||
/// Largest stage coordinate a bone point may have.
|
||||
const MAX_COORD: f32 = 1_000_000.0;
|
||||
|
||||
fn opt_point(p: &Value, key: &str) -> Result<Option<Vec2>> {
|
||||
let bad = || EngineError::Param(format!("param '{key}' must be [x, y] (finite numbers within ±1,000,000)"));
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Array(a)) if a.len() == 2 => {
|
||||
let n = |i: usize| a.get(i).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() <= f64::from(MAX_COORD)).map(|v| v as f32).ok_or_else(bad);
|
||||
Ok(Some(Vec2::new(n(0)?, n(1)?)))
|
||||
}
|
||||
Some(_) => Err(bad()),
|
||||
}
|
||||
}
|
||||
|
||||
fn unlocked(s: &Session, id: LayerId) -> Result<()> {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let l = tl.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
if l.locked || tl.locked_by_folder(id) {
|
||||
return Err(EngineError::State(format!("layer '{}' is locked", l.name)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes instance `id` off the keyframe covering the playhead on layer `layer`.
|
||||
fn take_off(s: &mut Session, layer: LayerId, id: ElementId) -> Result<()> {
|
||||
let frame = s.frame;
|
||||
let l = s.layer_mut(Some(layer))?;
|
||||
if let Some(k) = l.keyframe_index_at(frame).and_then(|i| l.keyframe_mut(i)) {
|
||||
k.elements.retain(|e| e.id != id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A layer name `base_N` no layer of the scene has yet.
|
||||
fn fresh_name(s: &Session, base: &str) -> String {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
(1..).map(|n| format!("{base}{n}")).find(|n| tl.layers.iter().all(|l| &l.name != n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
/// Places the instances of every keyframe of `layer` by its pose (after the armature changed).
|
||||
fn rebake(layer: &mut Layer) {
|
||||
let Some(arm) = layer.armature.clone() else { return };
|
||||
for k in &mut layer.keyframes {
|
||||
let k = Arc::make_mut(k);
|
||||
let pose = k.pose.allowed(&arm);
|
||||
armature::apply(&arm, &mut k.elements, &pose);
|
||||
}
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let req = |k: &str| opt_u64(p, k)?.map(ElementId).ok_or_else(|| EngineError::Param(format!("param '{k}' (an instance id) is required")));
|
||||
let (from, to) = (req("from")?, req("to")?);
|
||||
let (head, tail) = (opt_point(p, "head")?, opt_point(p, "tail")?);
|
||||
let name = opt_str(p, "name")?.unwrap_or("").trim().to_string();
|
||||
if name.len() > MAX_NAME {
|
||||
return Err(EngineError::Param(format!("param 'name' must be at most {MAX_NAME} bytes")));
|
||||
}
|
||||
if from == to {
|
||||
return Err(EngineError::Param("a bone joins two different instances".into()));
|
||||
}
|
||||
let missing = |id: ElementId| EngineError::State(format!("no instance with id {} on the stage at frame {}", id.0, s.frame + 1));
|
||||
let f = find_instance(s, from).ok_or_else(|| missing(from))?;
|
||||
let t = find_instance(s, to).ok_or_else(|| missing(to))?;
|
||||
for x in [&f, &t] {
|
||||
if !matches!(x.el.kind, ElementKind::Symbol { .. }) {
|
||||
return Err(EngineError::State("bones join symbol instances: convert the artwork to a symbol first (Modify › Convert to Symbol, F8)".into()));
|
||||
}
|
||||
if !matches!(x.kind, LayerKind::Normal | LayerKind::Armature) {
|
||||
return Err(EngineError::State("bones join instances on normal layers (not on guide or mask layers)".into()));
|
||||
}
|
||||
unlocked(s, x.layer)?;
|
||||
}
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let arm_of = |x: &Found| (x.kind == LayerKind::Armature).then(|| tl.layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default());
|
||||
let (fa, ta) = (arm_of(&f), arm_of(&t));
|
||||
match (&fa, &ta) {
|
||||
(_, Some(a)) if f.layer == t.layer && a.bone_into(to).is_some() => return Err(EngineError::State("that instance already hangs from a bone; each instance has one bone into it".into())),
|
||||
(_, Some(_)) if f.layer == t.layer => return Err(EngineError::State("that instance is the armature's root: drag from the root to the other instances instead".into())),
|
||||
(None, Some(_)) => return Err(EngineError::State("start the bone on the armature: drag from one of its instances to the new one".into())),
|
||||
(Some(_), Some(_)) => return Err(EngineError::State("those instances are in different armatures".into())),
|
||||
_ => {}
|
||||
}
|
||||
if fa.as_ref().is_some_and(|a| a.bones.len() >= MAX_BONES) {
|
||||
return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones")));
|
||||
}
|
||||
let (wf, wt) = (f.el.transform, t.el.transform);
|
||||
let singular = || EngineError::State("an instance scaled to nothing can't hold a bone".into());
|
||||
let (inv_f, inv_t) = (wf.inverse().ok_or_else(singular)?, wt.inverse().ok_or_else(singular)?);
|
||||
// The joint: given, else the end of the bone into `from` (a chain joins end to start), else
|
||||
// its registration point.
|
||||
let into_from = fa.as_ref().and_then(|a| a.bone_into(from)).map(|b| wf.apply(b.tail));
|
||||
let head = head.or(into_from).unwrap_or(wf.translation());
|
||||
let tail = tail.unwrap_or(wt.translation());
|
||||
let rest = inv_f.mul(&wt);
|
||||
if !rest.is_finite() || rest.inverse().is_none() {
|
||||
return Err(singular());
|
||||
}
|
||||
let id = BoneId(s.doc.alloc_id());
|
||||
let bone = Bone { id, name, parent: from, child: to, head: inv_f.apply(head), tail: inv_t.apply(tail), rest, limits: None, pinned: false };
|
||||
take_off(s, t.layer, to)?;
|
||||
let lid = match fa {
|
||||
Some(_) => {
|
||||
// Another bone on this armature: the new instance joins every pose, at angle 0.
|
||||
let l = s.layer_mut(Some(f.layer))?;
|
||||
let mut arm = l.armature.as_deref().cloned().unwrap_or_default();
|
||||
arm.bones.push(bone);
|
||||
l.armature = Some(Arc::new(arm));
|
||||
for k in &mut l.keyframes {
|
||||
Arc::make_mut(k).elements.push(t.el.clone());
|
||||
}
|
||||
rebake(l);
|
||||
f.layer
|
||||
}
|
||||
None => {
|
||||
// The first bone: both instances move to a new armature layer above them, whose one
|
||||
// pose spans from their keyframe to the end of the timeline.
|
||||
let (start, end) = s.doc.timeline(s.scene).layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end()));
|
||||
let end = end.max(s.frame_count());
|
||||
take_off(s, f.layer, from)?;
|
||||
if s.doc.timeline(s.scene).layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let lid = LayerId(s.doc.alloc_id());
|
||||
let mut layer = Layer::new(lid, fresh_name(s, "Armature_"));
|
||||
layer.kind = LayerKind::Armature;
|
||||
// Bones show in the layer colour: a green that reads on light and dark artwork.
|
||||
layer.color = Rgba::hex(0x2fb67c);
|
||||
layer.armature = Some(Arc::new(Armature { bones: vec![bone] }));
|
||||
let mut k = Keyframe::new(start, end.saturating_sub(start).max(1));
|
||||
k.elements = vec![f.el.clone(), t.el.clone()];
|
||||
k.tween = Some(Tween::default());
|
||||
layer.keyframes = vec![Arc::new(k)];
|
||||
let index = f.index.min(t.index);
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
layer.parent = tl.container_at(index, LayerKind::Armature);
|
||||
tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer));
|
||||
tl.repair_masks();
|
||||
lid
|
||||
}
|
||||
};
|
||||
s.layer = lid;
|
||||
s.selection.clear();
|
||||
Ok(json!({"bone": id.0, "layer": lid.0, "created": lid != f.layer}))
|
||||
}
|
||||
|
||||
/// How many keyframes of an armature layer hold a pose of their own (more than one: the
|
||||
/// armature is animated).
|
||||
pub(crate) fn poses(l: &Layer) -> usize {
|
||||
l.keyframes.iter().filter(|k| !k.elements.is_empty()).count()
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = bone_param(p)?;
|
||||
let (lid, arm) = find_bone(s, id)?;
|
||||
unlocked(s, lid)?;
|
||||
let gone = arm.subtree(id);
|
||||
let mut left = (*arm).clone();
|
||||
left.bones.retain(|b| !gone.contains(&b.id));
|
||||
let dissolve = left.is_empty();
|
||||
let freed: Vec<ElementId> = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() };
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let (start, end) = (layer.keyframes.first().map_or(0, |k| k.start), layer.end_frame());
|
||||
// The freed instances as they look at the playhead (or at the armature's first frame).
|
||||
let at = s.frame.clamp(start, end.saturating_sub(1).max(start));
|
||||
let shown: Vec<Arc<Element>> = evaluate_layer_elements(layer, at).map(|(_, e)| e.iter().filter(|e| freed.contains(&e.id)).cloned().collect()).unwrap_or_default();
|
||||
let folder = layer.parent.filter(|p| tl.layer(*p).is_some_and(|x| x.kind == LayerKind::Folder));
|
||||
let new_id = LayerId(s.doc.alloc_id());
|
||||
let mut freed_layer = Layer::new(new_id, fresh_name(s, "Layer "));
|
||||
freed_layer.parent = folder;
|
||||
let mut k = Keyframe::new(start, end.saturating_sub(start).max(1));
|
||||
k.elements = shown;
|
||||
freed_layer.keyframes = vec![Arc::new(k)];
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
if dissolve {
|
||||
tl.layers.retain(|l| l.id != lid);
|
||||
tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer));
|
||||
} else {
|
||||
let l = tl.layer_mut(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
for k in &mut l.keyframes {
|
||||
let k = Arc::make_mut(k);
|
||||
k.elements.retain(|e| !freed.contains(&e.id));
|
||||
k.pose.retain(|b| !gone.contains(&b));
|
||||
}
|
||||
l.armature = Some(Arc::new(left));
|
||||
rebake(l);
|
||||
tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer));
|
||||
}
|
||||
tl.repair_masks();
|
||||
s.layer = if dissolve { new_id } else { lid };
|
||||
s.selection.clear();
|
||||
Ok(json!({"removed": gone.iter().map(|b| b.0).collect::<Vec<_>>(), "freed": freed.iter().map(|e| e.0).collect::<Vec<_>>(), "layer": new_id.0, "armature_removed": dissolve}))
|
||||
}
|
||||
|
||||
fn set_limits(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = bone_param(p)?;
|
||||
let constrain = opt_bool(p, "constrain")?;
|
||||
let (min, max) = (opt_f32(p, "min")?, opt_f32(p, "max")?);
|
||||
let deg = MAX_LIMIT.to_degrees();
|
||||
for v in [min, max].into_iter().flatten() {
|
||||
if !(-deg..=deg).contains(&v) {
|
||||
return Err(EngineError::Param(format!("joint limits must be between −{deg:.0}° and {deg:.0}°")));
|
||||
}
|
||||
}
|
||||
let (lid, arm) = find_bone(s, id)?;
|
||||
unlocked(s, lid)?;
|
||||
let cur = arm.bone(id).and_then(|b| b.limits);
|
||||
let limits = if constrain == Some(false) {
|
||||
None
|
||||
} else {
|
||||
// Turning limits on without numbers: a quarter turn either way.
|
||||
let base = cur.unwrap_or(Limits { min: -std::f32::consts::FRAC_PI_2, max: std::f32::consts::FRAC_PI_2 });
|
||||
let l = Limits { min: min.map_or(base.min, f32::to_radians), max: max.map_or(base.max, f32::to_radians) };
|
||||
if l.min > l.max {
|
||||
return Err(EngineError::Param("the joint's min must be at most its max".into()));
|
||||
}
|
||||
Some(l)
|
||||
};
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
let mut arm = (*arm).clone();
|
||||
if let Some(b) = arm.bone_mut(id) {
|
||||
b.limits = limits;
|
||||
}
|
||||
// Every pose keeps to the new limits.
|
||||
for k in &mut l.keyframes {
|
||||
if let Some(b) = arm.bone(id) {
|
||||
let a = k.pose.angle(id);
|
||||
if b.allow(a) != a {
|
||||
Arc::make_mut(k).pose.set(id, b.allow(a));
|
||||
}
|
||||
}
|
||||
}
|
||||
l.armature = Some(Arc::new(arm));
|
||||
rebake(l);
|
||||
Ok(json!({"bone": id.0, "constrain": limits.is_some(), "min": limits.map(|l| l.min.to_degrees()), "max": limits.map(|l| l.max.to_degrees())}))
|
||||
}
|
||||
|
||||
fn pin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = bone_param(p)?;
|
||||
let pinned = opt_bool(p, "pinned")?.ok_or_else(|| EngineError::Param("param 'pinned' (true or false) is required".into()))?;
|
||||
let (lid, arm) = find_bone(s, id)?;
|
||||
unlocked(s, lid)?;
|
||||
let mut arm = (*arm).clone();
|
||||
if let Some(b) = arm.bone_mut(id) {
|
||||
b.pinned = pinned;
|
||||
}
|
||||
s.layer_mut(Some(lid))?.armature = Some(Arc::new(arm));
|
||||
Ok(json!({"bone": id.0, "pinned": pinned}))
|
||||
}
|
||||
|
||||
/// Runs `edit` on the keyframe of armature layer `lid` that a pose at `frame` changes (keying
|
||||
/// the frame inside a pose tween, extending the layer past its end), then places the
|
||||
/// keyframe's instances by its pose.
|
||||
fn edit_pose<T>(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Armature, &mut Keyframe) -> Result<T>) -> Result<T> {
|
||||
if frame > MAX_FRAME {
|
||||
return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}")));
|
||||
}
|
||||
let arm = s.doc.timeline(s.scene).layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?;
|
||||
// Past the end a pose carries on from the last one (not a blank keyframe).
|
||||
{
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
if l.keyframe_at(frame).is_none() && frame >= l.end_frame() && !l.locked {
|
||||
insert_keyframe_at(l, frame, true)?;
|
||||
}
|
||||
}
|
||||
let (layer, at) = (s.layer, s.frame);
|
||||
s.layer = lid;
|
||||
s.frame = frame;
|
||||
let out = (|| {
|
||||
let kf = s.editable_keyframe_in(KeyEdit::Pose)?;
|
||||
let v = edit(&arm, kf)?;
|
||||
kf.pose = kf.pose.allowed(&arm);
|
||||
armature::apply(&arm, &mut kf.elements, &kf.pose);
|
||||
Ok(v)
|
||||
})();
|
||||
s.layer = layer;
|
||||
s.frame = at;
|
||||
out
|
||||
}
|
||||
|
||||
fn pose(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bone = opt_u64(p, "bone")?.map(BoneId);
|
||||
let (angle, rotate_by, dx, dy) = (opt_f32(p, "angle")?, opt_f32(p, "rotate_by")?, opt_f32(p, "dx")?, opt_f32(p, "dy")?);
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
|
||||
let lid = match (bone, opt_u64(p, "layer")?) {
|
||||
(Some(b), _) => find_bone(s, b)?.0,
|
||||
(None, Some(l)) => LayerId(l),
|
||||
(None, None) => s.layer,
|
||||
};
|
||||
if bone.is_none() && (angle.is_some() || rotate_by.is_some()) {
|
||||
return Err(EngineError::Param("param 'bone' says which joint 'angle' or 'rotate_by' turns".into()));
|
||||
}
|
||||
let v = edit_pose(s, lid, frame, |arm, kf| {
|
||||
let mut out = json!({"layer": lid.0});
|
||||
if let Some(b) = bone.and_then(|b| arm.bone(b)) {
|
||||
let cur = kf.pose.angle(b.id);
|
||||
let next = b.allow(angle.map_or(cur, f32::to_radians) + rotate_by.unwrap_or(0.0).to_radians());
|
||||
kf.pose.set(b.id, next);
|
||||
out["bone"] = json!(b.id.0);
|
||||
out["angle"] = json!(next.to_degrees());
|
||||
}
|
||||
if dx.is_some() || dy.is_some() {
|
||||
let by = Affine::translate(dx.unwrap_or(0.0), dy.unwrap_or(0.0));
|
||||
let roots = arm.roots();
|
||||
for e in kf.elements.iter_mut().filter(|e| roots.contains(&e.id)) {
|
||||
let m = by.mul(&e.transform);
|
||||
let t = m.translation();
|
||||
if m.is_finite() && t.x.abs() <= MAX_COORD && t.y.abs() <= MAX_COORD {
|
||||
Arc::make_mut(e).transform = m;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn solve(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = bone_param(p)?;
|
||||
let target = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
if target.x.abs() > MAX_COORD || target.y.abs() > MAX_COORD {
|
||||
return Err(EngineError::Param("the target must be within ±1,000,000 px".into()));
|
||||
}
|
||||
let local = opt_point(p, "local")?;
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
|
||||
let (lid, arm) = find_bone(s, id)?;
|
||||
if armature::movable_chain(&arm, id).is_empty() {
|
||||
return Err(EngineError::State("that bone is pinned, or hangs from a pinned bone: unpin it to drag it".into()));
|
||||
}
|
||||
let tail = arm.bone(id).map_or(Vec2::new(0.0, 0.0), |b| b.tail);
|
||||
edit_pose(s, lid, frame, |arm, kf| {
|
||||
let r = armature::solve(arm, &kf.elements, &kf.pose, id, local.unwrap_or(tail), target).ok_or_else(|| EngineError::State("the bone's instances aren't on this frame".into()))?;
|
||||
kf.pose = r.pose;
|
||||
Ok(json!({"bone": id.0, "reached": r.error <= 0.5, "error": r.error, "chain": r.chain}))
|
||||
})
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
|
||||
let only = opt_u64(p, "layer")?.map(LayerId);
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let deg = |v: f32| v.to_degrees();
|
||||
let pt = |v: Vec2| json!([v.x, v.y]);
|
||||
let list: Vec<Value> = tl
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.kind == LayerKind::Armature && only.is_none_or(|o| o == l.id))
|
||||
.filter_map(|l| {
|
||||
let arm = l.armature.as_deref()?;
|
||||
let pose = armature::pose_at(l, frame).unwrap_or_default();
|
||||
let (_, els) = evaluate_layer_elements(l, frame).unwrap_or((0, std::borrow::Cow::Borrowed(&[])));
|
||||
let at = armature::bones_at(arm, &els, &pose);
|
||||
let bones: Vec<Value> = arm
|
||||
.bones
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let g = at.iter().find(|g| g.id == b.id);
|
||||
json!({
|
||||
"id": b.id.0, "name": b.name, "from": b.parent.0, "to": b.child.0,
|
||||
"parent_bone": arm.parent_bone(b).map(|x| x.id.0),
|
||||
"head": g.map(|g| pt(g.head)), "tail": g.map(|g| pt(g.tail)),
|
||||
"angle": deg(b.allow(pose.angle(b.id))),
|
||||
"min": b.limits.map(|l| deg(l.min)), "max": b.limits.map(|l| deg(l.max)),
|
||||
"pinned": b.pinned,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::<Vec<_>>(), "poses": poses(l), "bones": bones}))
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"frame": frame, "armatures": list}))
|
||||
}
|
||||
@@ -170,10 +170,11 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
PaintMode::Behind => kf.elements.insert(0, Arc::new(el)),
|
||||
PaintMode::Normal | PaintMode::Fills => kf.elements.push(Arc::new(el)),
|
||||
}
|
||||
s.selection = vec![id];
|
||||
s.select_only([id]);
|
||||
return Ok(json!({"element": id.0, "elements": [id.0], "mode": mode.key(), "merged": false}));
|
||||
}
|
||||
s.selection = merge::merge_in_order(s, vec![el], mode.order())?;
|
||||
let ids: Vec<u64> = s.selection.iter().map(|e| e.0).collect();
|
||||
let merged = merge::merge_in_order(s, vec![el], mode.order())?;
|
||||
s.select_only(merged);
|
||||
let ids: Vec<u64> = s.selection.id_list();
|
||||
Ok(json!({"element": ids.first(), "elements": ids, "mode": mode.key(), "merged": true}))
|
||||
}
|
||||
@@ -132,7 +132,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.layer = id;
|
||||
s.frame = frame;
|
||||
let out: Result<Camera> = (|| {
|
||||
let kf = s.editable_keyframe_in(true)?;
|
||||
let kf = s.editable_keyframe_in(crate::KeyEdit::Camera)?;
|
||||
let i = match kf.elements.iter().position(|e| matches!(e.kind, ElementKind::Camera)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Drawing, selection, element and symbol commands.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use crate::{CommandSpec, EngineError, Result, Selection, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline};
|
||||
use anicraft_geom::{Affine, Decomposed, Path, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
@@ -10,36 +10,37 @@ use std::sync::Arc;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("draw.rect", "Rectangle", "", None, "{x, y, w, h, radius?, fill?, stroke?, stroke_width?, profile?, object?}", true, draw_rect as crate::RunFn),
|
||||
c("draw.ellipse", "Oval", "", None, "{x, y, w, h, fill?, stroke?, stroke_width?, profile?, object?}", true, draw_ellipse),
|
||||
c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, object?}", true, draw_star),
|
||||
c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line),
|
||||
c("draw.rect", "Rectangle", "", None, "{x, y, w, h, radius?, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}", true, draw_rect as crate::RunFn),
|
||||
c("draw.ellipse", "Oval", "", None, "{x, y, w, h, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}", true, draw_ellipse),
|
||||
c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, cap?, join?, style?, dash?, object?}", true, draw_star),
|
||||
c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (the line style, as stroke.set_style; default: the tool's), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line),
|
||||
c("draw.object_drawing", "Object Drawing", "", Some("J"), "{on?: bool} (default: toggle)", false, object_drawing),
|
||||
c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", None, "{on?: bool} (default: toggle) dragged points and selections snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point and raw.move_handle do nothing while it is off)", false, snap_to_objects),
|
||||
c("edit.select_all", "Select All", "Edit", Some("Ctrl+A"), "{}", false, select_all),
|
||||
c("edit.deselect", "Deselect All", "Edit", Some("Ctrl+Shift+A"), "{}", false, |s, _| {
|
||||
s.selection.clear();
|
||||
Ok(json!({"selected": 0}))
|
||||
}),
|
||||
c("edit.delete", "Clear", "Edit", Some("Delete"), "{}", true, delete),
|
||||
c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?}", true, duplicate),
|
||||
c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool}", false, select),
|
||||
c("element.pick", "Select at Point", "", None, "{x, y, add?: bool}", false, pick),
|
||||
c("element.translate", "Move", "", None, "{dx, dy}", true, translate),
|
||||
c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, set_transform),
|
||||
c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, set_fill),
|
||||
c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..]}", true, set_stroke),
|
||||
c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, set_alpha),
|
||||
c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, set_blend),
|
||||
c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, set_filters),
|
||||
c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, set_loop),
|
||||
c("edit.delete", "Clear", "Edit", Some("Delete"), "{} (on every layer with selected items)", true, delete_selection),
|
||||
c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?} (each copy on its original's layer)", true, |s, p| s.each_layer(true, |s| duplicate(s, p))),
|
||||
c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); the active layer becomes the first one's unless it has some of them", false, select),
|
||||
c("element.pick", "Select at Point", "", None, "{x, y, add?: bool} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer", false, pick),
|
||||
c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends (the nearest to `from`) then snaps onto a point, line or fill edge of the rest within that distance", true, translate),
|
||||
c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))),
|
||||
c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))),
|
||||
c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))),
|
||||
c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))),
|
||||
c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))),
|
||||
c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))),
|
||||
c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))),
|
||||
c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the selected instance's)}", true, set_symbol_kind),
|
||||
c("element.rename", "Instance Name", "", None, "{name}", true, rename),
|
||||
c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{}", true, |s, _| arrange(s, true)),
|
||||
c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{}", true, |s, _| arrange_step(s, true)),
|
||||
c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{}", true, |s, _| arrange_step(s, false)),
|
||||
c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{}", true, |s, _| arrange(s, false)),
|
||||
c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?}", true, convert_to_symbol),
|
||||
c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, break_apart),
|
||||
c("element.rename", "Instance Name", "", None, "{name}", true, |s, p| s.each_layer(true, |s| rename(s, p))),
|
||||
c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, true))),
|
||||
c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, true))),
|
||||
c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, false))),
|
||||
c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, false))),
|
||||
c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol),
|
||||
c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))),
|
||||
c("library.place", "Place Instance", "", None, "{symbol | bitmap, x?, y?}", true, place),
|
||||
]
|
||||
}
|
||||
@@ -65,6 +66,7 @@ pub(crate) fn style(s: &Session, p: &Value, closed: bool) -> Result<(Option<Pain
|
||||
None => s.style.stroke_width,
|
||||
};
|
||||
let profile = opt_profile(p, "profile")?.unwrap_or_else(|| s.style.profile());
|
||||
let line = opt_stroke_style(p, &s.style.line, width)?.unwrap_or_else(|| s.style.line.clone());
|
||||
let stroke = if p.get("stroke").is_some_and(Value::is_null) || width <= 0.0 {
|
||||
None
|
||||
} else {
|
||||
@@ -73,7 +75,7 @@ pub(crate) fn style(s: &Session, p: &Value, closed: bool) -> Result<(Option<Pain
|
||||
None => (s.style.use_stroke || !closed).then_some(Stroke::new(s.style.stroke, width)),
|
||||
}
|
||||
}
|
||||
.map(|st| st.with_profile(profile));
|
||||
.map(|st| st.with_profile(profile).with_style(line));
|
||||
if fill.is_none() && stroke.is_none() {
|
||||
return Err(EngineError::Param("shape would be invisible: give it a fill or a stroke".into()));
|
||||
}
|
||||
@@ -99,7 +101,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2,
|
||||
// A gradient or bitmap from the fill swatch is in stage space: it stays where it is on the
|
||||
// stage (Animate's Lock Fill after the Eyedropper).
|
||||
let fill = fill.map(|f| f.transformed(&Affine::translate(-origin.x, -origin.y)));
|
||||
let merge = !object && crate::merge::can_merge(fill.as_ref(), stroke.as_ref());
|
||||
let merge = !object && crate::merge::can_merge(stroke.as_ref());
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
@@ -109,8 +111,9 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2,
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge }),
|
||||
};
|
||||
if merge {
|
||||
s.selection = crate::merge::merge_in(s, vec![el])?;
|
||||
let ids: Vec<u64> = s.selection.iter().map(|e| e.0).collect();
|
||||
let merged = crate::merge::merge_in(s, vec![el])?;
|
||||
s.select_only(merged);
|
||||
let ids: Vec<u64> = s.selection.id_list();
|
||||
return Ok(json!({"element": ids.first(), "elements": ids, "kind": name, "merged": true}));
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
@@ -118,7 +121,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2,
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
}
|
||||
kf.elements.push(Arc::new(el));
|
||||
s.selection = vec![id];
|
||||
s.select_only([id]);
|
||||
Ok(json!({"element": id.0, "kind": name}))
|
||||
}
|
||||
|
||||
@@ -165,6 +168,11 @@ fn draw_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_shape(s, "line", Path::line(a - c, b - c), c, None, stroke, object_param(s, p)?)
|
||||
}
|
||||
|
||||
fn snap_to_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.style.snap_objects = opt_bool(p, "on")?.unwrap_or(!s.style.snap_objects);
|
||||
Ok(json!({"snap_to_objects": s.style.snap_objects}))
|
||||
}
|
||||
|
||||
fn object_drawing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.style.object_drawing = opt_bool(p, "on")?.unwrap_or(!s.style.object_drawing);
|
||||
Ok(json!({"object_drawing": s.style.object_drawing}))
|
||||
@@ -172,27 +180,63 @@ fn object_drawing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ----- selection --------------------------------------------------------------------------
|
||||
|
||||
/// Everything on every visible, unlocked layer at the playhead, as Animate's Select All.
|
||||
fn select_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.selection = s.visible_elements().iter().map(|e| e.id).collect();
|
||||
let layers: Vec<LayerId> = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect();
|
||||
let mut sel = Selection::default();
|
||||
for l in layers.into_iter().filter(|l| s.gathers(*l)) {
|
||||
sel.extend_on(l, s.elements_on(l).iter().map(|e| e.id));
|
||||
}
|
||||
s.selection = sel;
|
||||
Ok(json!({"selected": s.selection.len()}))
|
||||
}
|
||||
|
||||
/// Most ids `element.select` takes.
|
||||
const MAX_SELECT: usize = 100_000;
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = opt_u64_list(p, "ids")?.ok_or_else(|| EngineError::Param("param 'ids' is required".into()))?;
|
||||
if ids.len() > MAX_SELECT {
|
||||
return Err(EngineError::Param(format!("param 'ids' has more than {MAX_SELECT} ids")));
|
||||
}
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
let present: Vec<ElementId> = s.visible_elements().iter().map(|e| e.id).collect();
|
||||
// Where each element is at the playhead: on `layer`, else the active layer first, then the
|
||||
// others top to bottom.
|
||||
let order: Vec<LayerId> = match opt_u64(p, "layer")?.map(LayerId) {
|
||||
Some(l) if s.doc.timeline(s.scene).layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))),
|
||||
Some(l) => vec![l],
|
||||
None => std::iter::once(s.layer).chain(s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(),
|
||||
};
|
||||
let mut at: std::collections::HashMap<ElementId, LayerId> = std::collections::HashMap::new();
|
||||
for l in order {
|
||||
for e in s.elements_on(l) {
|
||||
at.entry(e.id).or_insert(l);
|
||||
}
|
||||
}
|
||||
let mut picked: Vec<(LayerId, ElementId)> = Vec::with_capacity(ids.len());
|
||||
for id in ids.into_iter().map(ElementId) {
|
||||
let Some(&l) = at.get(&id) else {
|
||||
return Err(EngineError::State(format!("element {} is not on the active layer, or any layer, at this frame", id.0)));
|
||||
};
|
||||
if !s.selectable(l) {
|
||||
let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
return Err(EngineError::State(format!("element {} is on layer '{name}', which is locked or hidden", id.0)));
|
||||
}
|
||||
picked.push((l, id));
|
||||
}
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
for id in ids.into_iter().map(ElementId) {
|
||||
if !present.contains(&id) {
|
||||
return Err(EngineError::State(format!("element {} is not on the active layer at this frame", id.0)));
|
||||
}
|
||||
if !s.selection.contains(&id) {
|
||||
s.selection.push(id);
|
||||
}
|
||||
for &(l, id) in &picked {
|
||||
s.selection.insert(l, id);
|
||||
}
|
||||
Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
// As a click does: the active layer is where the artwork is.
|
||||
if let Some(&(l, _)) = picked.first()
|
||||
&& !picked.iter().any(|(x, _)| *x == s.layer)
|
||||
{
|
||||
s.layer = l;
|
||||
}
|
||||
Ok(json!({"selected": s.selection.id_list()}))
|
||||
}
|
||||
|
||||
fn pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -200,19 +244,13 @@ fn pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
match s.hit_test(pt, 2.0) {
|
||||
Some((layer, el)) => {
|
||||
if layer != s.layer {
|
||||
s.layer = layer;
|
||||
s.selection.clear();
|
||||
}
|
||||
// Shift adds it to (or takes it from) the selection, whichever layers that is on.
|
||||
if add {
|
||||
if let Some(i) = s.selection.iter().position(|e| *e == el) {
|
||||
s.selection.remove(i);
|
||||
} else {
|
||||
s.selection.push(el);
|
||||
}
|
||||
} else if !s.selection.contains(&el) {
|
||||
s.selection = vec![el];
|
||||
s.selection.toggle(layer, el);
|
||||
} else if !s.selection.contains(layer, el) {
|
||||
s.selection = Selection::only(layer, [el]);
|
||||
}
|
||||
s.layer = layer;
|
||||
Ok(json!({"layer": layer.0, "element": el.0}))
|
||||
}
|
||||
None => {
|
||||
@@ -227,13 +265,39 @@ fn pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// ----- element edits ----------------------------------------------------------------------
|
||||
|
||||
fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (dx, dy) = (f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
let els = s.selected_elements_mut()?;
|
||||
let n = els.len();
|
||||
for e in els {
|
||||
e.transform = Affine::translate(dx, dy).mul(&e.transform);
|
||||
let (mut dx, mut dy) = (f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
let snap = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0));
|
||||
let from = match p.get("from").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => {
|
||||
let xy = v.as_array().filter(|a| a.len() == 2).and_then(|a| Some(Vec2::new(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32)));
|
||||
Some(xy.filter(|q| q.is_finite()).ok_or_else(|| EngineError::Param("param 'from' must be [x, y]".into()))?)
|
||||
}
|
||||
};
|
||||
let n = move_by(s, Vec2::new(dx, dy))?;
|
||||
// Snapping while dragging (ADR 0041): a little more, onto what is near.
|
||||
let mut snapped = Value::Null;
|
||||
if snap > 0.0
|
||||
&& let Some((extra, at, kind)) = crate::cmds_raw::snap_selection(s, snap, from)
|
||||
{
|
||||
move_by(s, extra)?;
|
||||
(dx, dy) = (dx + extra.x, dy + extra.y);
|
||||
snapped = json!({"x": at.x, "y": at.y, "to": kind.key()});
|
||||
}
|
||||
Ok(json!({"moved": n}))
|
||||
Ok(json!({"moved": n, "dx": dx, "dy": dy, "snapped": snapped}))
|
||||
}
|
||||
|
||||
/// Moves the selection by `d` on every layer it is on; how many elements moved.
|
||||
fn move_by(s: &mut Session, d: Vec2) -> Result<u64> {
|
||||
let v = s.each_layer(true, |s| {
|
||||
let els = s.selected_elements_mut()?;
|
||||
let n = els.len();
|
||||
for e in els {
|
||||
e.transform = Affine::translate(d.x, d.y).mul(&e.transform);
|
||||
}
|
||||
Ok(json!({"moved": n}))
|
||||
})?;
|
||||
Ok(v["moved"].as_u64().unwrap_or(0))
|
||||
}
|
||||
|
||||
fn set_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -306,12 +370,14 @@ fn set_stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let profile = opt_profile(p, "profile")?;
|
||||
let default = s.style.clone();
|
||||
// Checked once up front, so a bad style param changes nothing.
|
||||
opt_stroke_style(p, &default.line, default.stroke_width)?;
|
||||
for sh in shapes_mut(s)? {
|
||||
if remove {
|
||||
sh.stroke = None;
|
||||
continue;
|
||||
}
|
||||
let mut st = sh.stroke.take().unwrap_or_else(|| Stroke::new(default.stroke, default.stroke_width).with_profile(default.profile()));
|
||||
let mut st = sh.stroke.take().unwrap_or_else(|| default.new_stroke(default.stroke, default.stroke_width));
|
||||
if let Some(c) = color {
|
||||
st.color = c;
|
||||
}
|
||||
@@ -321,6 +387,9 @@ fn set_stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(pr) = &profile {
|
||||
st = st.with_profile(pr.clone());
|
||||
}
|
||||
if let Some(line) = opt_stroke_style(p, &st.style, st.width)? {
|
||||
st = st.with_style(line);
|
||||
}
|
||||
sh.stroke = (st.width > 0.0).then_some(st);
|
||||
}
|
||||
Ok(json!({"ok": true}))
|
||||
@@ -467,8 +536,8 @@ fn set_symbol_kind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(id) => SymbolId(id),
|
||||
None => {
|
||||
// The symbol of the selected instance.
|
||||
let sel = s.selection.first().copied().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?;
|
||||
s.visible_elements()
|
||||
let (layer, sel) = s.selection.first().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?;
|
||||
s.elements_on(layer)
|
||||
.iter()
|
||||
.find(|e| e.id == sel)
|
||||
.and_then(|e| match e.kind {
|
||||
@@ -491,8 +560,13 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"name": name}))
|
||||
}
|
||||
|
||||
pub(crate) fn delete(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
/// Clear: the selection goes, on every layer it is on.
|
||||
pub(crate) fn delete_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.each_layer(true, |s| delete(s, p))
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let sel = s.selection.on(s.layer);
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
@@ -507,7 +581,7 @@ pub(crate) fn delete(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dx = opt_f32(p, "dx")?.unwrap_or(10.0);
|
||||
let dy = opt_f32(p, "dy")?.unwrap_or(10.0);
|
||||
let sel = s.selection.clone();
|
||||
let sel = s.selection.on(s.layer);
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
@@ -521,12 +595,12 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
out.push(Arc::new(e));
|
||||
}
|
||||
s.editable_keyframe()?.elements.extend(out);
|
||||
s.selection = new_ids.clone();
|
||||
s.select_only(new_ids.iter().copied());
|
||||
Ok(json!({"created": new_ids.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn arrange(s: &mut Session, front: bool) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
let sel = s.selection.on(s.layer);
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
@@ -539,7 +613,7 @@ fn arrange(s: &mut Session, front: bool) -> Result<Value> {
|
||||
/// Bring Forward / Send Backward: each selected element swaps with the unselected neighbour
|
||||
/// above (or below) it; a selected block moves as one, keeping its order.
|
||||
fn arrange_step(s: &mut Session, forward: bool) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
let sel = s.selection.on(s.layer);
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
@@ -565,31 +639,22 @@ fn arrange_step(s: &mut Session, forward: bool) -> Result<Value> {
|
||||
|
||||
// ----- symbols ----------------------------------------------------------------------------
|
||||
|
||||
/// Convert to Symbol. The registration point is the centre of the selection's bounds. A
|
||||
/// selection on several layers becomes one symbol with those layers inside it (named and
|
||||
/// stacked as they are), and its instance lands on the topmost of them, where its first
|
||||
/// selected element was; the other layers lose what was selected (ADR 0044).
|
||||
pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
let layers = s.selected_layers();
|
||||
let Some(&top) = layers.first() else {
|
||||
return Err(EngineError::State("select something to convert".into()));
|
||||
}
|
||||
};
|
||||
let n = s.doc.library.len() + 1;
|
||||
let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}"));
|
||||
let bounds = s.selection_bounds();
|
||||
let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() };
|
||||
let sym_id = SymbolId(s.doc.alloc_id());
|
||||
let layer_id = LayerId(s.doc.alloc_id());
|
||||
let first_layer = LayerId(s.doc.alloc_id());
|
||||
let inst_id = ElementId(s.doc.alloc_id());
|
||||
let kf = s.editable_keyframe()?;
|
||||
let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len());
|
||||
let (picked, rest): (Vec<Arc<Element>>, Vec<Arc<Element>>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id));
|
||||
// Children are stored relative to the registration point (the selection centre).
|
||||
let to_local = Affine::translate(-center.x, -center.y);
|
||||
let children: Vec<Arc<Element>> = picked
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let mut e = Arc::unwrap_or_clone(e);
|
||||
e.transform = to_local.mul(&e.transform);
|
||||
Arc::new(e)
|
||||
})
|
||||
.collect();
|
||||
let instance = Element {
|
||||
id: inst_id,
|
||||
name: String::new(),
|
||||
@@ -597,20 +662,46 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() },
|
||||
};
|
||||
let mut elements = rest;
|
||||
elements.insert(first_pos.min(elements.len()), Arc::new(instance));
|
||||
kf.elements = elements;
|
||||
let mut layer = Layer::new(layer_id, "Layer 1");
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.elements = children;
|
||||
// Children are stored relative to the registration point (the selection centre).
|
||||
let to_local = Affine::translate(-center.x, -center.y);
|
||||
let single = layers.len() == 1;
|
||||
let mut inner: Vec<Arc<Layer>> = Vec::with_capacity(layers.len());
|
||||
for l in layers {
|
||||
let sel = s.selection.on(l);
|
||||
let source = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
let picked = s.with_layer(l, |s| -> Result<Vec<Arc<Element>>> {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len());
|
||||
let (picked, mut rest): (Vec<Arc<Element>>, Vec<Arc<Element>>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id));
|
||||
if l == top {
|
||||
rest.insert(first_pos.min(rest.len()), Arc::new(instance.clone()));
|
||||
}
|
||||
kf.elements = rest;
|
||||
Ok(picked)
|
||||
})?;
|
||||
let children: Vec<Arc<Element>> = picked
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let mut e = Arc::unwrap_or_clone(e);
|
||||
e.transform = to_local.mul(&e.transform);
|
||||
Arc::new(e)
|
||||
})
|
||||
.collect();
|
||||
let id = if inner.is_empty() { first_layer } else { LayerId(s.doc.alloc_id()) };
|
||||
let mut layer = Layer::new(id, if single { "Layer 1".to_string() } else { source });
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.elements = children;
|
||||
}
|
||||
inner.push(Arc::new(layer));
|
||||
}
|
||||
s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(layer)] } }));
|
||||
s.selection = vec![inst_id];
|
||||
Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name}))
|
||||
s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: inner } }));
|
||||
s.layer = top;
|
||||
s.select_only([inst_id]);
|
||||
Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0}))
|
||||
}
|
||||
|
||||
fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
let sel = s.selection.on(s.layer);
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
@@ -657,7 +748,7 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
return Err(EngineError::State("the selection has no symbol instances or text to break apart".into()));
|
||||
}
|
||||
s.editable_keyframe()?.elements = out;
|
||||
s.selection = fresh_ids.clone();
|
||||
s.select_only(fresh_ids.iter().copied());
|
||||
Ok(json!({"created": fresh_ids.len()}))
|
||||
}
|
||||
|
||||
@@ -682,7 +773,7 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
kind: ElementKind::Symbol { symbol: sym, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() },
|
||||
};
|
||||
s.editable_keyframe()?.elements.push(Arc::new(el));
|
||||
s.selection = vec![id];
|
||||
s.select_only([id]);
|
||||
Ok(json!({"element": id.0}))
|
||||
}
|
||||
|
||||
@@ -708,6 +799,6 @@ fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> R
|
||||
}),
|
||||
};
|
||||
s.editable_keyframe()?.elements.push(Arc::new(el));
|
||||
s.selection = vec![id];
|
||||
s.select_only([id]);
|
||||
Ok(json!({"element": id.0}))
|
||||
}
|
||||
@@ -101,7 +101,7 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start:
|
||||
EraseMode::Fills => (fills.clone(), touching.clone()),
|
||||
// Only the lines take part, so the fills stay exactly as they are.
|
||||
EraseMode::Lines => (lines.clone(), lines.clone()),
|
||||
EraseMode::SelectedFills => (fills.iter().copied().filter(|i| el(i).is_some_and(|e| s.selection.contains(&e.id))).collect(), touching.clone()),
|
||||
EraseMode::SelectedFills => (fills.iter().copied().filter(|i| el(i).is_some_and(|e| s.selection.contains(s.layer, e.id))).collect(), touching.clone()),
|
||||
EraseMode::Inside => {
|
||||
// The topmost raw fill under the start of the stroke.
|
||||
let at = fills.iter().rev().copied().find(|i| el(i).is_some_and(|e| mergeable(e).is_some_and(|sh| sh.path.contains(start, &e.transform, sh.fill_rule))));
|
||||
@@ -111,7 +111,7 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start:
|
||||
if targets.is_empty() {
|
||||
s.doc = before;
|
||||
return nothing(match mode {
|
||||
EraseMode::SelectedFills if s.selection.is_empty() => "select the fills to erase first",
|
||||
EraseMode::SelectedFills if s.selection.on(s.layer).is_empty() => "select the fills to erase first",
|
||||
EraseMode::Inside => "start the stroke on a fill to erase inside it",
|
||||
_ => "nothing raw to erase there",
|
||||
});
|
||||
@@ -120,8 +120,9 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start:
|
||||
// cut the fills they cross and nothing hides them).
|
||||
let rest: Vec<usize> = members.iter().copied().filter(|i| !targets.contains(i)).collect();
|
||||
let (rest_fills, rest_lines): (Vec<usize>, Vec<usize>) = rest.into_iter().partition(is_fill);
|
||||
let here = s.layer;
|
||||
let selected = s.selection.clone();
|
||||
let shape = |i: &usize| el(i).map(|e| Part::Shape(e, selected.contains(&e.id)));
|
||||
let shape = |i: &usize| el(i).map(|e| Part::Shape(e, selected.contains(here, e.id)));
|
||||
let parts: Vec<Part> = targets.iter().filter_map(shape).chain(std::iter::once(Part::Eraser(eraser))).chain(rest_fills.iter().filter_map(shape)).chain(rest_lines.iter().filter_map(shape)).collect();
|
||||
let Some((out, picked)) = merge::remerge(s, &parts) else {
|
||||
s.doc = before;
|
||||
@@ -139,8 +140,8 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start:
|
||||
let gone: Vec<ElementId> = members.iter().filter_map(el).map(|e| e.id).collect();
|
||||
merge::replace(s, &members, out, false)?;
|
||||
// What stays selected: the rest of the selection, and what is left of selected shapes.
|
||||
s.selection.retain(|id| !gone.contains(id));
|
||||
s.selection.extend(picked);
|
||||
s.selection.retain(|l, id| l != here || !gone.contains(&id));
|
||||
s.selection.extend_on(here, picked);
|
||||
Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0)}))
|
||||
}
|
||||
|
||||
@@ -258,7 +259,8 @@ fn faucet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (id, line) = (hit.id, matches!(&hit.kind, ElementKind::Shape(sh) if sh.fill.is_none()));
|
||||
let kf = s.editable_keyframe()?;
|
||||
kf.elements.retain(|e| e.id != id);
|
||||
s.selection.retain(|x| *x != id);
|
||||
let here = s.layer;
|
||||
s.selection.remove(here, id);
|
||||
Ok(json!({"deleted": id.0, "kind": if line { "line" } else { "fill" }}))
|
||||
}
|
||||
|
||||
|
||||
@@ -168,14 +168,19 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
anicraft_xfl::import_path(&path)
|
||||
};
|
||||
let (doc, report) = imported.map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?;
|
||||
let (mut doc, report) = imported.map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?;
|
||||
// Raw artwork arrives one shape per style: each keyframe's becomes one merged drawing,
|
||||
// as it was in Animate (ADR 0042).
|
||||
let merged = crate::merge::merge_document(&mut doc);
|
||||
s.replace_document(doc, None);
|
||||
let mut info = s.info();
|
||||
info["imported"] = json!(path.display().to_string());
|
||||
info["report"] = json!(report.summary());
|
||||
info["skipped"] = json!(report.skipped);
|
||||
info["kept"] = json!(report.kept);
|
||||
info["runs"] = json!(report.runs);
|
||||
info["missing_fonts"] = json!(report.missing_fonts);
|
||||
info["merged_keyframes"] = json!(merged);
|
||||
return Ok(info);
|
||||
}
|
||||
let doc = format::load(&path)?;
|
||||
@@ -347,7 +352,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.layer = lid;
|
||||
(lid, ids, made, Some(fid.0))
|
||||
};
|
||||
s.selection = ids.clone();
|
||||
s.select_only(ids.iter().copied());
|
||||
Ok(json!({
|
||||
"layer": layer_id.0,
|
||||
"folder": folder,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, Symbol, SymbolId};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Symbol, SymbolId};
|
||||
use anicraft_geom::{Affine, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashSet;
|
||||
@@ -12,15 +12,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("edit.cut", "Cut", "Edit", Some("Ctrl+X"), "{}", true, cut as crate::RunFn),
|
||||
c("edit.copy", "Copy", "Edit", Some("Ctrl+C"), "{}", false, copy),
|
||||
c("edit.paste", "Paste in Center", "Edit", Some("Ctrl+V"), "{x?, y?} (centre of the pasted artwork; default: offset 10 px)", true, paste),
|
||||
c("edit.paste_in_place", "Paste in Place", "Edit", Some("Ctrl+Shift+V"), "{}", true, paste_in_place),
|
||||
c("modify.transform", "Transform", "", None, "{a, b, c, d, e, f} affine applied in stage space (free transform)", true, transform),
|
||||
c("edit.copy", "Copy", "Edit", Some("Ctrl+C"), "{} (the selection on every layer, each layer's artwork kept apart)", false, copy),
|
||||
c("edit.paste", "Paste in Center", "Edit", Some("Ctrl+V"), "{x?, y?} (centre of the pasted artwork; default: offset 10 px). Artwork copied from one layer lands on the active layer; from several, back on those layers when they are all here, else on the active layer and the ones below it, creating missing ones", true, paste),
|
||||
c("edit.paste_in_place", "Paste in Place", "Edit", Some("Ctrl+Shift+V"), "{} (layers as edit.paste)", true, paste_in_place),
|
||||
c("modify.transform", "Transform", "", None, "{a, b, c, d, e, f} affine applied in stage space (free transform), to the selection on every layer", true, |s, p| s.each_layer(true, |s| transform(s, p))),
|
||||
c("modify.rotate_cw", "Rotate 90° CW", "Modify/Transform", Some("Ctrl+Shift+9"), "{}", true, |s, _| about_center(s, Affine::rotate(std::f32::consts::FRAC_PI_2))),
|
||||
c("modify.rotate_ccw", "Rotate 90° CCW", "Modify/Transform", Some("Ctrl+Shift+7"), "{}", true, |s, _| about_center(s, Affine::rotate(-std::f32::consts::FRAC_PI_2))),
|
||||
c("modify.flip_h", "Flip Horizontal", "Modify/Transform", None, "{}", true, |s, _| about_center(s, Affine::scale(-1.0, 1.0))),
|
||||
c("modify.flip_v", "Flip Vertical", "Modify/Transform", None, "{}", true, |s, _| about_center(s, Affine::scale(1.0, -1.0))),
|
||||
c("modify.remove_transform", "Remove Transform", "Modify/Transform", Some("Ctrl+Shift+Z"), "{}", true, remove_transform),
|
||||
c("modify.remove_transform", "Remove Transform", "Modify/Transform", Some("Ctrl+Shift+Z"), "{}", true, |s, p| s.each_layer(true, |s| remove_transform(s, p))),
|
||||
c("align.left", "Left", "Modify/Align", Some("Ctrl+Alt+1"), "{to_stage?}", true, |s, p| align(s, p, Edge::Left)),
|
||||
c("align.hcenter", "Horizontal Center", "Modify/Align", Some("Ctrl+Alt+2"), "{to_stage?}", true, |s, p| align(s, p, Edge::HCenter)),
|
||||
c("align.right", "Right", "Modify/Align", Some("Ctrl+Alt+3"), "{to_stage?}", true, |s, p| align(s, p, Edge::Right)),
|
||||
@@ -34,17 +34,34 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
// ----- clipboard --------------------------------------------------------------------------------
|
||||
|
||||
/// Copied artwork: elements as they look at the playhead, plus every symbol they need, so a
|
||||
/// paste into another document is complete.
|
||||
/// Copied artwork: elements as they look at the playhead, kept apart by the layer they came from,
|
||||
/// plus every symbol they need, so a paste into another document is complete.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Clipboard {
|
||||
pub elements: Vec<Element>,
|
||||
/// One entry per layer the selection was on, top to bottom.
|
||||
pub layers: Vec<ClipLayer>,
|
||||
pub symbols: Vec<Arc<Symbol>>,
|
||||
}
|
||||
|
||||
/// One layer's copied artwork.
|
||||
#[derive(Clone)]
|
||||
pub struct ClipLayer {
|
||||
/// The layer it came from, and its name (for a layer a paste has to create).
|
||||
pub layer: LayerId,
|
||||
pub name: String,
|
||||
pub elements: Vec<Element>,
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.elements.is_empty()
|
||||
self.layers.iter().all(|l| l.elements.is_empty())
|
||||
}
|
||||
/// Every copied element, layer by layer.
|
||||
pub fn elements(&self) -> impl Iterator<Item = &Element> {
|
||||
self.layers.iter().flat_map(|l| l.elements.iter())
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.layers.iter().map(|l| l.elements.len()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,26 +93,35 @@ pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec<Arc<Symbol>
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
let layers = s.selected_layers();
|
||||
if layers.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
// What you see is what you copy: the evaluated state at the playhead (tweens applied).
|
||||
let elements: Vec<Element> = s.visible_elements().iter().filter(|e| sel.contains(&e.id)).map(|e| (**e).clone()).collect();
|
||||
let symbols = collect_symbols(s, &elements);
|
||||
let n = elements.len();
|
||||
s.clipboard = Clipboard { elements, symbols };
|
||||
Ok(json!({"copied": n}))
|
||||
let mut copied = Vec::with_capacity(layers.len());
|
||||
for l in layers {
|
||||
let elements: Vec<Element> = s.elements_on(l).iter().filter(|e| s.selection.contains(l, e.id)).map(|e| (**e).clone()).collect();
|
||||
let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
if !elements.is_empty() {
|
||||
copied.push(ClipLayer { layer: l, name, elements });
|
||||
}
|
||||
}
|
||||
let all: Vec<Element> = copied.iter().flat_map(|c| c.elements.iter().cloned()).collect();
|
||||
let symbols = collect_symbols(s, &all);
|
||||
let n = all.len();
|
||||
let layers = copied.len();
|
||||
s.clipboard = Clipboard { layers: copied, symbols };
|
||||
Ok(json!({"copied": n, "layers": layers}))
|
||||
}
|
||||
|
||||
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
copy(s, p)?;
|
||||
crate::cmds_draw::delete(s, p)?;
|
||||
Ok(json!({"cut": s.clipboard.elements.len()}))
|
||||
crate::cmds_draw::delete_selection(s, p)?;
|
||||
Ok(json!({"cut": s.clipboard.len()}))
|
||||
}
|
||||
|
||||
fn clipboard_bounds(s: &Session) -> Rect {
|
||||
s.clipboard.elements.iter().fold(Rect::EMPTY, |r, e| r.union(&clip_element_bounds(s, e)))
|
||||
s.clipboard.elements().fold(Rect::EMPTY, |r, e| r.union(&clip_element_bounds(s, e)))
|
||||
}
|
||||
|
||||
fn clip_element_bounds(s: &Session, e: &Element) -> Rect {
|
||||
@@ -109,27 +135,103 @@ fn clip_element_bounds(s: &Session, e: &Element) -> Rect {
|
||||
e.bounds(&doc)
|
||||
}
|
||||
|
||||
/// The layers a paste puts each copied layer's artwork on (ADR 0044). One copied layer goes on
|
||||
/// the active layer. Several go back on the layers they came from when every one of them is in
|
||||
/// this scene (same id and name) and can be drawn on; else on the active layer and the drawable
|
||||
/// layers below it, in order, with missing layers created at the bottom named after the copied
|
||||
/// ones, as Paste Frames does.
|
||||
fn paste_targets(s: &mut Session) -> Result<Vec<LayerId>> {
|
||||
let n = s.clipboard.layers.len();
|
||||
if n <= 1 {
|
||||
return Ok(vec![s.layer]);
|
||||
}
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let drawable = |s: &Session, l: &Layer| s.selectable(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature);
|
||||
let home: Vec<LayerId> = s.clipboard.layers.iter().filter_map(|c| tl.layer(c.layer).filter(|l| l.name == c.name && drawable(s, l)).map(|l| l.id)).collect();
|
||||
if home.len() == n {
|
||||
return Ok(home);
|
||||
}
|
||||
let at = s.active_layer_index().unwrap_or(0);
|
||||
let mut out = vec![s.layer];
|
||||
out.extend(tl.layers.iter().skip(at + 1).filter(|l| drawable(s, l)).map(|l| l.id).take(n - 1));
|
||||
let names: Vec<String> = s.clipboard.layers.iter().skip(out.len()).map(|c| c.name.clone()).collect();
|
||||
for name in names {
|
||||
if s.doc.timeline(s.scene).layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let id = LayerId(s.doc.alloc_id());
|
||||
let count = s.doc.timeline(s.scene).layers.len();
|
||||
let mut layer = Layer::new(id, name);
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.duration = s.frame_count().max(1);
|
||||
}
|
||||
layer.color = crate::cmds_timeline::layer_color(count + 1);
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
tl.layers.push(Arc::new(layer));
|
||||
tl.repair_masks();
|
||||
out.push(id);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn paste_with(s: &mut Session, offset: Vec2) -> Result<Value> {
|
||||
if s.clipboard.is_empty() {
|
||||
return Err(EngineError::State("the clipboard is empty".into()));
|
||||
}
|
||||
import_symbols(s, &s.clipboard.symbols.clone());
|
||||
let targets = paste_targets(s)?;
|
||||
let copied = s.clipboard.layers.clone();
|
||||
let mut sel = crate::Selection::default();
|
||||
let mut all = Vec::new();
|
||||
let mut merged = false;
|
||||
for (c, &layer) in copied.iter().zip(&targets) {
|
||||
let (fresh, m) = s.with_layer(layer, |s| paste_layer(s, &c.elements, offset))?;
|
||||
merged |= m;
|
||||
all.extend(fresh.iter().map(|e| e.0));
|
||||
sel.extend_on(layer, fresh);
|
||||
}
|
||||
s.selection = sel;
|
||||
if let Some(&first) = targets.first()
|
||||
&& targets.len() > 1
|
||||
{
|
||||
s.layer = first;
|
||||
}
|
||||
let mut v = json!({"pasted": all, "merged": merged});
|
||||
if targets.len() > 1 {
|
||||
v["layers"] = json!(targets.iter().map(|l| l.0).collect::<Vec<_>>());
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Pastes `elements` moved by `offset` into the active layer's keyframe at the playhead; their
|
||||
/// new ids, and whether raw shapes merged.
|
||||
fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec<ElementId>, bool)> {
|
||||
let mut fresh = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for e in s.clipboard.elements.clone() {
|
||||
let mut raw = Vec::new();
|
||||
for e in elements.iter().cloned() {
|
||||
let mut e = e;
|
||||
e.id = ElementId(s.doc.alloc_id());
|
||||
e.transform = Affine::translate(offset.x, offset.y).mul(&e.transform);
|
||||
fresh.push(e.id);
|
||||
out.push(Arc::new(e));
|
||||
// Raw shapes go into the drawing where they land, cutting and joining what they touch
|
||||
// (ADR 0042); objects go on top.
|
||||
if crate::merge::mergeable(&e).is_some() {
|
||||
raw.push(e);
|
||||
} else {
|
||||
fresh.push(e.id);
|
||||
out.push(Arc::new(e));
|
||||
}
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() + out.len() > 100_000 {
|
||||
if kf.elements.len() + out.len() + raw.len() > 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
}
|
||||
kf.elements.extend(out);
|
||||
s.selection = fresh.clone();
|
||||
Ok(json!({"pasted": fresh.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
let merged = !raw.is_empty();
|
||||
if merged {
|
||||
fresh.extend(crate::merge::merge_in(s, raw)?);
|
||||
}
|
||||
Ok((fresh, merged))
|
||||
}
|
||||
|
||||
/// Adds the symbols this document lacks (from a clipboard, maybe another document's) and
|
||||
@@ -207,6 +309,7 @@ fn remove_transform(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"reset": n}))
|
||||
}
|
||||
|
||||
/// `m` about the centre of the whole selection's bounds, on every layer it is on.
|
||||
fn about_center(s: &mut Session, m: Affine) -> Result<Value> {
|
||||
let b = s.selection_bounds();
|
||||
if b.is_empty() {
|
||||
@@ -214,8 +317,7 @@ fn about_center(s: &mut Session, m: Affine) -> Result<Value> {
|
||||
}
|
||||
let c = b.center();
|
||||
let full = Affine::translate(c.x, c.y).mul(&m).mul(&Affine::translate(-c.x, -c.y));
|
||||
let n = apply(s, &full)?;
|
||||
Ok(json!({"transformed": n}))
|
||||
s.each_layer(true, |s| Ok(json!({"transformed": apply(s, &full)?})))
|
||||
}
|
||||
|
||||
// ----- align ------------------------------------------------------------------------------------
|
||||
@@ -230,7 +332,10 @@ enum Edge {
|
||||
Bottom,
|
||||
}
|
||||
|
||||
fn moves_for(bounds: &[(ElementId, Rect)], target: Rect, edge: Edge) -> Vec<(ElementId, Vec2)> {
|
||||
/// A selected element: its layer and id.
|
||||
type Item = (LayerId, ElementId);
|
||||
|
||||
fn moves_for(bounds: &[(Item, Rect)], target: Rect, edge: Edge) -> Vec<(Item, Vec2)> {
|
||||
bounds
|
||||
.iter()
|
||||
.map(|(id, b)| {
|
||||
@@ -247,23 +352,38 @@ fn moves_for(bounds: &[(ElementId, Rect)], target: Rect, edge: Edge) -> Vec<(Ele
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn translate_each(s: &mut Session, moves: &[(ElementId, Vec2)]) -> Result<usize> {
|
||||
let kf = s.editable_keyframe()?;
|
||||
/// Moves each element by its own amount, on its own layer.
|
||||
fn translate_each(s: &mut Session, moves: &[(Item, Vec2)]) -> Result<usize> {
|
||||
let mut layers: Vec<LayerId> = Vec::new();
|
||||
for ((l, _), _) in moves {
|
||||
if !layers.contains(l) {
|
||||
layers.push(*l);
|
||||
}
|
||||
}
|
||||
let mut n = 0;
|
||||
for (id, d) in moves {
|
||||
if d.x == 0.0 && d.y == 0.0 {
|
||||
continue; // untouched elements stay shared with the undo snapshot
|
||||
}
|
||||
for e in kf.elements_mut_where(|e| e == *id) {
|
||||
e.transform = Affine::translate(d.x, d.y).mul(&e.transform);
|
||||
n += 1;
|
||||
for layer in layers {
|
||||
let mine: Vec<(ElementId, Vec2)> = moves.iter().filter(|((l, _), d)| *l == layer && (d.x != 0.0 || d.y != 0.0)).map(|((_, id), d)| (*id, *d)).collect();
|
||||
if mine.is_empty() {
|
||||
continue; // untouched layers stay shared with the undo snapshot
|
||||
}
|
||||
n += s.with_layer(layer, |s| -> Result<usize> {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let mut n = 0;
|
||||
for (id, d) in &mine {
|
||||
for e in kf.elements_mut_where(|e| e == *id) {
|
||||
e.transform = Affine::translate(d.x, d.y).mul(&e.transform);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(n)
|
||||
})?;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn selected_bounds(s: &Session) -> Vec<(ElementId, Rect)> {
|
||||
s.selection.iter().map(|id| (*id, s.element_bounds(*id))).filter(|(_, b)| !b.is_empty()).collect()
|
||||
/// Each selected element's bounds, over every layer: alignment works across layers.
|
||||
fn selected_bounds(s: &Session) -> Vec<(Item, Rect)> {
|
||||
s.selected_elements().iter().map(|(l, e)| ((*l, e.id), s.element_bounds_on(*l, e.id))).filter(|(_, b)| !b.is_empty()).collect()
|
||||
}
|
||||
|
||||
fn align(s: &mut Session, p: &Value, edge: Edge) -> Result<Value> {
|
||||
@@ -293,7 +413,7 @@ fn distribute(s: &mut Session, horizontal: bool) -> Result<Value> {
|
||||
let (Some(first), Some(last)) = (bounds.first(), bounds.last()) else { return Ok(json!({"moved": 0})) };
|
||||
let (a, z) = (key(&first.1), key(&last.1));
|
||||
let step = (z - a) / (bounds.len() - 1) as f32;
|
||||
let moves: Vec<(ElementId, Vec2)> = bounds
|
||||
let moves: Vec<(Item, Vec2)> = bounds
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (id, b))| {
|
||||
|
||||
@@ -6,11 +6,16 @@
|
||||
//! [`begin_edit`] swaps the target for how it looks at the playhead, and after the command
|
||||
//! [`finish_edit`] turns whatever changed in its transform or colour effect into property keys
|
||||
//! and puts the base object back (with any other change, a new fill say, kept).
|
||||
//!
|
||||
//! On a motion path, moving the object at a frame pins the path there (ADR 0049): the anchor
|
||||
//! pinned to that frame moves (an end, at the first or last position key), or a new anchor is
|
||||
//! added where the object is, pinned to the frame, and moved; after the last position key the
|
||||
//! path carries on to where the object was put.
|
||||
|
||||
use crate::cmds_timeline::target;
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Property, Props};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
@@ -21,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|tint, value (px, %, °), frame?, layer?}", true, set_key as crate::RunFn),
|
||||
c("motion.remove_key", "Remove Property Keyframe", "", None, "{property? (default: every property), frame?, layer?}", true, remove_key),
|
||||
c("motion.set_ease", "Property Ease", "", None, "{easing, property? (default: every property), frame? (inside the segment), layer?}", true, set_ease),
|
||||
c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path and where the object is", false, info),
|
||||
c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is", false, info),
|
||||
c("motion.set_path", "Edit Motion Path", "", None, "{d: SVG path data in stage space (its first subpath; ends are the start and end positions), layer?, frame?}", true, set_path),
|
||||
c("motion.clear_path", "Remove Motion Path", "", None, "{layer?, frame?}: back to the straight path the X/Y curves trace", true, clear_path),
|
||||
c("motion.orient", "Orient to Path", "", None, "{orient: bool, layer?, frame?}: turn the object as its motion path turns", true, orient),
|
||||
@@ -29,6 +34,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("motion.delete_points", "Delete Motion Path Points", "", None, "{anchors: [index, ..] (as motion.info lists them; the ends stay), layer?, frame?}: the path refits through the rest", true, delete_points),
|
||||
c("motion.convert_point", "Convert Motion Path Point", "", None, "{anchor, smooth: bool, layer?, frame?}: smooth (handles in line) or corner (handles on the anchor)", true, convert_point),
|
||||
c("motion.move_path", "Move Motion Path", "", None, "{dx, dy, layer?, frame?}: the whole path with its object, keeping the timing", true, move_path),
|
||||
c("motion.pin_point", "Pin Motion Path Point", "", None, "{anchor? (default: a new anchor where the object is), frame? (the frame to pin it to, between the first and last position keys), layer?}: the object passes the anchor exactly on that frame → {anchor, frame, pins}", true, pin_point),
|
||||
c("motion.unpin_point", "Unpin Motion Path Point", "", None, "{anchor? | frame?, layer?}: the anchor shapes the path only again; the X/Y keys of its frame go → {anchor, frame, pins}", true, unpin_point),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -132,19 +139,37 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Most bends [`move_on_path`] makes to land the object where it was put; each takes 15–35%
|
||||
/// off the miss on typical paths (the path's length changes as it bends, sliding the object).
|
||||
/// Most bends [`move_on_path`] makes to land the object where it was put off the path; each
|
||||
/// takes 15–35% off the miss on typical paths (the path's length changes as it bends, sliding the
|
||||
/// object).
|
||||
const BEND_STEPS: usize = 48;
|
||||
|
||||
/// The object on a motion path was moved by `d` at `offset`: at or before the first position
|
||||
/// key the path's start moves, at or after the last its end, in between the path bends so it
|
||||
/// passes where the object was put (a few bends, as the path's length changes with each);
|
||||
/// without position keys the whole path moves.
|
||||
/// The object on a motion path was moved by `d` at `offset` (ADR 0049): the anchor pinned to
|
||||
/// that frame moves with it (before the first position key, the start); after the last position
|
||||
/// key the path carries on to where it was put; in between, a new anchor where the object is gets
|
||||
/// pinned to the frame and moved. Where the object is off the path (an overshooting ease) the
|
||||
/// path bends instead (ADR 0030); without position keys the whole path moves.
|
||||
fn move_on_path(m: &mut MotionTween, base: &Props, offset: u32, d: Vec2, last: u32) {
|
||||
let Some(mut path) = m.path.clone() else { return };
|
||||
let f = offset as f32;
|
||||
match m.position_range() {
|
||||
Some((f0, f1)) if f1 > f0 && offset > f0 && offset < f1 => {
|
||||
Some((f0, f1)) if f1 > f0 => {
|
||||
let pinned = m.pinned_anchors(base).into_iter().find(|p| p.frame == offset).map(|p| p.anchor as usize);
|
||||
if let Some(a) = pinned.or((offset < f0).then_some(0)) {
|
||||
m.move_anchor(a, d, base, last);
|
||||
return;
|
||||
}
|
||||
if offset > f1 {
|
||||
let end = anicraft_doc::motion::path_ends(&path).map(|(_, b)| b).unwrap_or_default();
|
||||
if !m.extend_to(offset, end + d, base) {
|
||||
m.move_anchor(path.cmds.len().saturating_sub(1), d, base, last);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Ok(a) = m.pin_here(offset, base) {
|
||||
m.move_anchor(a, d, base, last);
|
||||
return;
|
||||
}
|
||||
let f = offset as f32;
|
||||
let Some(target) = m.on_path(base).map(|op| op.point(f) + d) else { return };
|
||||
let mut trial = m.clone();
|
||||
for _ in 0..BEND_STEPS {
|
||||
@@ -160,10 +185,6 @@ fn move_on_path(m: &mut MotionTween, base: &Props, offset: u32, d: Vec2, last: u
|
||||
trial.path = Some(path.clone());
|
||||
}
|
||||
}
|
||||
Some((f0, f1)) if f1 > f0 => {
|
||||
let anchor = if offset <= f0 { 0 } else { path.cmds.len().saturating_sub(1) };
|
||||
path.move_anchor(anchor, d);
|
||||
}
|
||||
_ => path = path.transformed(&Affine::translate(d.x, d.y)),
|
||||
}
|
||||
m.set_path(&path, base, last);
|
||||
@@ -182,7 +203,7 @@ fn set_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = anicraft_geom::svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?;
|
||||
let (kf, _) = motion_span(s, p)?;
|
||||
let base = base_of(kf)?;
|
||||
let last = kf.duration.saturating_sub(1);
|
||||
let (start, last) = (kf.start, kf.duration.saturating_sub(1));
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
if last == 0 && m.position_range().is_none_or(|(a, b)| a == b) {
|
||||
return Err(EngineError::State("a one-frame span has no room to move along a path: make the span longer first".into()));
|
||||
@@ -190,33 +211,61 @@ fn set_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !m.set_path(&path, &base, last) {
|
||||
return Err(EngineError::Param("param 'd' needs a segment of some length, with finite points within ±1000000".into()));
|
||||
}
|
||||
Ok(path_summary(m))
|
||||
Ok(path_summary(m, start, &base))
|
||||
}
|
||||
|
||||
fn path_summary(m: &MotionTween) -> Value {
|
||||
let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient}) };
|
||||
fn path_summary(m: &MotionTween, start: u32, base: &Props) -> Value {
|
||||
let pins = pins_json(m, start, base);
|
||||
let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient, "pins": pins}) };
|
||||
let len = anicraft_geom::walk::CurveWalk::new(path).map_or(0.0, |w| w.length());
|
||||
let (a, b) = anicraft_doc::motion::path_ends(path).unwrap_or_default();
|
||||
// Anchor `i` is path command `i` (a motion path is a move and cubics).
|
||||
let anchors: Vec<[f32; 2]> = path.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect();
|
||||
json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient})
|
||||
json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient, "pins": pins})
|
||||
}
|
||||
|
||||
/// The anchors tied to frames (ADR 0049), ends included: `{anchor, frame, end, at}`, frames
|
||||
/// counted from the timeline's start.
|
||||
fn pins_json(m: &MotionTween, start: u32, base: &Props) -> Value {
|
||||
let path = m.path.clone().or_else(|| m.path_from_tracks(base));
|
||||
let pins = m.pinned_anchors(base);
|
||||
let n = pins.len();
|
||||
let v: Vec<Value> = pins
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, q)| {
|
||||
let at = path.as_ref().and_then(|p| p.point(q.anchor as usize, anicraft_geom::edit::ANCHOR)).map(|v| json!([v.x, v.y]));
|
||||
json!({"anchor": q.anchor, "frame": start + q.frame, "end": i == 0 || i + 1 == n, "at": at})
|
||||
})
|
||||
.collect();
|
||||
Value::Array(v)
|
||||
}
|
||||
|
||||
/// Edits the motion path at the target frame with `edit`: the tween's own path, or the straight
|
||||
/// one its X/Y curves trace (which the edit makes its own, as on the stage). The ends' keys stay
|
||||
/// unless the edit moved an end, so the timing is kept. Returns what `edit` returned and the
|
||||
/// path's summary.
|
||||
fn edit_path<T>(s: &mut Session, p: &Value, edit: impl FnOnce(&mut anicraft_geom::Path) -> Result<T>) -> Result<(T, Value)> {
|
||||
/// one its X/Y curves trace (which the edit makes its own, as on the stage, its position keys
|
||||
/// pinned to their anchors). The ends' and pins' keys stay unless the edit moved their anchors,
|
||||
/// so the timing is kept. Returns what `edit` returned and the path's summary.
|
||||
fn edit_path<T>(s: &mut Session, p: &Value, edit: impl FnOnce(&mut MotionTween) -> Result<T>) -> Result<(T, Value)> {
|
||||
let (kf, _) = motion_span(s, p)?;
|
||||
let base = base_of(kf)?;
|
||||
let last = kf.duration.saturating_sub(1);
|
||||
let (start, last) = (kf.start, kf.duration.saturating_sub(1));
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
let mut path = m.path.clone().or_else(|| m.path_from_tracks(&base)).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?;
|
||||
let out = edit(&mut path)?;
|
||||
if m.path.is_none() {
|
||||
let (path, pins) = m.path_and_pins_from_tracks(&base).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?;
|
||||
m.path = Some(path);
|
||||
m.pins = pins;
|
||||
}
|
||||
let out = edit(m)?;
|
||||
let path = m.path.clone().ok_or_else(|| EngineError::State("the motion path went away".into()))?;
|
||||
if !m.set_path(&path, &base, last) {
|
||||
return Err(EngineError::State("that would leave the motion path with no length".into()));
|
||||
}
|
||||
Ok((out, path_summary(m)))
|
||||
Ok((out, path_summary(m, start, &base)))
|
||||
}
|
||||
|
||||
/// The motion path being edited (there is one inside [`edit_path`]).
|
||||
fn path_mut(m: &mut MotionTween) -> Result<&mut anicraft_geom::Path> {
|
||||
m.path.as_mut().ok_or_else(|| EngineError::State("no motion path here".into()))
|
||||
}
|
||||
|
||||
/// An anchor index param, checked against the path.
|
||||
@@ -242,7 +291,8 @@ fn add_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !(0.0..=1000.0).contains(&slop) {
|
||||
return Err(EngineError::Param("param 'slop' must be between 0 and 1000".into()));
|
||||
}
|
||||
let (anchor, mut v) = edit_path(s, p, |path| {
|
||||
let (anchor, mut v) = edit_path(s, p, |m| {
|
||||
let path = path_mut(m)?;
|
||||
if path.cmds.len() > anicraft_doc::motion::MAX_PATH_SEGMENTS {
|
||||
return Err(EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS)));
|
||||
}
|
||||
@@ -268,7 +318,8 @@ fn add_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !(1e-3..=1.0 - 1e-3).contains(&t) {
|
||||
return Err(EngineError::State("there is already an anchor there".into()));
|
||||
}
|
||||
if !path.split_segment(cmd, t) {
|
||||
// Pins after it stay on their anchors.
|
||||
if !m.split_path(cmd, t) {
|
||||
return Err(EngineError::State("cannot add a point there".into()));
|
||||
}
|
||||
// The new anchor ends the first half.
|
||||
@@ -283,8 +334,8 @@ fn delete_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if wanted.is_empty() {
|
||||
return Err(EngineError::Param("param 'anchors' lists no anchor".into()));
|
||||
}
|
||||
let ((deleted, kept_ends), mut v) = edit_path(s, p, |path| {
|
||||
let n = path.cmds.len();
|
||||
let ((deleted, kept_ends, unpinned), mut v) = edit_path(s, p, |m| {
|
||||
let n = path_mut(m)?.cmds.len();
|
||||
let mut set = std::collections::BTreeSet::new();
|
||||
for &i in wanted.iter().take(100_000) {
|
||||
match usize::try_from(i).ok().filter(|i| *i < n) {
|
||||
@@ -296,23 +347,28 @@ fn delete_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if set.is_empty() {
|
||||
return Err(EngineError::State("the ends of a motion path can't be deleted: they are where the motion starts and ends. Drag them to move them, or Straighten the path".into()));
|
||||
}
|
||||
// Last first, so the indices still to go stay where they were.
|
||||
let mut deleted = 0;
|
||||
// Last first, so the indices still to go stay where they were. A pinned anchor's pin
|
||||
// goes with it (and its X/Y keys).
|
||||
let (mut deleted, mut unpinned) = (0, 0);
|
||||
for i in set.into_iter().rev() {
|
||||
if path.merge_at(i) {
|
||||
let pinned = m.live_pins().iter().any(|q| q.anchor as usize == i);
|
||||
if m.delete_anchor(i) {
|
||||
deleted += 1;
|
||||
unpinned += usize::from(pinned);
|
||||
}
|
||||
}
|
||||
Ok((deleted, ends))
|
||||
Ok((deleted, ends, unpinned))
|
||||
})?;
|
||||
v["deleted"] = json!(deleted);
|
||||
v["kept_ends"] = json!(kept_ends);
|
||||
v["unpinned"] = json!(unpinned);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn convert_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required (true: smooth, false: corner)".into()))?;
|
||||
let (changed, mut v) = edit_path(s, p, |path| {
|
||||
let (changed, mut v) = edit_path(s, p, |m| {
|
||||
let path = path_mut(m)?;
|
||||
let a = anchor_index(p, "anchor", path)?;
|
||||
Ok(if smooth { path.make_smooth(a) } else { path.make_corner(a) })
|
||||
})?;
|
||||
@@ -326,6 +382,7 @@ fn move_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Param("params 'dx' and 'dy' must be finite".into()));
|
||||
}
|
||||
let (kf, _) = motion_span(s, p)?;
|
||||
let start = kf.start;
|
||||
let i = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?;
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
if !m.translate(d) {
|
||||
@@ -337,7 +394,8 @@ fn move_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
el.transform = Affine::translate(d.x, d.y).mul(&el.transform);
|
||||
*slot = Arc::new(el);
|
||||
}
|
||||
let mut v = kf.motion.as_ref().map_or(Value::Null, path_summary);
|
||||
let base = base_of(kf)?;
|
||||
let mut v = kf.motion.as_ref().map_or(Value::Null, |m| path_summary(m, start, &base));
|
||||
v["moved"] = json!([d.x, d.y]);
|
||||
Ok(v)
|
||||
}
|
||||
@@ -349,8 +407,10 @@ fn clear_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if m.path.take().is_none() {
|
||||
return Err(EngineError::State(format!("the motion tween at frame {} has no motion path to remove", frame + 1)));
|
||||
}
|
||||
// Orient to path has nothing left to turn with.
|
||||
// Orient to path has nothing left to turn with, and pins nothing to pin. Their keys stay:
|
||||
// the straight path runs through them.
|
||||
m.orient = false;
|
||||
m.pins.clear();
|
||||
Ok(json!({"cleared": true}))
|
||||
}
|
||||
|
||||
@@ -358,7 +418,7 @@ fn orient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let on = opt_bool(p, "orient")?.ok_or_else(|| EngineError::Param("param 'orient' is required (true or false)".into()))?;
|
||||
let (kf, _) = motion_span(s, p)?;
|
||||
let base = base_of(kf)?;
|
||||
let last = kf.duration.saturating_sub(1);
|
||||
let (start, last) = (kf.start, kf.duration.saturating_sub(1));
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
// The straight path the X/Y curves trace becomes the path to turn along.
|
||||
let mut created = false;
|
||||
@@ -367,11 +427,84 @@ fn orient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
created = m.set_path(&path, &base, last);
|
||||
}
|
||||
m.orient = on;
|
||||
let mut v = path_summary(m);
|
||||
let mut v = path_summary(m, start, &base);
|
||||
v["path_created"] = json!(created);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Why a pin can't be made, in words an artist (or an agent) can act on. `start` is the span's
|
||||
/// first frame (messages count frames from 1, as the timeline does).
|
||||
fn pin_error(e: PinError, start: u32, frame: u32) -> EngineError {
|
||||
let shown = |f: u32| start + f + 1;
|
||||
match e {
|
||||
PinError::NoPath => EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()),
|
||||
PinError::NoAnchor => EngineError::Param("no such anchor on this motion path (motion.info lists them, from 0 at the start)".into()),
|
||||
PinError::End => EngineError::State("the ends of a motion path are always pinned, to the first and last position keys: move the object on those frames to move them".into()),
|
||||
PinError::Outside(f0, f1) => EngineError::State(format!("frame {} is outside the motion (frames {} to {}): move the object there to carry the path on", shown(frame), shown(f0), shown(f1))),
|
||||
PinError::Order(q) => EngineError::State(format!("anchor {} is pinned to frame {}: pins keep the path's order, a later frame on a later anchor", q.anchor, shown(q.frame))),
|
||||
PinError::OffPath => EngineError::State(format!("at frame {} the object is beyond an end of the path (its ease overshoots): pin an anchor of the path instead", shown(frame))),
|
||||
PinError::Full => EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A straight motion's path becomes the tween's own, its position keys pinned to its anchors
|
||||
/// (nothing moves).
|
||||
fn own_path(m: &mut MotionTween, base: &Props, last: u32) -> std::result::Result<(), PinError> {
|
||||
if m.path.is_none() {
|
||||
let (path, pins) = m.path_and_pins_from_tracks(base).ok_or(PinError::NoPath)?;
|
||||
m.path = Some(path.clone());
|
||||
m.pins = pins;
|
||||
m.set_path(&path, base, last);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pin_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let anchor = opt_u64(p, "anchor")?.map(|a| usize::try_from(a).unwrap_or(usize::MAX));
|
||||
let (kf, offset) = motion_span(s, p)?;
|
||||
let base = base_of(kf)?;
|
||||
let (start, last) = (kf.start, kf.duration.saturating_sub(1));
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
own_path(m, &base, last).map_err(|e| pin_error(e, start, offset))?;
|
||||
let a = match anchor {
|
||||
Some(a) => m.pin(a, offset, &base).map(|_| a),
|
||||
None => m.pin_here(offset, &base),
|
||||
}
|
||||
.map_err(|e| pin_error(e, start, offset))?;
|
||||
let mut v = path_summary(m, start, &base);
|
||||
v["anchor"] = json!(a);
|
||||
v["frame"] = json!(start + offset);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn unpin_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let anchor = opt_u64(p, "anchor")?;
|
||||
let (kf, offset) = motion_span(s, p)?;
|
||||
let base = base_of(kf)?;
|
||||
let (start, last) = (kf.start, kf.duration.saturating_sub(1));
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
own_path(m, &base, last).map_err(|e| pin_error(e, start, offset))?;
|
||||
let all = m.pinned_anchors(&base);
|
||||
let found: Option<Pin> = match anchor {
|
||||
Some(a) => all.iter().find(|q| u64::from(q.anchor) == a).copied(),
|
||||
None => all.iter().find(|q| q.frame == offset).copied(),
|
||||
};
|
||||
let Some(pin) = found else {
|
||||
return Err(EngineError::State(match anchor {
|
||||
Some(a) => format!("anchor {a} isn't pinned to a frame"),
|
||||
None => format!("no anchor is pinned to frame {}", start + offset + 1),
|
||||
}));
|
||||
};
|
||||
if all.first() == Some(&pin) || all.last() == Some(&pin) {
|
||||
return Err(pin_error(PinError::End, start, pin.frame));
|
||||
}
|
||||
m.unpin(pin.frame);
|
||||
let mut v = path_summary(m, start, &base);
|
||||
v["anchor"] = json!(pin.anchor);
|
||||
v["frame"] = json!(start + pin.frame);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Insert Keyframe (F6) inside a motion tween: every property gets a key at `frame` holding its
|
||||
/// value there; the timeline is not split. Whether `frame` was in a motion tween.
|
||||
pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool {
|
||||
@@ -384,7 +517,13 @@ pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool {
|
||||
let Some(m) = kf.motion.as_mut() else { return false };
|
||||
let Some(base) = m.target_index(&kf.elements).and_then(|t| kf.elements.get(t)).map(|e| Props::of(e)) else { return true };
|
||||
let now = m.props_at(&base, offset as f32);
|
||||
// On a motion path the frame's place is an anchor pinned to it (ADR 0049), where the
|
||||
// object is: nothing moves on this frame.
|
||||
let pinned = m.path.is_some() && m.pin_here(offset, &base).is_ok();
|
||||
for p in Property::ALL {
|
||||
if pinned && matches!(p, Property::X | Property::Y) {
|
||||
continue;
|
||||
}
|
||||
m.set_key(p, offset, now.get(p), base.get(p));
|
||||
}
|
||||
true
|
||||
@@ -416,6 +555,9 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if layer.kind == LayerKind::Folder {
|
||||
return Err(EngineError::State("a folder holds layers, not frames; pick a layer inside it".into()));
|
||||
}
|
||||
if layer.kind == LayerKind::Armature {
|
||||
return Err(EngineError::State("an armature layer tweens its poses: add a pose at another frame and Create Classic Tween between them".into()));
|
||||
}
|
||||
let k = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?;
|
||||
if let Some(m) = &k.motion {
|
||||
return Ok(json!({"motion": k.start, "target": m.target.0, "frames": k.duration, "converted": false}));
|
||||
@@ -440,7 +582,7 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = format!("Tween {}", s.doc.library.len() + 1);
|
||||
s.layer = lid;
|
||||
s.frame = start;
|
||||
s.selection = ids;
|
||||
s.selection = crate::Selection::only(lid, ids);
|
||||
let r = crate::cmds_draw::convert_to_symbol(s, &json!({"name": name}));
|
||||
s.frame = frame;
|
||||
if layer != lid {
|
||||
@@ -502,8 +644,19 @@ fn set_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (kf, offset) = motion_span(s, p)?;
|
||||
let base = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e));
|
||||
let base = base.ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?;
|
||||
let start = kf.start;
|
||||
let (start, last) = (kf.start, kf.duration.saturating_sub(1));
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
// On a path, the X/Y keys of a pinned frame are its anchor's place: setting one moves the
|
||||
// anchor (ADR 0049).
|
||||
let pinned = matches!(prop, Property::X | Property::Y).then(|| m.pinned_anchors(&base).into_iter().find(|q| q.frame == offset)).flatten().filter(|_| m.path.is_some());
|
||||
if let Some(pin) = pinned {
|
||||
let at = m.path.as_ref().and_then(|p| p.point(pin.anchor as usize, anicraft_geom::edit::ANCHOR)).unwrap_or_default();
|
||||
let d = if prop == Property::X { Vec2::new(value - at.x, 0.0) } else { Vec2::new(0.0, value - at.y) };
|
||||
if d != Vec2::ZERO && !m.move_anchor(pin.anchor as usize, d, &base, last) {
|
||||
return Err(EngineError::Param(format!("{} must keep the motion path within ±1000000 px", prop.label())));
|
||||
}
|
||||
return Ok(json!({"property": prop.key(), "frame": start + offset, "value": value, "anchor": pin.anchor}));
|
||||
}
|
||||
m.set_key(prop, offset, value, base.get(prop));
|
||||
Ok(json!({"property": prop.key(), "frame": start + offset, "value": value}))
|
||||
}
|
||||
@@ -513,11 +666,20 @@ fn remove_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (kf, offset) = motion_span(s, p)?;
|
||||
let start = kf.start;
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
let removed: Vec<&str> = Property::ALL.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect();
|
||||
// Removing a pinned frame's X or Y key lets the pin go, with both keys (ADR 0049).
|
||||
let pin = m.live_pins().into_iter().find(|q| q.frame == offset).filter(|_| only.is_none_or(|o| matches!(o, Property::X | Property::Y)));
|
||||
let mut removed: Vec<&str> = Property::ALL.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect();
|
||||
if pin.is_some() {
|
||||
for k in [Property::X.key(), Property::Y.key()] {
|
||||
if !removed.contains(&k) {
|
||||
removed.push(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
if removed.is_empty() {
|
||||
return Err(EngineError::State(format!("there is no property keyframe at frame {}", start + offset + 1)));
|
||||
}
|
||||
Ok(json!({"removed": removed, "frame": start + offset}))
|
||||
Ok(json!({"removed": removed, "frame": start + offset, "unpinned": pin.map(|q| q.anchor)}))
|
||||
}
|
||||
|
||||
fn set_ease(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -558,8 +720,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let values: serde_json::Map<String, Value> = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().to_string(), json!(n.get(*p))))).collect();
|
||||
// Where the object is (on a motion path the X/Y values are its timing, not its place).
|
||||
let position = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| m.apply(e, (frame - kf.start) as f32).transform.translation()).map(|q| json!([q.x, q.y]));
|
||||
let path = path_summary(m);
|
||||
let path = m.path.as_ref().map(|p| p.to_svg());
|
||||
// The anchors point edits address: the path's own, or the straight path's (ADR 0038).
|
||||
let anchors: Vec<[f32; 2]> = m.path.clone().or_else(|| base.and_then(|b| m.path_from_tracks(&b))).map(|p| p.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect()).unwrap_or_default();
|
||||
Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path["path"], "anchors": anchors, "orient": m.orient}))
|
||||
// And those tied to frames, ends included (ADR 0049).
|
||||
let pins = base.map_or(Value::Array(Vec::new()), |b| pins_json(m, kf.start, &b));
|
||||
Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path, "anchors": anchors, "pins": pins, "orient": m.orient}))
|
||||
}
|
||||
@@ -30,10 +30,18 @@ use std::sync::Arc;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("paint.bucket", "Paint Bucket", "", None, "{x, y, color?, gap? (stage units: how wide an opening still counts as closed)}", true, bucket as crate::RunFn),
|
||||
c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?, profile?}", true, ink),
|
||||
c(
|
||||
"paint.bucket",
|
||||
"Paint Bucket",
|
||||
"",
|
||||
None,
|
||||
"{x, y, color?, gap? (stage units: how wide an opening still counts as closed), object?: bool} fills the closed area under the point, or recolours the fill there; unless `object` (default: the Object Drawing setting), the fill is raw and merges with the drawing (an area closed by raw lines and fills is filled exactly up to them)",
|
||||
true,
|
||||
bucket as crate::RunFn,
|
||||
),
|
||||
c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?, profile?, cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing?} (the tool's line style unless given; see stroke.set_style)", true, ink),
|
||||
c("paint.pick", "Eyedropper", "", None, "{x, y, other?: bool (into the other swatch only: a fill's colour into the stroke, a line's into the fill), slop?} picks the style under the point on any visible layer into the tool settings: a fill's paint (solid, gradient or bitmap, kept where it is on the stage) into the fill swatch, a line's colour, width and profile into the stroke settings", false, pick_style),
|
||||
c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, apply_style),
|
||||
c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, |s, p| s.each_layer(false, |s| apply_style(s, p))),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -76,16 +84,26 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !(0.0..=1000.0).contains(&gap) {
|
||||
return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into()));
|
||||
}
|
||||
let object = crate::cmds_draw::object_param(s, p)?;
|
||||
let items = layer_items(s);
|
||||
// 1. On a fill: recolour it.
|
||||
// 1. On a fill: recolour it. A raw fill then joins the fills of its new colour it touches.
|
||||
if let Some((id, true)) = pick(&items, at, 0.0) {
|
||||
let to_local = items.iter().find(|i| i.element == id).and_then(|i| i.transform.inverse()).unwrap_or(Affine::IDENTITY);
|
||||
element_shape_mut(s, id)?.fill = Some(paint.transformed(&to_local));
|
||||
let sh = element_shape_mut(s, id)?;
|
||||
sh.fill = Some(paint.transformed(&to_local));
|
||||
if sh.merge {
|
||||
crate::cmds_raw::remerge_in_place(s, &[id])?;
|
||||
return Ok(json!({"recolored": id.0, "merged": true}));
|
||||
}
|
||||
return Ok(json!({"recolored": id.0}));
|
||||
}
|
||||
// 2. Find the enclosed area.
|
||||
let Some(path) = enclosed_region(&items, at, gap)? else {
|
||||
return Err(EngineError::State("this area isn't closed. Close the outline, or choose a larger gap size".into()));
|
||||
// 2. Find the enclosed area: exactly, when raw lines and fills close it off (ADR 0042),
|
||||
// else from the rasterized layer.
|
||||
let exact = if object { None } else { crate::merge::enclosed_area(&s.visible_elements(), at) };
|
||||
let was_exact = exact.is_some();
|
||||
let path = match exact {
|
||||
Some(p) => p,
|
||||
None => enclosed_region(&items, at, gap)?.ok_or_else(|| EngineError::State("this area isn't closed. Close the outline, or choose a larger gap size".into()))?,
|
||||
};
|
||||
let c = path.bounds().center();
|
||||
let local = path.transformed(&Affine::translate(-c.x, -c.y));
|
||||
@@ -95,8 +113,15 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
name: String::new(),
|
||||
transform: Affine::translate(c.x, c.y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(paint.transformed(&Affine::translate(-c.x, -c.y))), stroke: None, fill_rule: FillRule::EvenOdd, merge: false }),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(paint.transformed(&Affine::translate(-c.x, -c.y))), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }),
|
||||
};
|
||||
if !object {
|
||||
// Raw: behind the drawing, so it takes only what is empty and joins the fills of its
|
||||
// colour it meets; the lines that bound it stay on top.
|
||||
let ids = crate::merge::merge_in_order(s, vec![el], crate::merge::Order::Behind)?;
|
||||
s.selection.clear();
|
||||
return Ok(json!({"element": ids.first().map(|e| e.0), "elements": ids.iter().map(|e| e.0).collect::<Vec<_>>(), "merged": true, "exact": was_exact}));
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() >= 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
@@ -289,7 +314,9 @@ fn ink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(pr) => pr,
|
||||
None => s.style.profile(),
|
||||
};
|
||||
element_shape_mut(s, id)?.stroke = Some(Stroke::new(color, width).with_profile(profile));
|
||||
// The Ink Bottle carries the whole line: caps, joins and dashes too.
|
||||
let line = opt_stroke_style(p, &s.style.line, width)?.unwrap_or_else(|| s.style.line.clone());
|
||||
element_shape_mut(s, id)?.stroke = Some(Stroke::new(color, width).with_profile(profile).with_style(line));
|
||||
Ok(json!({"element": id.0}))
|
||||
}
|
||||
|
||||
@@ -360,6 +387,8 @@ fn pick_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.stroke = stroke.color;
|
||||
st.stroke_width = (stroke.width * scale).clamp(0.1, 1000.0);
|
||||
st.use_stroke = true;
|
||||
// Caps, joins and dashes as drawn (dashes scale with the shape, like the width).
|
||||
st.line = stroke.style.scaled(scale).sanitized();
|
||||
let preset = anicraft_doc::ProfilePreset::ALL.into_iter().find(|pr| pr.profile() == stroke.profile);
|
||||
let profile = match preset {
|
||||
Some(pr) => {
|
||||
@@ -371,7 +400,7 @@ fn pick_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"custom"
|
||||
}
|
||||
};
|
||||
Ok(json!({"picked": "line", "into": "stroke", "color": stroke.color.to_hex(), "width": st.stroke_width, "profile": profile}))
|
||||
Ok(json!({"picked": "line", "into": "stroke", "color": stroke.color.to_hex(), "width": st.stroke_width, "profile": profile, "cap": st.line.cap.key(), "join": st.line.join.key(), "style": st.line.dash_kind().key()}))
|
||||
}
|
||||
None => Err(EngineError::State("click a fill or a line to pick its colour".into())),
|
||||
}
|
||||
@@ -387,7 +416,7 @@ fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let style = s.style.clone();
|
||||
let paint = style.fill_paint();
|
||||
let line = Stroke::new(style.stroke, style.stroke_width).with_profile(style.profile());
|
||||
let line = style.new_stroke(style.stroke, style.stroke_width);
|
||||
let mut changed = 0;
|
||||
for e in s.selected_elements_mut()? {
|
||||
let to_local = e.transform.inverse();
|
||||
|
||||
@@ -31,7 +31,7 @@ const MAX_ELEMENTS: usize = 10_000;
|
||||
/// a namespace this list doesn't know is refused until someone decides (a test checks that
|
||||
/// every registered namespace is known).
|
||||
pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> {
|
||||
const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "script"];
|
||||
const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw", "frames"];
|
||||
match id {
|
||||
"edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"),
|
||||
"edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" => {
|
||||
@@ -90,7 +90,7 @@ fn document_view(s: &Session) -> Value {
|
||||
"frames": s.frame_count(),
|
||||
"layer": s.layer.0,
|
||||
"layers": layers,
|
||||
"selection": s.selection.iter().map(|e| e.0).collect::<Vec<_>>(),
|
||||
"selection": s.selection.id_list(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result<Value, String>
|
||||
*e = e.union(&r);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for e in s.visible_elements().iter().filter(|e| !only_selected || s.selection.contains(&e.id)) {
|
||||
for e in s.visible_elements().iter().filter(|e| !only_selected || s.selection.contains(s.layer, e.id)) {
|
||||
if out.len() >= MAX_ELEMENTS {
|
||||
break;
|
||||
}
|
||||
@@ -124,7 +124,7 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result<Value, String>
|
||||
let mut v = json!({
|
||||
"id": e.id.0,
|
||||
"name": e.name,
|
||||
"selected": s.selection.contains(&e.id),
|
||||
"selected": s.selection.contains(s.layer, e.id),
|
||||
"transform": e.transform.m,
|
||||
"bounds": if b.is_empty() { Value::Null } else { json!([b.min.x, b.min.y, b.max.x - b.min.x, b.max.y - b.min.y]) },
|
||||
"alpha": e.color.alpha,
|
||||
|
||||
@@ -0,0 +1,676 @@
|
||||
//! The Selection tool on raw shapes (ADR 0041; issue #42 §2 and §4): bending an edge by dragging
|
||||
//! it, moving a corner or an end together with every raw shape that shares it, snapping what is
|
||||
//! dragged to points, lines and fill edges, and a marquee that selects the parts of fills and
|
||||
//! strokes under it.
|
||||
//!
|
||||
//! Positions and moves are in stage space. A layer's merged drawing stores a shared edge or
|
||||
//! point once in each shape that has it, so every edit here changes all the copies alike and
|
||||
//! then merges the shapes again (ADR 0031), unless asked not to while a drag is still going.
|
||||
|
||||
use crate::cmds_draw::MAX_EXTENT;
|
||||
use crate::merge::{self, Part, mergeable, reach};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, CutOrigin, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, LayerId};
|
||||
use anicraft_geom::planar::SNAP;
|
||||
use anicraft_geom::raw::{self as rawgeom, Cubic};
|
||||
use anicraft_geom::walk::cubic_point;
|
||||
use anicraft_geom::{Path, PathCmd, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c(
|
||||
"path.bend_segment",
|
||||
"Bend Segment",
|
||||
"",
|
||||
None,
|
||||
"{x, y, dx, dy, id?, cmd?, t?, slop?, merge?: bool} the segment at (x, y) (of shape `id`, else the one there) bends so that point moves by (dx, dy), its ends staying; a raw shape's copies of the edge bend with it and merge again (unless merge is false)",
|
||||
true,
|
||||
bend_segment as crate::RunFn,
|
||||
),
|
||||
c(
|
||||
"raw.move_point",
|
||||
"Move Point",
|
||||
"",
|
||||
None,
|
||||
"{x, y, to_x, to_y, with?: [[x, y], ..], points?: [[id, cmd], ..], snap?, slop?, merge?: bool} moves the corner or end at (x, y), with every raw shape that shares it, to (to_x, to_y), snapped within `snap` to points, lines and fill edges (while Snap to Objects is on); the anchors at `with` move by as much; returns the points to pass on while a drag goes on",
|
||||
true,
|
||||
move_point,
|
||||
),
|
||||
c(
|
||||
"raw.select_rect",
|
||||
"Select Parts",
|
||||
"",
|
||||
None,
|
||||
"{x0, y0, x1, y1, add?: bool} the marquee, on every visible, unlocked layer: the parts of raw fills and strokes under the rectangle (cut at its edges, per layer) and the objects wholly inside it",
|
||||
true,
|
||||
select_rect,
|
||||
),
|
||||
c("raw.merge", "Merge Shapes", "", None, "{ids?: [..]} the raw shapes (default: the selection) merge again with the raw shapes they touch, in place", true, merge_cmd),
|
||||
c("raw.hit", "Selection Tool Target", "", None, "{x, y, slop?, point_slop?} what a Selection-tool drag from (x, y) takes: a point, a segment to bend, a fill, or an object", false, hit),
|
||||
]
|
||||
}
|
||||
|
||||
/// Most points one move takes along.
|
||||
const MAX_POINTS: usize = 10_000;
|
||||
/// Most anchors and segments looked at when snapping.
|
||||
const MAX_TARGETS: usize = 50_000;
|
||||
|
||||
// ----- what the Selection tool takes -----------------------------------------------------------
|
||||
|
||||
/// What a Selection-tool drag starting at a point takes (Animate's corner and curve cursors).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Grab {
|
||||
/// A corner or end that raw shapes share: the drag moves it.
|
||||
Point { at: Vec2 },
|
||||
/// A raw stroke segment or fill edge, at parameter `t` of command `cmd`: the drag bends it.
|
||||
Segment { id: ElementId, cmd: usize, t: f32, at: Vec2 },
|
||||
/// The inside of an unselected raw fill: the drag selects and moves it.
|
||||
Fill { id: ElementId },
|
||||
/// Anything else (an object, or something selected): the drag moves the selection.
|
||||
Object { id: ElementId },
|
||||
}
|
||||
|
||||
impl Grab {
|
||||
pub fn key(&self) -> &'static str {
|
||||
match self {
|
||||
Grab::Point { .. } => "point",
|
||||
Grab::Segment { .. } => "segment",
|
||||
Grab::Fill { .. } => "fill",
|
||||
Grab::Object { .. } => "object",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A raw shape's anchors in stage space.
|
||||
fn stage_anchors(e: &Element) -> Vec<(usize, Vec2)> {
|
||||
match mergeable(e) {
|
||||
Some(sh) => sh.path.editable_anchors().into_iter().map(|(i, p)| (i, e.transform.apply(p))).collect(),
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// What a Selection-tool drag from `p` takes: a shared point within `point_slop`, a segment
|
||||
/// within `slop`, the inside of a fill, or the object there. Raw shapes that are selected
|
||||
/// count as objects (a drag moves the selection). `None` over empty space.
|
||||
pub fn raw_grab(&self, p: Vec2, slop: f32, point_slop: f32) -> Option<(LayerId, Grab)> {
|
||||
let (layer, id) = self.hit_test(p, slop)?;
|
||||
let object = Some((layer, Grab::Object { id }));
|
||||
if self.selection.contains(layer, id) {
|
||||
return object;
|
||||
}
|
||||
let els = self.elements_on(layer);
|
||||
let el = els.iter().find(|e| e.id == id)?;
|
||||
let Some(sh) = mergeable(el) else { return object };
|
||||
// A corner or end there, of any raw shape on the layer.
|
||||
let mut best: Option<(f32, Vec2)> = None;
|
||||
for e in els.iter().filter(|e| mergeable(e).is_some_and(|x| reach(x, &e.transform).inflate(point_slop).contains(p))) {
|
||||
for (_, q) in stage_anchors(e) {
|
||||
let d = q.distance(p);
|
||||
if d <= point_slop && best.is_none_or(|b| d < b.0) {
|
||||
best = Some((d, q));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((_, at)) = best {
|
||||
return Some((layer, Grab::Point { at }));
|
||||
}
|
||||
// The edge of a fill bends; its inside moves.
|
||||
if sh.fill.is_some() && sh.path.distance_to_edge(p, &el.transform) > slop {
|
||||
return Some((layer, Grab::Fill { id }));
|
||||
}
|
||||
let (cmd, t, _) = sh.path.nearest_segment(p, &el.transform)?;
|
||||
let at = sh.path.segment_point(cmd, t).map(|q| el.transform.apply(q))?;
|
||||
Some((layer, Grab::Segment { id, cmd, t, at }))
|
||||
}
|
||||
}
|
||||
|
||||
fn hit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0);
|
||||
let point_slop = opt_f32(p, "point_slop")?.unwrap_or(slop * 1.5).clamp(0.0, 100.0);
|
||||
Ok(match s.raw_grab(at, slop, point_slop) {
|
||||
None => json!({"kind": null}),
|
||||
Some((layer, g)) => {
|
||||
let mut v = json!({"kind": g.key(), "layer": layer.0});
|
||||
match g {
|
||||
Grab::Point { at } => {
|
||||
v["x"] = json!(at.x);
|
||||
v["y"] = json!(at.y);
|
||||
}
|
||||
Grab::Segment { id, cmd, t, at } => {
|
||||
v["id"] = json!(id.0);
|
||||
v["cmd"] = json!(cmd);
|
||||
v["t"] = json!(t);
|
||||
v["x"] = json!(at.x);
|
||||
v["y"] = json!(at.y);
|
||||
}
|
||||
Grab::Fill { id } | Grab::Object { id } => v["id"] = json!(id.0),
|
||||
}
|
||||
v
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Makes the layer of what is at `at` (within `slop`) the active one, as a click does.
|
||||
fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) {
|
||||
if let Some((layer, _)) = s.hit_test(at, slop)
|
||||
&& layer != s.layer
|
||||
{
|
||||
s.layer = layer;
|
||||
s.selection.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn check_extent(path: &Path) -> Result<()> {
|
||||
let b = path.bounds();
|
||||
if b.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if !(b.min.is_finite() && b.max.is_finite()) || b.width() > MAX_EXTENT || b.height() > MAX_EXTENT || b.min.x.abs().max(b.min.y.abs()).max(b.max.x.abs()).max(b.max.y.abs()) > MAX_EXTENT {
|
||||
return Err(EngineError::Param("that would make the shape too large".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ----- bending ----------------------------------------------------------------------------------
|
||||
|
||||
fn bend_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0);
|
||||
let merge_after = opt_bool(p, "merge")?.unwrap_or(true);
|
||||
// The shape: `id`, else the one under the point (its layer becomes the active one).
|
||||
let id = match opt_u64(p, "id")? {
|
||||
Some(i) => ElementId(i),
|
||||
None => {
|
||||
activate_layer_at(s, at, slop);
|
||||
s.hit_test(at, slop).map(|(_, e)| e).ok_or_else(|| EngineError::State("no shape there".into()))?
|
||||
}
|
||||
};
|
||||
let els = s.visible_elements();
|
||||
let el = els.iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?;
|
||||
let ElementKind::Shape(sh) = &el.kind else { return Err(EngineError::State("only shapes have segments to bend".into())) };
|
||||
let m = el.transform;
|
||||
let mut path = (*sh.path).clone();
|
||||
path.close_explicitly();
|
||||
let (cmd, t) = match opt_u64(p, "cmd")? {
|
||||
Some(c) => (usize::try_from(c).unwrap_or(usize::MAX), opt_f32(p, "t")?.ok_or_else(|| EngineError::Param("param 't' is required with 'cmd'".into()))?.clamp(0.0, 1.0)),
|
||||
None => {
|
||||
let (cmd, t, dist) = path.nearest_segment(at, &m).ok_or_else(|| EngineError::State("the shape has no segments".into()))?;
|
||||
if dist > slop {
|
||||
return Err(EngineError::State("no segment there".into()));
|
||||
}
|
||||
(cmd, t)
|
||||
}
|
||||
};
|
||||
let old = rawgeom::segment_cubic(&path, cmd).map(|c| rawgeom::transform(&c, &m)).ok_or_else(|| EngineError::Param(format!("no segment {cmd} on this shape")))?;
|
||||
let new = rawgeom::bend(&old, t, d).ok_or_else(|| EngineError::Param("cannot bend that segment".into()))?;
|
||||
let raw = mergeable(el).is_some();
|
||||
let changed = edit_edge(s, id, cmd, &old, &new, raw)?;
|
||||
let point = cubic_point(&new, t.clamp(0.02, 0.98));
|
||||
if raw && merge_after {
|
||||
remerge_in_place(s, &changed)?;
|
||||
}
|
||||
Ok(json!({"id": id.0, "cmd": cmd, "t": t, "x": point.x, "y": point.y, "changed": changed.iter().map(|e| e.0).collect::<Vec<_>>(), "merged": raw && merge_after}))
|
||||
}
|
||||
|
||||
/// Replaces segment `cmd` of shape `id` (stage space: `old`) with `new` (same ends). When `raw`,
|
||||
/// every raw shape's copy of the edge changes alike (a fill and its outline, two fills that
|
||||
/// meet there); an object only changes itself. Returns the shapes that changed.
|
||||
pub(crate) fn edit_edge(s: &mut Session, id: ElementId, cmd: usize, old: &Cubic, new: &Cubic, raw: bool) -> Result<Vec<ElementId>> {
|
||||
let area = new.iter().chain(old).fold(Rect::EMPTY, |mut r, q| {
|
||||
r.include(*q);
|
||||
r
|
||||
});
|
||||
let kf = s.editable_keyframe()?;
|
||||
let mut changed = Vec::new();
|
||||
for e in kf.elements.iter_mut() {
|
||||
let target = e.id == id;
|
||||
if !target && !(raw && mergeable(e).is_some_and(|x| !reach(x, &e.transform).intersect(&area).is_empty())) {
|
||||
continue;
|
||||
}
|
||||
let (Some(inv), ElementKind::Shape(x)) = (e.transform.inverse(), &e.kind) else { continue };
|
||||
let (ol, nl) = (rawgeom::transform(old, &inv), rawgeom::transform(new, &inv));
|
||||
let mut edited = (*x.path).clone();
|
||||
let n = if target {
|
||||
edited.close_explicitly();
|
||||
let end = edited.point(cmd, anicraft_geom::edit::ANCHOR);
|
||||
match (edited.cmds.get_mut(cmd), end) {
|
||||
(Some(c), Some(end)) => {
|
||||
*c = PathCmd::CubicTo(nl[1], nl[2], end);
|
||||
1
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
} else {
|
||||
rawgeom::follow(&mut edited, &ol, &nl, SNAP / e.transform.mean_scale().max(1e-6))
|
||||
};
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
check_extent(&edited)?;
|
||||
if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind {
|
||||
x.path = Arc::new(edited);
|
||||
}
|
||||
changed.push(e.id);
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
// ----- moving shared points ---------------------------------------------------------------------
|
||||
|
||||
fn points_param(p: &Value) -> Result<Option<Vec<(ElementId, usize)>>> {
|
||||
let Some(v) = p.get("points").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let bad = || EngineError::Param("param 'points' must be a list of [id, cmd] pairs".into());
|
||||
let list = v.as_array().ok_or_else(bad)?;
|
||||
if list.len() > MAX_POINTS {
|
||||
return Err(EngineError::Param(format!("param 'points' has more than {MAX_POINTS} points")));
|
||||
}
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for pair in list {
|
||||
let pair = pair.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?;
|
||||
let id = pair.first().and_then(Value::as_u64).ok_or_else(bad)?;
|
||||
let cmd = pair.get(1).and_then(Value::as_u64).ok_or_else(bad)?;
|
||||
out.push((ElementId(id), usize::try_from(cmd).unwrap_or(usize::MAX)));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(EngineError::Param("param 'points' is empty".into()));
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// A list of `[x, y]` stage positions (empty when absent).
|
||||
pub(crate) fn positions_param(p: &Value, key: &str) -> Result<Vec<Vec2>> {
|
||||
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
|
||||
let bad = || EngineError::Param(format!("param '{key}' must be a list of [x, y] pairs"));
|
||||
let list = v.as_array().ok_or_else(bad)?;
|
||||
if list.len() > MAX_POINTS {
|
||||
return Err(EngineError::Param(format!("param '{key}' has more than {MAX_POINTS} points")));
|
||||
}
|
||||
list.iter()
|
||||
.map(|xy| {
|
||||
let xy = xy.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?;
|
||||
let n = |i: usize| xy.get(i).and_then(Value::as_f64).map(|f| f as f32).filter(|f| f.is_finite()).ok_or_else(bad);
|
||||
Ok(Vec2::new(n(0)?, n(1)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every raw shape's anchor at `at` (within [`SNAP`]) on the editable keyframe; shapes whose edge
|
||||
/// passes there get an anchor there first.
|
||||
fn shared_points(s: &mut Session, at: Vec2) -> Result<Vec<(ElementId, usize)>> {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let mut out = Vec::new();
|
||||
for e in kf.elements.iter_mut() {
|
||||
let Some(sh) = mergeable(e) else { continue };
|
||||
if !reach(sh, &e.transform).contains(at) {
|
||||
continue;
|
||||
}
|
||||
let Some(inv) = e.transform.inverse() else { continue };
|
||||
let mut path = (*sh.path).clone();
|
||||
let len = path.cmds.len();
|
||||
let cmds = rawgeom::anchors_at(&mut path, inv.apply(at), SNAP / e.transform.mean_scale().max(1e-6));
|
||||
if path.cmds.len() != len
|
||||
&& let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind
|
||||
{
|
||||
x.path = Arc::new(path);
|
||||
}
|
||||
out.extend(cmds.into_iter().map(|c| (e.id, c)));
|
||||
if out.len() > MAX_POINTS {
|
||||
return Err(EngineError::State("too many shapes meet there".into()));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let from = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let to = Vec2::new(f32_req(p, "to_x")?, f32_req(p, "to_y")?);
|
||||
let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0));
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0);
|
||||
let merge_after = opt_bool(p, "merge")?.unwrap_or(true);
|
||||
let points = match points_param(p)? {
|
||||
Some(points) => points,
|
||||
None => {
|
||||
activate_layer_at(s, from, slop);
|
||||
// The nearest corner or end of a raw shape, then everything that shares it.
|
||||
let els = s.visible_elements();
|
||||
let at = els.iter().flat_map(|e| stage_anchors(e)).map(|(_, q)| q).filter(|q| q.distance(from) <= slop).min_by(|a, b| a.distance(from).total_cmp(&b.distance(from)));
|
||||
let at = at.ok_or_else(|| EngineError::State("no corner or end of a raw shape there".into()))?;
|
||||
let mut points = shared_points(s, at)?;
|
||||
// Other selected anchors (the Subselection tool) move by as much.
|
||||
for w in positions_param(p, "with")? {
|
||||
for pt in shared_points(s, w)? {
|
||||
if !points.contains(&pt) {
|
||||
points.push(pt);
|
||||
}
|
||||
}
|
||||
if points.len() > MAX_POINTS {
|
||||
return Err(EngineError::State("too many points to move at once".into()));
|
||||
}
|
||||
}
|
||||
points
|
||||
}
|
||||
};
|
||||
let els = s.visible_elements();
|
||||
let find = |id: ElementId| els.iter().find(|e| e.id == id);
|
||||
let &(id0, cmd0) = points.first().ok_or_else(|| EngineError::State("no point there".into()))?;
|
||||
let cur = find(id0).and_then(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.path.point(cmd0, anicraft_geom::edit::ANCHOR).map(|q| e.transform.apply(q)),
|
||||
_ => None,
|
||||
});
|
||||
let cur = cur.ok_or_else(|| EngineError::Param(format!("no point ({}, {cmd0}) on the active layer", id0.0)))?;
|
||||
let snapped = if radius > 0.0 { snap_point(&els, to, radius, &points) } else { None };
|
||||
let target = snapped.map_or(to, |(q, _)| q);
|
||||
let d = target - cur;
|
||||
let kf = s.editable_keyframe()?;
|
||||
let mut moved: BTreeSet<ElementId> = BTreeSet::new();
|
||||
for e in kf.elements.iter_mut() {
|
||||
let cmds: Vec<usize> = points.iter().filter(|(id, _)| *id == e.id).map(|(_, c)| *c).collect();
|
||||
if cmds.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (Some(inv), ElementKind::Shape(sh)) = (e.transform.inverse(), &e.kind) else { continue };
|
||||
let local = inv.apply_vector(d);
|
||||
let mut path = (*sh.path).clone();
|
||||
for cmd in cmds {
|
||||
if !path.move_anchor(cmd, local) && local.length() > 0.0 {
|
||||
return Err(EngineError::Param(format!("no point ({}, {cmd}) to move", e.id.0)));
|
||||
}
|
||||
}
|
||||
check_extent(&path)?;
|
||||
if let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind {
|
||||
sh.path = Arc::new(path);
|
||||
}
|
||||
moved.insert(e.id);
|
||||
}
|
||||
if points.iter().any(|(id, _)| !moved.contains(id)) {
|
||||
return Err(EngineError::Param("a point to move is not on the active layer at this frame".into()));
|
||||
}
|
||||
let ids: Vec<ElementId> = moved.into_iter().collect();
|
||||
if merge_after {
|
||||
remerge_in_place(s, &ids)?;
|
||||
}
|
||||
Ok(json!({
|
||||
"x": target.x, "y": target.y,
|
||||
"snapped": snapped.map(|(q, kind)| json!({"x": q.x, "y": q.y, "to": kind.key()})),
|
||||
"points": if merge_after { json!([]) } else { json!(points.iter().map(|(id, c)| [id.0, *c as u64]).collect::<Vec<_>>()) },
|
||||
"moved": ids.len(),
|
||||
"merged": merge_after,
|
||||
}))
|
||||
}
|
||||
|
||||
// ----- snapping ---------------------------------------------------------------------------------
|
||||
|
||||
/// What a dragged point snapped to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum SnapTo {
|
||||
/// An anchor (corner or end).
|
||||
Point,
|
||||
/// A stroke or a fill's edge.
|
||||
Line,
|
||||
}
|
||||
|
||||
impl SnapTo {
|
||||
pub fn key(&self) -> &'static str {
|
||||
match self {
|
||||
SnapTo::Point => "point",
|
||||
SnapTo::Line => "line",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors and segments to snap to, in stage space.
|
||||
#[derive(Default)]
|
||||
struct Targets {
|
||||
points: Vec<Vec2>,
|
||||
segs: Vec<Cubic>,
|
||||
}
|
||||
|
||||
/// The shapes' anchors and segments, leaving out the anchors `skip_point(id, cmd)` and the
|
||||
/// segments `skip_seg(id, cmd)` says move along.
|
||||
fn targets(els: &[Arc<Element>], skip_el: impl Fn(ElementId) -> bool, skip_point: impl Fn(ElementId, usize) -> bool, skip_seg: impl Fn(ElementId, usize) -> bool) -> Targets {
|
||||
let mut t = Targets::default();
|
||||
for e in els.iter().filter(|e| !skip_el(e.id)) {
|
||||
let ElementKind::Shape(sh) = &e.kind else { continue };
|
||||
if t.points.len() + t.segs.len() > MAX_TARGETS {
|
||||
break;
|
||||
}
|
||||
let mut path = (*sh.path).clone();
|
||||
path.close_explicitly();
|
||||
for (i, q) in path.editable_anchors() {
|
||||
if !skip_point(e.id, i) {
|
||||
t.points.push(e.transform.apply(q));
|
||||
}
|
||||
}
|
||||
for k in 0..path.cmds.len().min(MAX_TARGETS) {
|
||||
if !skip_seg(e.id, k)
|
||||
&& let Some(c) = rawgeom::segment_cubic(&path, k)
|
||||
{
|
||||
t.segs.push(rawgeom::transform(&c, &e.transform));
|
||||
}
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// The nearest anchor within `radius` of `p`, else the nearest point on a segment.
|
||||
fn snap_to(t: &Targets, p: Vec2, radius: f32) -> Option<(Vec2, SnapTo, f32)> {
|
||||
let point = t.points.iter().map(|q| (*q, q.distance(p))).filter(|(_, d)| *d <= radius).min_by(|a, b| a.1.total_cmp(&b.1));
|
||||
if let Some((q, d)) = point {
|
||||
return Some((q, SnapTo::Point, d));
|
||||
}
|
||||
let near = |c: &Cubic| {
|
||||
let (lo, hi) = c.iter().fold((Vec2::new(f32::INFINITY, f32::INFINITY), Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY)), |(lo, hi), q| (Vec2::new(lo.x.min(q.x), lo.y.min(q.y)), Vec2::new(hi.x.max(q.x), hi.y.max(q.y))));
|
||||
p.x >= lo.x - radius && p.x <= hi.x + radius && p.y >= lo.y - radius && p.y <= hi.y + radius
|
||||
};
|
||||
t.segs
|
||||
.iter()
|
||||
.filter(|c| near(c))
|
||||
.map(|c| {
|
||||
let (u, d) = rawgeom::nearest(c, p);
|
||||
(cubic_point(c, u), d)
|
||||
})
|
||||
.filter(|(_, d)| *d <= radius)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(q, d)| (q, SnapTo::Line, d))
|
||||
}
|
||||
|
||||
/// Where a point being moved (`moving`: the anchors that go with it) snaps near `to`.
|
||||
fn snap_point(els: &[Arc<Element>], to: Vec2, radius: f32, moving: &[(ElementId, usize)]) -> Option<(Vec2, SnapTo)> {
|
||||
// The segments leaving the moving anchors move too.
|
||||
let mut segs: BTreeSet<(ElementId, usize)> = BTreeSet::new();
|
||||
for e in els {
|
||||
let ElementKind::Shape(sh) = &e.kind else { continue };
|
||||
for (_, cmd) in moving.iter().filter(|(id, _)| *id == e.id) {
|
||||
let (i, o) = sh.path.anchor_segments(*cmd);
|
||||
segs.extend(i.into_iter().chain(o).map(|k| (e.id, k)));
|
||||
}
|
||||
}
|
||||
let t = targets(els, |_| false, |id, c| moving.contains(&(id, c)), |id, k| segs.contains(&(id, k)));
|
||||
snap_to(&t, to, radius).map(|(q, k, _)| (q, k))
|
||||
}
|
||||
|
||||
/// After the selection moved: the extra move that snaps one of its anchors (the nearest to
|
||||
/// `from` when given, else whichever comes closest) onto an anchor or line of the shapes that
|
||||
/// did not move, within `radius`.
|
||||
pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option<Vec2>) -> Option<(Vec2, Vec2, SnapTo)> {
|
||||
let mut own: Vec<Vec2> = Vec::new();
|
||||
for (_, e) in s.selected_elements() {
|
||||
if let ElementKind::Shape(sh) = &e.kind {
|
||||
own.extend(sh.path.editable_anchors().into_iter().map(|(_, q)| e.transform.apply(q)));
|
||||
}
|
||||
if own.len() > 4 * MAX_POINTS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let candidates: Vec<Vec2> = match from {
|
||||
Some(f) => own.iter().copied().min_by(|a, b| a.distance(f).total_cmp(&b.distance(f))).into_iter().collect(),
|
||||
None => own.into_iter().take(512).collect(),
|
||||
};
|
||||
if candidates.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// What stays put on the layers the selection is on (ADR 0044).
|
||||
let rest: Vec<Arc<Element>> = s.selected_layers().into_iter().flat_map(|l| s.elements_on(l).into_iter().filter(move |e| !s.selection.contains(l, e.id))).collect();
|
||||
let t = targets(&rest, |_| false, |_, _| false, |_, _| false);
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter_map(|c| snap_to(&t, c, radius).map(|(q, k, d)| (c, q, k, d)))
|
||||
.min_by(|a, b| a.3.total_cmp(&b.3))
|
||||
.map(|(c, q, k, _)| (q - c, q, k))
|
||||
}
|
||||
|
||||
// ----- the marquee ------------------------------------------------------------------------------
|
||||
|
||||
fn contains(outer: &Rect, inner: &Rect) -> bool {
|
||||
inner.min.x >= outer.min.x && inner.min.y >= outer.min.y && inner.max.x <= outer.max.x && inner.max.y <= outer.max.y
|
||||
}
|
||||
|
||||
/// Whether the playhead is on a keyframe whose artwork can be cut here (not inside a tween, where
|
||||
/// an edit would add a keyframe).
|
||||
fn on_editable_key(s: &Session) -> bool {
|
||||
s.active_layer().and_then(|l| l.keyframe_at(s.frame)).is_some_and(|k| k.motion.is_none() && (k.tween.is_none() || k.start == s.frame))
|
||||
}
|
||||
|
||||
/// The marquee (ADR 0041, 0044): on every visible, unlocked layer, the parts of raw shapes under
|
||||
/// the rectangle (cut at its edges) and the objects wholly inside it.
|
||||
fn select_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Vec2::new(f32_req(p, "x0")?, f32_req(p, "y0")?);
|
||||
let b = Vec2::new(f32_req(p, "x1")?, f32_req(p, "y1")?);
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
let r = Rect::from_points(a, b);
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Ok(json!({"selected": s.selection.id_list(), "cut": 0}));
|
||||
}
|
||||
// What each layer has under the marquee, from one display list: wholly inside, or (raw
|
||||
// shapes) partly.
|
||||
let mut found: Vec<(LayerId, Vec<ElementId>, Vec<ElementId>)> = Vec::new();
|
||||
let layers: Vec<LayerId> = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect();
|
||||
for l in layers {
|
||||
let (mut picked, mut partial) = (Vec::new(), Vec::new());
|
||||
for e in s.elements_on(l) {
|
||||
let bounds = s.element_bounds_on(l, e.id);
|
||||
if bounds.is_empty() || bounds.intersect(&r).is_empty() {
|
||||
continue;
|
||||
}
|
||||
if contains(&r, &bounds) {
|
||||
picked.push(e.id);
|
||||
} else if mergeable(&e).is_some() {
|
||||
partial.push(e.id);
|
||||
}
|
||||
}
|
||||
if !picked.is_empty() || !partial.is_empty() {
|
||||
found.push((l, picked, partial));
|
||||
}
|
||||
}
|
||||
let mut cut = 0;
|
||||
let (mut origin, mut inside): (CutOrigin, Vec<ElementId>) = (Vec::new(), Vec::new());
|
||||
let mut hit: Vec<LayerId> = Vec::new();
|
||||
for (l, picked, partial) in found {
|
||||
let (n, o, i) = s.with_layer(l, |s| marquee_layer(s, &r, picked, &partial))?;
|
||||
cut += n;
|
||||
origin.extend(o);
|
||||
inside.extend(i);
|
||||
hit.push(l);
|
||||
}
|
||||
if !inside.is_empty() {
|
||||
s.pending_cut = Some((origin, inside));
|
||||
}
|
||||
// The active layer stays when the marquee took something there, else the topmost that it
|
||||
// did becomes active, as a click would make it.
|
||||
if !hit.contains(&s.layer)
|
||||
&& let Some(&top) = hit.first()
|
||||
{
|
||||
s.layer = top;
|
||||
}
|
||||
Ok(json!({"selected": s.selection.id_list(), "cut": cut}))
|
||||
}
|
||||
|
||||
/// The marquee on the active layer: raw shapes partly under `r` are cut at its edges and the
|
||||
/// parts inside are selected, the rest stay as they are; `picked` (wholly inside) are selected.
|
||||
/// How many pieces it cut, each piece with the shape it came from, and the pieces inside.
|
||||
fn marquee_layer(s: &mut Session, r: &Rect, mut picked: Vec<ElementId>, partial: &[ElementId]) -> Result<(usize, CutOrigin, Vec<ElementId>)> {
|
||||
let here = s.layer;
|
||||
let mut cut = 0;
|
||||
let (mut origin, mut inside_all) = (Vec::new(), Vec::new());
|
||||
if !partial.is_empty() && on_editable_key(s) {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let existing = kf.elements.clone();
|
||||
let idx: Vec<usize> = existing.iter().enumerate().filter(|(_, e)| partial.contains(&e.id)).map(|(i, _)| i).collect();
|
||||
// Parts already selected (an earlier marquee, with Shift) stay selected, cut or not.
|
||||
let parts: Vec<Part> = idx.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), s.selection.contains(here, e.id))).collect();
|
||||
let cutter = Path::rect(r.min.x, r.min.y, r.width(), r.height());
|
||||
match merge::remerge_with(s, &parts, Some(&cutter)) {
|
||||
Some(rm) if !rm.inside.is_empty() => {
|
||||
origin = rm.from.iter().filter_map(|&(piece, part)| idx.get(part).and_then(|&i| existing.get(i)).map(|e| (piece, e.id))).collect();
|
||||
cut = rm.inside.len();
|
||||
let gone: Vec<ElementId> = idx.iter().filter_map(|&i| existing.get(i)).map(|e| e.id).collect();
|
||||
s.selection.retain(|l, id| l != here || !gone.contains(&id));
|
||||
let mut inside = rm.inside;
|
||||
inside.extend(rm.picked.iter().filter(|id| !inside.contains(id)).copied().collect::<Vec<_>>());
|
||||
picked.extend(inside.iter().copied());
|
||||
merge::replace(s, &idx, rm.out, false)?;
|
||||
inside_all = inside;
|
||||
}
|
||||
// Only their bounds reached in: nothing of them is under the marquee.
|
||||
Some(_) => {}
|
||||
// Too much to cut at once: they are selected whole.
|
||||
None => picked.extend(partial.iter().copied()),
|
||||
}
|
||||
} else {
|
||||
picked.extend(partial.iter().copied());
|
||||
}
|
||||
s.selection.extend_on(here, picked);
|
||||
Ok((cut, origin, inside_all))
|
||||
}
|
||||
|
||||
// ----- merging again ----------------------------------------------------------------------------
|
||||
|
||||
fn merge_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match opt_u64_list(p, "ids")? {
|
||||
Some(v) => remerge_in_place(s, &v.into_iter().map(ElementId).collect::<Vec<_>>())?,
|
||||
// The selection's shapes, on each layer they are on.
|
||||
None => {
|
||||
s.each_layer(true, |s| {
|
||||
let ids = s.selection.on(s.layer);
|
||||
remerge_in_place(s, &ids)?;
|
||||
Ok(json!({}))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(json!({"selected": s.selection.id_list()}))
|
||||
}
|
||||
|
||||
/// Merges the raw shapes `ids` again with the raw shapes they touch, keeping their stacking (an
|
||||
/// edit changed them in place). Selected shapes' pieces stay selected.
|
||||
pub(crate) fn remerge_in_place(s: &mut Session, ids: &[ElementId]) -> Result<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
let existing = kf.elements.clone();
|
||||
let area = existing.iter().filter(|e| ids.contains(&e.id)).filter_map(|e| mergeable(e).map(|sh| reach(sh, &e.transform))).fold(Rect::EMPTY, |r, b| r.union(&b));
|
||||
if area.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let touching: Vec<usize> = existing.iter().enumerate().filter(|(_, e)| mergeable(e).is_some_and(|sh| !reach(sh, &e.transform).intersect(&area).is_empty())).map(|(i, _)| i).collect();
|
||||
let here = s.layer;
|
||||
let parts: Vec<Part> = touching.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), s.selection.contains(here, e.id))).collect();
|
||||
// Too much to merge at once: the shapes stay as edited.
|
||||
let Some((out, picked)) = merge::remerge(s, &parts) else { return Ok(()) };
|
||||
let gone: Vec<ElementId> = touching.iter().filter_map(|&i| existing.get(i)).map(|e| e.id).collect();
|
||||
merge::replace(s, &touching, out, false)?;
|
||||
s.selection.retain(|l, id| l != here || !gone.contains(&id));
|
||||
s.selection.extend_on(here, picked);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
//! The Subselection tool on raw shapes (ADR 0042; issue #42 §3).
|
||||
//!
|
||||
//! Clicking a raw stroke or fill shows the anchors of every raw shape **connected** to it: the
|
||||
//! strokes and fills that meet it at a point or along an edge, and the ones those meet, and so
|
||||
//! on. A layer's merged drawing stores a shared corner once in each shape that has it (ADR 0031),
|
||||
//! so the anchors are listed once per position. Moving one moves every shape that shares it
|
||||
//! (`raw.move_point`); dragging a handle changes the curve in every shape that has that edge
|
||||
//! (`raw.move_handle`).
|
||||
//!
|
||||
//! Which anchors are selected is view state, kept by the editor (as for drawing objects): the
|
||||
//! commands here report anchors and handles by stage position, and take positions back.
|
||||
|
||||
use crate::cmds_raw::{check_extent, edit_edge, remerge_in_place};
|
||||
use crate::merge::mergeable;
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind};
|
||||
use anicraft_geom::planar::SNAP;
|
||||
use anicraft_geom::raw::{self as rawgeom, Cubic};
|
||||
use anicraft_geom::{Path, PathCmd, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c(
|
||||
"raw.subselect",
|
||||
"Subselect",
|
||||
"",
|
||||
None,
|
||||
"{x, y, add?: bool, slop?} the Subselection tool's click: the raw stroke or fill at (x, y) and every raw shape connected to it are selected, to show their anchors (an object there is selected alone); returns the anchors and, on an edge, its ends",
|
||||
false,
|
||||
subselect as crate::RunFn,
|
||||
),
|
||||
c(
|
||||
"raw.subselect_rect",
|
||||
"Subselect Rectangle",
|
||||
"",
|
||||
None,
|
||||
"{x0, y0, x1, y1, add?: bool} the Subselection tool's marquee, on the active layer only: the shapes it touches are selected whole (raw ones with every raw shape connected to them); returns the raw anchors inside it",
|
||||
false,
|
||||
subselect_rect,
|
||||
),
|
||||
c("raw.points", "Raw Points", "", None, "{ids?: [..]} the anchors of raw shapes (default: the selection), once per position, and the handles of their curved segments", false, points_cmd),
|
||||
c(
|
||||
"raw.move_handle",
|
||||
"Move Handle",
|
||||
"",
|
||||
None,
|
||||
"{id, cmd, slot: 1|2, dx, dy, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false)",
|
||||
true,
|
||||
move_handle,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Most raw shapes one connected set takes in (keeps a click's cost bounded).
|
||||
const MAX_SHAPES: usize = 20_000;
|
||||
/// Most anchors listed.
|
||||
const MAX_ANCHORS: usize = 50_000;
|
||||
/// Raw shapes are connected where a point of one lies this near the other.
|
||||
const TOUCH: f32 = 2.0 * SNAP;
|
||||
/// Flattening tolerance for the connection test.
|
||||
const FLAT: f32 = 0.05;
|
||||
|
||||
// ----- connected raw shapes ----------------------------------------------------------------------
|
||||
|
||||
/// A raw shape's stage-space geometry for the connection test.
|
||||
struct Geo {
|
||||
id: ElementId,
|
||||
bounds: Rect,
|
||||
anchors: Vec<Vec2>,
|
||||
lines: Vec<(Vec2, Vec2)>,
|
||||
}
|
||||
|
||||
fn geo(e: &Element) -> Option<Geo> {
|
||||
let sh = mergeable(e)?;
|
||||
let m = e.transform;
|
||||
let anchors = sh.path.editable_anchors().into_iter().map(|(_, p)| m.apply(p)).collect();
|
||||
let mut lines = Vec::new();
|
||||
for pl in sh.path.flatten(&m, FLAT) {
|
||||
lines.extend(pl.points.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))));
|
||||
if pl.closed
|
||||
&& let (Some(a), Some(b)) = (pl.points.last(), pl.points.first())
|
||||
{
|
||||
lines.push((*a, *b));
|
||||
}
|
||||
}
|
||||
Some(Geo { id: e.id, bounds: sh.path.bounds().transformed(&m).inflate(TOUCH), anchors, lines })
|
||||
}
|
||||
|
||||
/// Whether a point of `a` lies on `b`, within [`TOUCH`].
|
||||
fn lands_on(a: &Geo, b: &Geo) -> bool {
|
||||
a.anchors.iter().filter(|p| b.bounds.contains(**p)).any(|p| b.lines.iter().any(|(u, v)| anicraft_geom::segment_distance(*p, *u, *v) <= TOUCH))
|
||||
}
|
||||
|
||||
fn touch(a: &Geo, b: &Geo) -> bool {
|
||||
!a.bounds.intersect(&b.bounds).is_empty() && (lands_on(a, b) || lands_on(b, a))
|
||||
}
|
||||
|
||||
/// A grid over the shapes' bounds, so each shape is only tested against its neighbours.
|
||||
struct Grid {
|
||||
cell: f32,
|
||||
cells: HashMap<(i64, i64), Vec<usize>>,
|
||||
/// Shapes too large for the grid: tested against everything.
|
||||
big: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Most cells one shape is put in before it counts as big.
|
||||
const MAX_CELLS: i64 = 256;
|
||||
|
||||
impl Grid {
|
||||
fn new(geos: &[Geo]) -> Grid {
|
||||
let sum: f32 = geos.iter().map(|g| g.bounds.width().max(g.bounds.height())).sum();
|
||||
let cell = (sum / geos.len().max(1) as f32).clamp(1.0, 1.0e6);
|
||||
let mut grid = Grid { cell, cells: HashMap::new(), big: Vec::new() };
|
||||
for (i, g) in geos.iter().enumerate() {
|
||||
match grid.span(&g.bounds) {
|
||||
Some(cells) => {
|
||||
for k in cells {
|
||||
grid.cells.entry(k).or_default().push(i);
|
||||
}
|
||||
}
|
||||
None => grid.big.push(i),
|
||||
}
|
||||
}
|
||||
grid
|
||||
}
|
||||
|
||||
/// The cells `r` covers, unless that is too many.
|
||||
fn span(&self, r: &Rect) -> Option<Vec<(i64, i64)>> {
|
||||
let k = |v: f32| (v / self.cell).floor() as i64;
|
||||
let (x0, y0, x1, y1) = (k(r.min.x), k(r.min.y), k(r.max.x), k(r.max.y));
|
||||
if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_CELLS {
|
||||
return None;
|
||||
}
|
||||
Some((x0..=x1).flat_map(|x| (y0..=y1).map(move |y| (x, y))).collect())
|
||||
}
|
||||
|
||||
/// The shapes that may touch `r` (every shape when `r` is too large).
|
||||
fn near(&self, r: &Rect, n: usize) -> Vec<usize> {
|
||||
let mut out: Vec<usize> = match self.span(r) {
|
||||
Some(cells) => cells.iter().filter_map(|k| self.cells.get(k)).flatten().copied().chain(self.big.iter().copied()).collect(),
|
||||
None => (0..n).collect(),
|
||||
};
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw shapes among `els` connected to the `seeds` (themselves included): sharing a point
|
||||
/// or an edge, directly or through others. Objects among the seeds are left out.
|
||||
pub fn connected(els: &[Arc<Element>], seeds: &[ElementId]) -> Vec<ElementId> {
|
||||
let geos: Vec<Geo> = els.iter().filter_map(|e| geo(e)).take(MAX_SHAPES).collect();
|
||||
let grid = Grid::new(&geos);
|
||||
let mut seen = vec![false; geos.len()];
|
||||
let mut todo: Vec<usize> = geos.iter().enumerate().filter(|(_, g)| seeds.contains(&g.id)).map(|(i, _)| i).collect();
|
||||
for &i in &todo {
|
||||
if let Some(s) = seen.get_mut(i) {
|
||||
*s = true;
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
while let Some(i) = todo.pop() {
|
||||
let Some(g) = geos.get(i) else { continue };
|
||||
out.push(g.id);
|
||||
for j in grid.near(&g.bounds, geos.len()) {
|
||||
if seen.get(j).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
if geos.get(j).is_some_and(|h| touch(g, h)) {
|
||||
if let Some(s) = seen.get_mut(j) {
|
||||
*s = true;
|
||||
}
|
||||
todo.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
// In stacking order, as the layer has them.
|
||||
els.iter().map(|e| e.id).filter(|id| out.contains(id)).collect()
|
||||
}
|
||||
|
||||
// ----- anchors and handles -----------------------------------------------------------------------
|
||||
|
||||
/// A handle of a curved segment, as the Subselection tool shows it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Handle {
|
||||
/// Where the handle is, and the anchor its direction line starts from (stage space).
|
||||
pub at: Vec2,
|
||||
pub anchor: Vec2,
|
||||
/// The shape, segment and control point (1: the segment's first, 2: its second) that
|
||||
/// `raw.move_handle` takes.
|
||||
pub id: ElementId,
|
||||
pub cmd: usize,
|
||||
pub slot: u8,
|
||||
}
|
||||
|
||||
/// The anchors and handles of a set of raw shapes.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RawPoints {
|
||||
/// Every anchor once (shapes share corners), in stage space.
|
||||
pub anchors: Vec<Vec2>,
|
||||
/// The handles of curved segments, once per position.
|
||||
pub handles: Vec<Handle>,
|
||||
}
|
||||
|
||||
/// Positions seen so far, within [`SNAP`] of each other counting as one.
|
||||
#[derive(Default)]
|
||||
struct Seen(HashMap<(i64, i64), Vec<Vec2>>);
|
||||
|
||||
impl Seen {
|
||||
fn key(p: Vec2) -> (i64, i64) {
|
||||
((p.x / SNAP).floor() as i64, (p.y / SNAP).floor() as i64)
|
||||
}
|
||||
/// Whether `p` is new (and remembers it).
|
||||
fn insert(&mut self, p: Vec2) -> bool {
|
||||
let (kx, ky) = Seen::key(p);
|
||||
let near = (-1..=1).any(|dx| (-1..=1).any(|dy| self.0.get(&(kx + dx, ky + dy)).is_some_and(|v| v.iter().any(|q| q.distance(p) <= SNAP))));
|
||||
if !near {
|
||||
self.0.entry((kx, ky)).or_default().push(p);
|
||||
}
|
||||
!near
|
||||
}
|
||||
}
|
||||
|
||||
/// The path as the raw commands address it (a closed subpath's last side written out).
|
||||
fn explicit(path: &Path) -> Path {
|
||||
let mut p = path.clone();
|
||||
p.close_explicitly();
|
||||
p
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The raw shapes on the active layer connected to `ids` (themselves included).
|
||||
pub fn raw_connected(&self, ids: &[ElementId]) -> Vec<ElementId> {
|
||||
connected(&self.visible_elements(), ids)
|
||||
}
|
||||
|
||||
/// The anchors (once per position) and curve handles of the raw shapes `ids` on the active
|
||||
/// layer.
|
||||
pub fn raw_points(&self, ids: &[ElementId]) -> RawPoints {
|
||||
let mut out = RawPoints::default();
|
||||
let (mut anchors, mut handles) = (Seen::default(), HashMap::<((i64, i64), (i64, i64)), Vec<(Vec2, Vec2)>>::new());
|
||||
for e in self.visible_elements().iter().filter(|e| ids.contains(&e.id)) {
|
||||
let Some(sh) = mergeable(e) else { continue };
|
||||
let m = e.transform;
|
||||
let path = explicit(&sh.path);
|
||||
for (_, q) in path.editable_anchors() {
|
||||
let q = m.apply(q);
|
||||
if out.anchors.len() < MAX_ANCHORS && anchors.insert(q) {
|
||||
out.anchors.push(q);
|
||||
}
|
||||
}
|
||||
for k in 0..path.cmds.len().min(MAX_ANCHORS) {
|
||||
if !matches!(path.cmds.get(k), Some(PathCmd::CubicTo(..) | PathCmd::QuadTo(..))) {
|
||||
continue;
|
||||
}
|
||||
let Some(c) = rawgeom::segment_cubic(&path, k).map(|c| rawgeom::transform(&c, &m)) else { continue };
|
||||
for (slot, at, anchor) in [(1u8, c[1], c[0]), (2u8, c[2], c[3])] {
|
||||
// A handle on its anchor has no direction to show.
|
||||
if at.distance(anchor) <= SNAP || out.handles.len() >= MAX_ANCHORS {
|
||||
continue;
|
||||
}
|
||||
// One edge shared by two shapes has its handles in both: show them once.
|
||||
let key = (Seen::key(anchor), Seen::key(at));
|
||||
let list = handles.entry(key).or_default();
|
||||
if list.iter().any(|(a, h)| a.distance(anchor) <= SNAP && h.distance(at) <= SNAP) {
|
||||
continue;
|
||||
}
|
||||
list.push((anchor, at));
|
||||
out.handles.push(Handle { at, anchor, id: e.id, cmd: k, slot });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn points_json(pts: &RawPoints) -> Value {
|
||||
json!({
|
||||
"anchors": pts.anchors.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(),
|
||||
"handles": pts.handles.iter().map(|h| json!({"x": h.at.x, "y": h.at.y, "ax": h.anchor.x, "ay": h.anchor.y, "id": h.id.0, "cmd": h.cmd, "slot": h.slot})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
fn points_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids: Vec<ElementId> = match opt_u64_list(p, "ids")? {
|
||||
Some(v) => v.into_iter().map(ElementId).collect(),
|
||||
None => s.selection.on(s.layer),
|
||||
};
|
||||
Ok(points_json(&s.raw_points(&ids)))
|
||||
}
|
||||
|
||||
// ----- clicking and the marquee ------------------------------------------------------------------
|
||||
|
||||
fn subselect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0);
|
||||
let Some((layer, hit)) = s.hit_test(at, slop) else {
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
return Ok(json!({"selected": s.selection.id_list(), "raw": false, "ends": []}));
|
||||
};
|
||||
if layer != s.layer {
|
||||
s.layer = layer;
|
||||
s.selection.clear();
|
||||
}
|
||||
let els = s.visible_elements();
|
||||
let el = els.iter().find(|e| e.id == hit);
|
||||
let raw = el.is_some_and(|e| mergeable(e).is_some());
|
||||
let picked = if raw { connected(&els, &[hit]) } else { vec![hit] };
|
||||
// On an edge (not inside a fill): its ends, whose handles show.
|
||||
let mut ends = Vec::new();
|
||||
if let Some(e) = el.filter(|_| raw)
|
||||
&& let Some(sh) = mergeable(e)
|
||||
{
|
||||
let path = explicit(&sh.path);
|
||||
if let Some((cmd, _, d)) = path.nearest_segment(at, &e.transform)
|
||||
&& d <= slop + sh.stroke.as_ref().map_or(0.0, |st| st.width * 0.5 * e.transform.mean_scale())
|
||||
&& let Some(c) = rawgeom::segment_cubic(&path, cmd)
|
||||
{
|
||||
ends = vec![e.transform.apply(c[0]), e.transform.apply(c[3])];
|
||||
}
|
||||
}
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
s.selection.extend_on(s.layer, picked);
|
||||
let mut v = if raw { points_json(&s.raw_points(&s.selection.on(s.layer))) } else { json!({}) };
|
||||
v["selected"] = json!(s.selection.id_list());
|
||||
v["raw"] = json!(raw);
|
||||
v["ends"] = json!(ends.iter().map(|q| [q.x, q.y]).collect::<Vec<_>>());
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Whether the shape `e` (stage space) has a part in `r`: a point, a line through it, or a fill
|
||||
/// around it. Anything else counts by its bounds.
|
||||
fn touches_rect(e: &Element, r: &Rect, bounds: &Rect) -> bool {
|
||||
if bounds.intersect(r).is_empty() {
|
||||
return false;
|
||||
}
|
||||
let ElementKind::Shape(sh) = &e.kind else { return true };
|
||||
let m = e.transform;
|
||||
let crosses = |a: Vec2, b: Vec2| {
|
||||
if r.contains(a) || r.contains(b) {
|
||||
return true;
|
||||
}
|
||||
let (p, q, u, v) = (r.min, Vec2::new(r.max.x, r.min.y), r.max, Vec2::new(r.min.x, r.max.y));
|
||||
[(p, q), (q, u), (u, v), (v, p)].into_iter().any(|(c, d)| segments_cross(a, b, c, d))
|
||||
};
|
||||
for pl in sh.path.flatten(&m, 0.25) {
|
||||
if pl.points.windows(2).any(|w| matches!(w, [a, b] if crosses(*a, *b))) || pl.points.first().is_some_and(|p| r.contains(*p)) {
|
||||
return true;
|
||||
}
|
||||
if pl.closed && matches!((pl.points.last(), pl.points.first()), (Some(a), Some(b)) if crosses(*a, *b)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
sh.fill.is_some() && sh.path.contains(r.center(), &m, sh.fill_rule)
|
||||
}
|
||||
|
||||
fn segments_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> bool {
|
||||
let side = |p: Vec2, q: Vec2, x: Vec2| (q - p).cross(x - p);
|
||||
let (d1, d2, d3, d4) = (side(c, d, a), side(c, d, b), side(a, b, c), side(a, b, d));
|
||||
(d1 * d2 <= 0.0) && (d3 * d4 <= 0.0)
|
||||
}
|
||||
|
||||
fn subselect_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Vec2::new(f32_req(p, "x0")?, f32_req(p, "y0")?);
|
||||
let b = Vec2::new(f32_req(p, "x1")?, f32_req(p, "y1")?);
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
let r = Rect::from_points(a, b);
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer);
|
||||
let empty = json!({"selected": s.selection.id_list(), "anchors": []});
|
||||
if !usable || !(r.width() > 0.0 || r.height() > 0.0) {
|
||||
return Ok(empty);
|
||||
}
|
||||
let els = s.visible_elements();
|
||||
let (mut seeds, mut objects) = (Vec::new(), Vec::new());
|
||||
for e in &els {
|
||||
if !touches_rect(e, &r, &s.element_bounds(e.id)) {
|
||||
continue;
|
||||
}
|
||||
if mergeable(e).is_some() { seeds.push(e.id) } else { objects.push(e.id) }
|
||||
}
|
||||
let raw = connected(&els, &seeds);
|
||||
// Subselection's marquee stays on the active layer, as in Animate (ADR 0042, 0044).
|
||||
s.selection.extend_on(s.layer, raw.iter().chain(&objects).copied());
|
||||
let inside: Vec<[f32; 2]> = s.raw_points(&raw).anchors.into_iter().filter(|q| r.contains(*q)).map(|q| [q.x, q.y]).collect();
|
||||
Ok(json!({"selected": s.selection.id_list(), "anchors": inside}))
|
||||
}
|
||||
|
||||
// ----- handles -----------------------------------------------------------------------------------
|
||||
|
||||
fn move_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?);
|
||||
let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?;
|
||||
let cmd = usize::try_from(cmd).unwrap_or(usize::MAX);
|
||||
let slot = opt_u64(p, "slot")?.filter(|k| matches!(k, 1 | 2)).ok_or_else(|| EngineError::Param("param 'slot' must be 1 or 2".into()))? as usize;
|
||||
let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
let merge_after = opt_bool(p, "merge")?.unwrap_or(true);
|
||||
let els = s.visible_elements();
|
||||
let el = els.iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?;
|
||||
let ElementKind::Shape(sh) = &el.kind else { return Err(EngineError::State("only shapes have handles".into())) };
|
||||
let path = explicit(&sh.path);
|
||||
if !matches!(path.cmds.get(cmd), Some(PathCmd::CubicTo(..) | PathCmd::QuadTo(..))) {
|
||||
return Err(EngineError::Param(format!("segment {cmd} of this shape is not a curve (it has no handles)")));
|
||||
}
|
||||
let old: Cubic = rawgeom::segment_cubic(&path, cmd).map(|c| rawgeom::transform(&c, &el.transform)).ok_or_else(|| EngineError::Param(format!("no segment {cmd} on this shape")))?;
|
||||
let mut new = old;
|
||||
if let Some(h) = new.get_mut(slot) {
|
||||
*h = *h + d;
|
||||
}
|
||||
if !new.iter().all(|q| q.is_finite()) {
|
||||
return Err(EngineError::Param("the move is too large".into()));
|
||||
}
|
||||
let mut bounds = Path::new();
|
||||
bounds.move_to(new[0]).cubic_to(new[1], new[2], new[3]);
|
||||
check_extent(&bounds)?;
|
||||
let raw = mergeable(el).is_some();
|
||||
let changed = edit_edge(s, id, cmd, &old, &new, raw)?;
|
||||
if raw && merge_after {
|
||||
remerge_in_place(s, &changed)?;
|
||||
}
|
||||
let at = new.get(slot).copied().unwrap_or(new[0]);
|
||||
Ok(json!({"x": at.x, "y": at.y, "changed": changed.iter().map(|e| e.0).collect::<Vec<_>>(), "merged": raw && merge_after}))
|
||||
}
|
||||
@@ -1,16 +1,19 @@
|
||||
//! Kept scripts (ADR 0013 tier 1): frame scripts written in another language (ActionScript, as
|
||||
//! Kept scripts (ADR 0013): frame scripts written in another language (ActionScript, as
|
||||
//! Animate documents bring them), symbol linkage classes and the document class, kept verbatim
|
||||
//! with the document. Nothing runs them yet: Test Movie, rendering and every export skip them.
|
||||
//! with the document. Scripts in the ActionScript 3.0 subset run in Test Movie and the HTML
|
||||
//! canvas export (tier 2); the rest are kept and not run, with the problems that say why.
|
||||
//! Rendering and the other exports never run scripts.
|
||||
//!
|
||||
//! `script.set / clear / list` edit and list a keyframe's kept script; `script.set_class`
|
||||
//! sets a symbol's linkage class or the document class. A keyframe holds actions, a plug-in
|
||||
//! `script.set / clear / list` edit and list a keyframe's kept script; `script.check` says
|
||||
//! whether a text would run; `script.set_class` sets a symbol's linkage class or the document
|
||||
//! class. A keyframe holds actions, a plug-in
|
||||
//! frame script *or* a kept script (one `Keyframe.script`), so setting one replaces the other,
|
||||
//! as one undo step.
|
||||
|
||||
use crate::cmds_actions::{Scope, keyframe_in};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::actions::{self, FrameScript, Language, SourceScript};
|
||||
use anicraft_doc::actions::{self, CompileResult, FrameScript, Language, SourceScript};
|
||||
use anicraft_doc::{Linkage, SymbolId};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
@@ -18,9 +21,10 @@ use std::sync::Arc;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("script.set", "Set Frame Script", "", None, "{text?: the script, verbatim (\"\" clears; at most 1 MiB), language?: actionscript3|actionscript1or2|other (default: the script's, else actionscript3), symbol?: id, layer?, frame?} keeps a script on the keyframe at the frame (it replaces actions there); it is kept with the document and doesn't run", true, set as crate::RunFn),
|
||||
c("script.set", "Set Frame Script", "", None, "{text?: the script, verbatim (\"\" clears; at most 1 MiB), language?: actionscript3|actionscript1or2|other (default: the script's, else actionscript3), symbol?: id, layer?, frame?} keeps a script on the keyframe at the frame (it replaces actions there); ActionScript 3.0 in the subset runs in Test Movie and the HTML export, the rest is kept and not run (`runs`, `problems` say which)", true, set as crate::RunFn),
|
||||
c("script.clear", "Clear Frame Script", "", None, "{symbol?, layer?, frame?} removes the keyframe's kept script (actions are left alone: actions.clear)", true, clear),
|
||||
c("script.list", "List Frame Scripts", "", None, "{text?: bool (default true)} every kept script in every scene and symbol, with its text, plus symbol linkage classes and the document class", false, list),
|
||||
c("script.list", "List Frame Scripts", "", None, "{text?: bool (default true)} every kept script in every scene and symbol, with its text, whether it runs and its problems, plus symbol linkage classes and the document class", false, list),
|
||||
c("script.check", "Check Frame Script", "", None, "{text: the script, language?: actionscript3|actionscript1or2|other (default actionscript3)} whether it would run (the ActionScript 3.0 subset, ADR 0013), its problems with line and column, what is ignored, and the steps it runs; changes nothing", false, check),
|
||||
c("script.set_class", "Set Script Class", "", None, "{symbol?: id (default: the document), class: dotted class name (\"\" clears), base?: the class it extends} sets a symbol's linkage class, or the document class; kept as text, not run", true, set_class),
|
||||
]
|
||||
}
|
||||
@@ -42,6 +46,30 @@ fn what(script: &Option<FrameScript>) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a script runs, its problems and notes (each `{line, column, message}`; line 0 is
|
||||
/// the whole script).
|
||||
fn status(c: &CompileResult) -> Value {
|
||||
match c {
|
||||
Ok(c) => json!({"runs": true, "problems": [], "notes": c.notes}),
|
||||
Err(p) => json!({"runs": false, "problems": p, "notes": []}),
|
||||
}
|
||||
}
|
||||
|
||||
fn check(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = str_req(p, "text")?;
|
||||
if text.len() > actions::MAX_SOURCE_BYTES {
|
||||
return Err(EngineError::Param(format!("a script is at most {} KiB", actions::MAX_SOURCE_BYTES / 1024)));
|
||||
}
|
||||
let script = SourceScript::new(language(p)?.unwrap_or_default(), text);
|
||||
let c = script.compiled();
|
||||
let mut v = status(c);
|
||||
if let Ok(c) = c {
|
||||
v["steps"] = json!(c.ops);
|
||||
v["describe"] = json!(c.ops.iter().map(|o| o.describe()).collect::<Vec<_>>());
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let lang = language(p)?;
|
||||
let text = match p.get("text") {
|
||||
@@ -74,7 +102,10 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let script = SourceScript::new(lang.or(old.map(|o| o.language)).unwrap_or_default(), text);
|
||||
script.check().map_err(EngineError::Param)?;
|
||||
let out = json!({"layer": lid.0, "keyframe": k.start, "language": script.language.key(), "lines": script.lines(), "bytes": script.text.len(), "replaced": if before == json!("script") { Value::Null } else { before }});
|
||||
let mut out = json!({"layer": lid.0, "keyframe": k.start, "language": script.language.key(), "lines": script.lines(), "bytes": script.text.len(), "replaced": if before == json!("script") { Value::Null } else { before }});
|
||||
if let (Some(o), Value::Object(st)) = (out.as_object_mut(), status(script.compiled())) {
|
||||
o.extend(st);
|
||||
}
|
||||
k.script = Some(FrameScript::Source(Arc::new(script)));
|
||||
Ok(out)
|
||||
}
|
||||
@@ -97,6 +128,9 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for k in &l.keyframes {
|
||||
let Some(src) = k.script.as_ref().and_then(FrameScript::source) else { continue };
|
||||
let mut v = json!({"timeline": name, "layer": l.id.0, "layer_name": l.name, "frame": k.start, "label": k.label, "language": src.language.key(), "lines": src.lines(), "bytes": src.text.len()});
|
||||
if let (Some(o), Value::Object(st)) = (v.as_object_mut(), status(src.compiled())) {
|
||||
o.extend(st);
|
||||
}
|
||||
if with_text {
|
||||
v["text"] = json!(src.text);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Stroke styles (ADR 0046): caps, joins, the miter limit, and dashed and dotted lines.
|
||||
//!
|
||||
//! The same style params work on `element.set_stroke`, the drawing commands and `paint.ink`
|
||||
//! (see [`crate::params::opt_stroke_style`]); `stroke.set_style` is the one Properties uses.
|
||||
//! Dash lengths and dot spacing are in the shape's own units, like the stroke width.
|
||||
|
||||
use crate::cmds_width::{id_param, shape_mut, visible_shape};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Dash, ElementId, StrokeStyle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![CommandSpec {
|
||||
id: "stroke.set_style",
|
||||
label: "Stroke Style",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{cap?: none|round|square, join?: miter|round|bevel, miter? (limit, 1..=100; a corner whose point is longer than this many widths is bevelled), style?: solid|dashed|dotted, dash? ([on, off, ..] lengths in the shape's units; implies dashed), dash_offset?, dot_spacing? (between dots, edge to edge; implies dotted), id? (default: the selected shapes)}",
|
||||
mutates: true,
|
||||
run: |s, p| s.each_layer(false, |s| set_style(s, p)),
|
||||
}]
|
||||
}
|
||||
|
||||
/// What a style is, as commands report it.
|
||||
pub(crate) fn describe(st: &StrokeStyle) -> Value {
|
||||
let mut v = json!({"cap": st.cap.key(), "join": st.join.key(), "miter": st.miter_limit, "style": st.dash_kind().key()});
|
||||
match &st.dash {
|
||||
Some(Dash::Dashed { lengths, offset }) => {
|
||||
v["dash"] = json!(lengths.to_vec());
|
||||
v["dash_offset"] = json!(offset);
|
||||
}
|
||||
Some(Dash::Dotted { spacing }) => v["dot_spacing"] = json!(spacing),
|
||||
None => {}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids: Vec<ElementId> = match id_param(p)? {
|
||||
Some(id) => vec![id],
|
||||
None => s.selection.on(s.layer),
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
let stroked: Vec<ElementId> = ids.into_iter().filter(|id| visible_shape(s, *id).is_ok()).collect();
|
||||
if stroked.is_empty() {
|
||||
return Err(EngineError::State("the selection has no stroked shapes".into()));
|
||||
}
|
||||
let mut last = None;
|
||||
for id in &stroked {
|
||||
if let Some(st) = shape_mut(s, *id)?.stroke.as_mut() {
|
||||
// Each stroke keeps what the params leave out (and sizes a new pattern by its width).
|
||||
let style = opt_stroke_style(p, &st.style, st.width)?.ok_or_else(|| EngineError::Param(format!("give a style to set ({STROKE_STYLE_PARAMS})")))?;
|
||||
st.style = style;
|
||||
last = Some(st.style.clone());
|
||||
}
|
||||
}
|
||||
let mut out = last.as_ref().map_or_else(|| json!({}), describe);
|
||||
out["changed"] = json!(stroked.len());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_doc::{Cap, ElementKind, Join, Stroke};
|
||||
|
||||
fn line(s: &mut Session) -> u64 {
|
||||
let v = s.execute("draw.line", &json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke_width": 4})).unwrap();
|
||||
v["element"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn stroke(s: &Session, id: u64) -> Option<Stroke> {
|
||||
s.visible_elements().into_iter().find(|e| e.id.0 == id).and_then(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.stroke.clone(),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_apply_to_the_selection_undo_and_round_trip() {
|
||||
let mut s = Session::default();
|
||||
let id = line(&mut s);
|
||||
assert!(stroke(&s, id).unwrap().style.is_default(), "new strokes are round and solid");
|
||||
let v = s.execute("stroke.set_style", &json!({"cap": "none", "join": "miter", "miter": 6})).unwrap();
|
||||
assert_eq!((v["cap"].as_str(), v["join"].as_str(), v["miter"].as_f64(), v["changed"].as_u64()), (Some("butt"), Some("miter"), Some(6.0), Some(1)));
|
||||
// Dashed with no lengths: sized by the stroke (4 wide: 12 on, 8 off).
|
||||
let v = s.execute("stroke.set_style", &json!({"style": "dashed"})).unwrap();
|
||||
assert_eq!(v["dash"], json!([12.0, 8.0]));
|
||||
let st = stroke(&s, id).unwrap().style;
|
||||
assert_eq!((st.cap, st.join, st.miter_limit), (Cap::Butt, Join::Miter, 6.0), "what the params leave out stays");
|
||||
// A pattern of its own, then dots; each is one undo step.
|
||||
s.execute("stroke.set_style", &json!({"dash": [5, 2, 1, 2], "dash_offset": 3})).unwrap();
|
||||
assert_eq!(stroke(&s, id).unwrap().style.dash, Dash::Dashed { lengths: vec![5.0, 2.0, 1.0, 2.0].into(), offset: 3.0 }.sanitized());
|
||||
let v = s.execute("stroke.set_style", &json!({"dot_spacing": 3, "id": id})).unwrap();
|
||||
assert_eq!((v["style"].as_str(), v["dot_spacing"].as_f64()), (Some("dotted"), Some(3.0)));
|
||||
s.undo().unwrap();
|
||||
assert_eq!(stroke(&s, id).unwrap().style.dash_kind(), anicraft_doc::DashKind::Dashed);
|
||||
// The .anicraft file keeps it.
|
||||
let text = crate::format::to_json(&s.doc).unwrap();
|
||||
assert!(text.contains("\"butt\"") && text.contains("\"lengths\""), "styled strokes are written");
|
||||
assert_eq!(crate::format::from_json(&text).unwrap(), s.doc);
|
||||
// Back to solid.
|
||||
s.execute("stroke.set_style", &json!({"style": "solid", "cap": "round", "join": "round", "miter": 3})).unwrap();
|
||||
assert!(stroke(&s, id).unwrap().style.is_default());
|
||||
let text = crate::format::to_json(&s.doc).unwrap();
|
||||
assert!(!text.contains("\"style\""), "a default style is written as nothing, as before styles");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_style_params_are_refused_and_change_nothing() {
|
||||
let mut s = Session::default();
|
||||
let id = line(&mut s);
|
||||
for bad in [
|
||||
json!({}),
|
||||
json!({"cap": "pointy"}),
|
||||
json!({"join": 3}),
|
||||
json!({"miter": 0.5}),
|
||||
json!({"miter": 1e9}),
|
||||
json!({"style": "ragged"}),
|
||||
json!({"dash": []}),
|
||||
json!({"dash": [5, 0]}),
|
||||
json!({"dash": [-1, 2]}),
|
||||
json!({"dash": [1e30, 2]}),
|
||||
json!({"dash": (0..40).collect::<Vec<_>>()}),
|
||||
json!({"dash": "5 2"}),
|
||||
json!({"dash_offset": 1e30}),
|
||||
json!({"dot_spacing": -2}),
|
||||
] {
|
||||
assert!(s.execute("stroke.set_style", &bad).is_err(), "{bad}");
|
||||
assert!(s.execute("element.set_stroke", &bad).is_err() || bad == json!({}), "{bad}");
|
||||
}
|
||||
assert!(stroke(&s, id).unwrap().style.is_default());
|
||||
s.execute("edit.deselect", &json!({})).unwrap();
|
||||
assert!(s.execute("stroke.set_style", &json!({"cap": "square"})).is_err(), "nothing selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_set_stroke_and_the_ink_bottle_carry_the_style() {
|
||||
let mut s = Session::default();
|
||||
// Drawing commands take the tool's line style, or params.
|
||||
s.style.line = StrokeStyle { cap: Cap::Square, ..StrokeStyle::default() };
|
||||
let id = line(&mut s);
|
||||
assert_eq!(stroke(&s, id).unwrap().style.cap, Cap::Square);
|
||||
let v = s.execute("draw.rect", &json!({"x": 400, "y": 400, "w": 50, "h": 40, "stroke": "#000000", "join": "bevel", "dash": [4, 2]})).unwrap();
|
||||
let rect = v["element"].as_u64().unwrap();
|
||||
let st = stroke(&s, rect).unwrap().style;
|
||||
assert_eq!((st.cap, st.join, st.dash_kind()), (Cap::Square, Join::Bevel, anicraft_doc::DashKind::Dashed));
|
||||
// element.set_stroke takes the same params.
|
||||
s.execute("element.set_stroke", &json!({"width": 6, "style": "dotted"})).unwrap();
|
||||
assert_eq!(stroke(&s, rect).unwrap().style.dash, Dash::dotted(6.0), "dots one width apart");
|
||||
// The Ink Bottle gives the tool's whole line.
|
||||
s.style.line = StrokeStyle { join: Join::Miter, dash: Dash::dashed(7.0, 3.0), ..StrokeStyle::default() };
|
||||
s.execute("paint.ink", &json!({"x": 200, "y": 100})).unwrap();
|
||||
let st = stroke(&s, id).unwrap().style;
|
||||
assert_eq!((st.join, st.dash), (Join::Miter, Dash::dashed(7.0, 3.0)));
|
||||
s.execute("paint.ink", &json!({"x": 200, "y": 100, "cap": "none", "style": "solid"})).unwrap();
|
||||
let st = stroke(&s, id).unwrap().style;
|
||||
assert_eq!((st.cap, st.dash), (Cap::Butt, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_eyedropper_picks_the_style_and_scales_its_dashes() {
|
||||
let mut s = Session::default();
|
||||
let id = line(&mut s);
|
||||
s.execute("stroke.set_style", &json!({"cap": "square", "dash": [6, 2]})).unwrap();
|
||||
s.execute("element.set_transform", &json!({"sx": 2, "sy": 2})).unwrap();
|
||||
let v = s.execute("paint.pick", &json!({"x": 200, "y": 100})).unwrap();
|
||||
assert_eq!((v["cap"].as_str(), v["style"].as_str()), (Some("square"), Some("dashed")), "{v}");
|
||||
assert_eq!(s.style.line.dash, Dash::dashed(12.0, 4.0), "as drawn: twice as long");
|
||||
assert!(stroke(&s, id).is_some());
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("text.create", "New Text", "", None, "{text, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn),
|
||||
c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, edit),
|
||||
c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, |s, p| s.each_layer(false, |s| edit(s, p))),
|
||||
c("text.fonts", "Fonts", "", None, "{}", false, fonts),
|
||||
]
|
||||
}
|
||||
@@ -153,7 +153,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.text_style = TextStyle { font: block.font.clone(), ..style };
|
||||
let el = Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) };
|
||||
s.editable_keyframe()?.elements.push(Arc::new(el));
|
||||
s.selection = vec![id];
|
||||
s.select_only([id]);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session};
|
||||
use anicraft_doc::{Keyframe, Layer, LayerId, LayerKind, Tween, TweenKind, evaluate_layer_elements};
|
||||
use anicraft_doc::{ElementId, Keyframe, Layer, LayerId, LayerKind, Tween, TweenKind, evaluate_layer_elements};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("layer.toggle_visible", "Show/Hide Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.visible = !l.visible)),
|
||||
c("layer.toggle_lock", "Lock/Unlock Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.locked = !l.locked)),
|
||||
c("layer.toggle_outline", "Outline Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.outline = !l.outline)),
|
||||
c("layer.select", "Select Layer", "", None, "{layer: id} or {index}", false, select_layer),
|
||||
c("layer.select", "Select Layer", "", None, "{layer: id} or {index}, select?: bool (also select all of its artwork at the playhead, as a click on the layer's name does; nothing on a locked or hidden layer)", false, select_layer),
|
||||
c("layer.move_up", "Move Layer Up", "Modify/Timeline", None, "{layer?}", true, |s, p| move_layer(s, p, -1)),
|
||||
c("layer.move_down", "Move Layer Down", "Modify/Timeline", None, "{layer?}", true, |s, p| move_layer(s, p, 1)),
|
||||
c("layer.toggle_mask", "Mask", "Modify/Timeline", None, "{layer?}", true, toggle_mask),
|
||||
@@ -135,6 +135,9 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> {
|
||||
if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Camera) {
|
||||
return Err(EngineError::State("the camera layer holds the camera; it can't become another kind of layer (Remove Camera takes it away)".into()));
|
||||
}
|
||||
if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Armature) {
|
||||
return Err(EngineError::State("an armature layer holds its armature; it can't become another kind of layer (removing its bones frees the instances)".into()));
|
||||
}
|
||||
// Whatever the type, the layer stays in the folder it is in.
|
||||
let folder = tl.folder_of(i);
|
||||
let (kind, parent) = match ty {
|
||||
@@ -169,6 +172,7 @@ fn layer_type_json(s: &Session, id: LayerId) -> Value {
|
||||
LayerKind::Guide => "guide",
|
||||
LayerKind::Folder => "folder",
|
||||
LayerKind::Camera => "camera",
|
||||
LayerKind::Armature => "armature",
|
||||
LayerKind::Normal if masked_by.is_some() => "masked",
|
||||
LayerKind::Normal if guided_by.is_some() => "guided",
|
||||
LayerKind::Normal => "normal",
|
||||
@@ -326,11 +330,14 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
k.elements.clear();
|
||||
k.tween = None;
|
||||
k.motion = None;
|
||||
k.pose = anicraft_doc::Pose::default();
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let elements = if copy { evaluate_layer_elements(layer, frame).map(|(_, e)| e.into_owned()) } else { None };
|
||||
// On an armature layer a copy keeps the pose the frame shows (tweened between keys).
|
||||
let pose = if copy { anicraft_doc::armature::pose_at(layer, frame) } else { None };
|
||||
// Past the end of a motion tween, a copy starts from how its object looks at the end.
|
||||
let last_state = match layer.keyframes.iter().rposition(|k| k.start < frame) {
|
||||
Some(i) if copy && layer.keyframe_index_at(frame).is_none() => {
|
||||
@@ -357,6 +364,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
nk.elements = elements.unwrap_or_default();
|
||||
nk.tween = tween;
|
||||
nk.motion = motion;
|
||||
nk.pose = pose.unwrap_or_default();
|
||||
layer.keyframes.insert(i + 1, Arc::new(nk));
|
||||
}
|
||||
None => {
|
||||
@@ -368,6 +376,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
if let Some(k) = layer.keyframe_mut(i) {
|
||||
if copy {
|
||||
nk.elements = last_state.unwrap_or_else(|| k.elements.clone());
|
||||
nk.pose = k.pose.clone();
|
||||
}
|
||||
k.duration = frame - k.start;
|
||||
}
|
||||
@@ -645,6 +654,12 @@ fn new_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_layer(s, p, LayerKind::Folder)
|
||||
}
|
||||
|
||||
/// The colour the `n`th layer gets (its outline and timeline bar).
|
||||
pub(crate) fn layer_color(n: usize) -> anicraft_doc::Rgba {
|
||||
const PALETTE: [u32; 7] = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65];
|
||||
anicraft_doc::Rgba::hex(PALETTE.get(n % PALETTE.len()).copied().unwrap_or(0x4fa3ff))
|
||||
}
|
||||
|
||||
fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result<Value> {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
if tl.layers.len() >= 1000 {
|
||||
@@ -672,8 +687,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result<Value> {
|
||||
// Match the timeline length so the new layer spans the existing frames.
|
||||
k.duration = s.frame_count().max(1);
|
||||
}
|
||||
let palette = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65];
|
||||
layer.color = anicraft_doc::Rgba::hex(palette[n % palette.len()]);
|
||||
layer.color = layer_color(n);
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
tl.layers.insert(at, Arc::new(layer));
|
||||
tl.repair_masks();
|
||||
@@ -740,6 +754,14 @@ fn select_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.doc.timeline(s.scene).layer(id).is_none() {
|
||||
return Err(EngineError::State(format!("no layer with id {}", id.0)));
|
||||
}
|
||||
// A click on a layer's name in Animate: the layer becomes active with all of its artwork at
|
||||
// the playhead selected (ADR 0044).
|
||||
if opt_bool(p, "select")? == Some(true) {
|
||||
s.layer = id;
|
||||
let ids: Vec<ElementId> = if s.selectable(id) { s.elements_on(id).iter().map(|e| e.id).collect() } else { Vec::new() };
|
||||
s.selection = crate::Selection::only(id, ids);
|
||||
return Ok(json!({"layer": id.0, "selected": s.selection.id_list()}));
|
||||
}
|
||||
if s.layer != id {
|
||||
s.layer = id;
|
||||
s.selection.clear();
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
None,
|
||||
"{profile: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], id? (default: the selected shapes)}",
|
||||
true,
|
||||
set_profile as crate::RunFn,
|
||||
(|s, p| s.each_layer(false, |s| set_profile(s, p))) as crate::RunFn,
|
||||
),
|
||||
c(
|
||||
"stroke.set_width_point",
|
||||
@@ -41,12 +41,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// Flattening tolerance for finding places on a stroke, in stage units.
|
||||
const FIND_TOL: f32 = 0.2;
|
||||
|
||||
fn id_param(p: &Value) -> Result<Option<ElementId>> {
|
||||
pub(crate) fn id_param(p: &Value) -> Result<Option<ElementId>> {
|
||||
Ok(opt_u64(p, "id")?.map(ElementId))
|
||||
}
|
||||
|
||||
/// The shape element `id` as it shows at the playhead on the active layer.
|
||||
fn visible_shape(s: &Session, id: ElementId) -> Result<std::sync::Arc<Element>> {
|
||||
pub(crate) fn visible_shape(s: &Session, id: ElementId) -> Result<std::sync::Arc<Element>> {
|
||||
let el = s.visible_elements().into_iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?;
|
||||
match &el.kind {
|
||||
ElementKind::Shape(sh) if sh.stroke.is_some() => Ok(el),
|
||||
@@ -56,7 +56,7 @@ fn visible_shape(s: &Session, id: ElementId) -> Result<std::sync::Arc<Element>>
|
||||
}
|
||||
|
||||
/// The editable copy of shape `id` (copy-on-write; keys a tween's frame like any edit).
|
||||
fn shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> {
|
||||
pub(crate) fn shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> {
|
||||
visible_shape(s, id)?;
|
||||
let kf = s.editable_keyframe()?;
|
||||
let el = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?;
|
||||
@@ -90,7 +90,7 @@ fn set_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let profile = opt_profile(p, "profile")?.ok_or_else(|| EngineError::Param("param 'profile' is required".into()))?;
|
||||
let ids: Vec<ElementId> = match id_param(p)? {
|
||||
Some(id) => vec![id],
|
||||
None => s.selection.clone(),
|
||||
None => s.selection.on(s.layer),
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
|
||||
@@ -156,6 +156,27 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
})
|
||||
}
|
||||
"camera.remove" => camera_removal(s, s.doc.timeline(s.scene).camera_layer()?),
|
||||
"bone.remove" => {
|
||||
// The bone's moves in every pose go with it (ADR 0043); one pose loses nothing.
|
||||
let id = anicraft_doc::BoneId(p.get("bone").and_then(Value::as_u64)?);
|
||||
let l = s.doc.timeline(s.scene).layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?;
|
||||
let arm = l.armature.as_deref()?;
|
||||
let n = crate::cmds_bone::poses(l);
|
||||
let below = arm.subtree(id).len().saturating_sub(1);
|
||||
let name = arm.bone(id).map(|b| if b.name.is_empty() { "The bone".to_string() } else { format!("“{}”", b.name) })?;
|
||||
(n > 1).then(|| Confirmation {
|
||||
title: "Remove bone?".into(),
|
||||
message: format!(
|
||||
"{name}{} {} posed over {}; removing takes {} out of every pose. The instances stay where they are now, on a layer of their own. You can undo this.",
|
||||
if below > 0 { format!(" and the {} below it", plural(below, "bone")) } else { String::new() },
|
||||
if below > 0 { "are" } else { "is" },
|
||||
plural(n, "keyframe"),
|
||||
if below > 0 { "them" } else { "it" },
|
||||
),
|
||||
action: "Remove Bone".into(),
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"layer.delete" => {
|
||||
let l = target_layer(s, p)?;
|
||||
if l.kind == anicraft_doc::LayerKind::Camera {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! actually copied. History is bounded by an estimate of that unique memory, not by step count,
|
||||
//! so a thousand small nudges are cheap while one huge import is still evictable.
|
||||
|
||||
use anicraft_doc::{Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Symbol};
|
||||
use anicraft_doc::{Document, Element, ElementKind, Keyframe, Layer, LayerId, Symbol};
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::mem::size_of;
|
||||
use std::sync::Arc;
|
||||
@@ -30,7 +30,7 @@ pub struct Snapshot {
|
||||
pub scene: usize,
|
||||
pub frame: u32,
|
||||
pub layer: LayerId,
|
||||
pub selection: Vec<ElementId>,
|
||||
pub selection: crate::Selection,
|
||||
/// Estimated bytes this snapshot keeps alive that the neighbouring state does not share.
|
||||
pub bytes: usize,
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod cmds_actions;
|
||||
mod cmds_bone;
|
||||
pub mod cmds_brush;
|
||||
mod cmds_camera;
|
||||
mod cmds_draw;
|
||||
@@ -17,6 +18,8 @@ mod cmds_motion;
|
||||
mod cmds_hints;
|
||||
mod cmds_paint;
|
||||
mod cmds_path;
|
||||
pub mod cmds_raw;
|
||||
pub mod cmds_rawsub;
|
||||
mod cmds_recovery;
|
||||
mod cmds_script;
|
||||
pub mod cmds_plugin;
|
||||
@@ -25,12 +28,15 @@ pub mod cmds_sound;
|
||||
pub mod cmds_text;
|
||||
mod cmds_timeline;
|
||||
mod cmds_width;
|
||||
mod cmds_stroke;
|
||||
pub mod confirm;
|
||||
pub mod format;
|
||||
pub mod history;
|
||||
mod merge;
|
||||
pub mod onion;
|
||||
pub mod recovery;
|
||||
pub mod render_service;
|
||||
pub mod selection;
|
||||
pub mod params;
|
||||
pub mod player;
|
||||
pub mod vfs;
|
||||
@@ -101,19 +107,24 @@ pub fn commands() -> Vec<CommandSpec> {
|
||||
v.extend(cmds_recovery::specs());
|
||||
v.extend(cmds_timeline::specs());
|
||||
v.extend(cmds_camera::specs());
|
||||
v.extend(cmds_bone::specs());
|
||||
v.extend(cmds_motion::specs());
|
||||
v.extend(cmds_hints::specs());
|
||||
v.extend(cmds_scene::specs());
|
||||
v.extend(cmds_frames::specs());
|
||||
v.extend(onion::specs());
|
||||
v.extend(cmds_draw::specs());
|
||||
v.extend(merge::specs());
|
||||
v.extend(cmds_modify::specs());
|
||||
v.extend(cmds_path::specs());
|
||||
v.extend(cmds_raw::specs());
|
||||
v.extend(cmds_rawsub::specs());
|
||||
v.extend(cmds_brush::specs());
|
||||
v.extend(cmds_erase::specs());
|
||||
v.extend(cmds_paint::specs());
|
||||
v.extend(cmds_text::specs());
|
||||
v.extend(cmds_width::specs());
|
||||
v.extend(cmds_stroke::specs());
|
||||
v.extend(cmds_plugin::specs());
|
||||
v.extend(cmds_sound::specs());
|
||||
v.extend(cmds_actions::specs());
|
||||
@@ -134,10 +145,32 @@ pub fn find_command(id: &str) -> Option<CommandSpec> {
|
||||
}
|
||||
|
||||
pub use history::{Snapshot, StateId};
|
||||
pub use selection::Selection;
|
||||
|
||||
/// Last addressable frame (0-based); about 70 minutes at 24 fps.
|
||||
pub const MAX_FRAME: u32 = 100_000;
|
||||
|
||||
/// The index of the topmost item of `dl` under `p` (stage space) that `ok` accepts (given its
|
||||
/// index). A bounding-box test rejects almost every item before any curve is flattened;
|
||||
/// masked-away parts cannot be picked.
|
||||
pub(crate) fn pick_index(dl: &DisplayList, p: Vec2, slop: f32, ok: impl Fn(usize, &anicraft_doc::DisplayItem) -> bool) -> Option<usize> {
|
||||
for (i, item) in dl.items.iter().enumerate().rev() {
|
||||
let hw = item.stroke.as_ref().map_or(0.0, |s| s.reach() * item.transform.mean_scale());
|
||||
let bounds = item.path.bounds().transformed(&item.transform).inflate(hw + slop);
|
||||
if !bounds.contains(p) || !ok(i, item) {
|
||||
continue;
|
||||
}
|
||||
if item.clip.is_some_and(|c| !dl.clip_contains(c, p)) {
|
||||
continue;
|
||||
}
|
||||
let inside = item.fill.is_some() && item.path.contains(p, &item.transform, item.fill_rule);
|
||||
if inside || item.path.distance_to_edge(p, &item.transform) <= hw + slop {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Drawing defaults used by the drawing commands when params omit colours.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ToolStyle {
|
||||
@@ -153,15 +186,20 @@ pub struct ToolStyle {
|
||||
pub stroke_profile: anicraft_doc::ProfilePreset,
|
||||
/// A picked width profile that is none of the presets (it wins over `stroke_profile`).
|
||||
pub custom_profile: Option<anicraft_doc::WidthProfile>,
|
||||
/// The caps, joins and dashes new strokes get (ADR 0046).
|
||||
pub line: anicraft_doc::StrokeStyle,
|
||||
/// Object Drawing: new shapes are drawing objects. Off, they merge with the raw shapes they
|
||||
/// touch (ADR 0031). On by default, so a script's draw command makes one element; the editor
|
||||
/// starts with it off, as Animate does.
|
||||
pub object_drawing: bool,
|
||||
/// Snap to Objects (Animate's magnet, ADR 0042): dragged points and selections snap to
|
||||
/// points, lines and fill edges nearby. On by default; off, the `snap` params do nothing.
|
||||
pub snap_objects: bool,
|
||||
}
|
||||
|
||||
impl Default for ToolStyle {
|
||||
fn default() -> Self {
|
||||
ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, object_drawing: true }
|
||||
ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, line: anicraft_doc::StrokeStyle::default(), object_drawing: true, snap_objects: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,6 +217,14 @@ impl ToolStyle {
|
||||
pub fn profile(&self) -> Option<anicraft_doc::WidthProfile> {
|
||||
self.custom_profile.clone().or_else(|| self.stroke_profile.profile())
|
||||
}
|
||||
/// A new stroke of `color` and `width` with the current profile and line style.
|
||||
pub fn new_stroke(&self, color: anicraft_doc::Rgba, width: f32) -> anicraft_doc::Stroke {
|
||||
anicraft_doc::Stroke::new(color, width).with_profile(self.profile()).with_style(self.line.clone())
|
||||
}
|
||||
/// The snapping radius a command asked for (`snap`), or none when Snap to Objects is off.
|
||||
pub fn snap_radius(&self, asked: f32) -> f32 {
|
||||
if self.snap_objects { asked } else { 0.0 }
|
||||
}
|
||||
/// Sets the profile to a preset (dropping a picked custom one).
|
||||
pub fn set_profile(&mut self, p: anicraft_doc::ProfilePreset) {
|
||||
self.stroke_profile = p;
|
||||
@@ -199,8 +245,8 @@ pub struct Session {
|
||||
pub frame: u32,
|
||||
/// Active layer.
|
||||
pub layer: LayerId,
|
||||
/// Selected elements on the active layer.
|
||||
pub selection: Vec<ElementId>,
|
||||
/// Selected elements at the playhead, each with its layer (ADR 0044).
|
||||
pub selection: Selection,
|
||||
/// Bumped on every document change, undo and redo (UI invalidation).
|
||||
pub revision: u64,
|
||||
/// Identity of the current document content (equal ids ⇒ identical content).
|
||||
@@ -227,6 +273,33 @@ pub struct Session {
|
||||
/// A name for the undo step the running command records, set by the command
|
||||
/// (`plugin.run` names its step after the plug-in).
|
||||
pub(crate) step_label: Option<String>,
|
||||
/// A marquee's cut that nothing has used yet (ADR 0041).
|
||||
provisional: Option<Provisional>,
|
||||
/// Set by `raw.select_rect` when it cut: each piece and the shape it was cut from, and the
|
||||
/// pieces inside the marquee.
|
||||
pub(crate) pending_cut: Option<(CutOrigin, Vec<ElementId>)>,
|
||||
/// The open gesture began on a provisional cut: the document with the cut.
|
||||
gesture_cut: Option<Document>,
|
||||
}
|
||||
|
||||
/// Each piece of a marquee's cut, with the shape it was cut from.
|
||||
pub(crate) type CutOrigin = Vec<(ElementId, ElementId)>;
|
||||
|
||||
/// A marquee's cut that nothing has used yet (ADR 0041). In Animate a marquee only selects: the
|
||||
/// drawing is cut where it crosses once the selection is moved or changed. Here the cut happens
|
||||
/// at once (the parts must be elements to be selected) and records no undo step. It is taken
|
||||
/// back as soon as the selection lets go of its pieces with nothing else changed; the first edit
|
||||
/// that uses it records one step from before the cut.
|
||||
struct Provisional {
|
||||
/// Before the cut.
|
||||
before: history::Snapshot,
|
||||
/// The document with the cut, and its state.
|
||||
cut: Document,
|
||||
state: history::StateId,
|
||||
/// Each piece and the shape it was cut from.
|
||||
origin: Vec<(ElementId, ElementId)>,
|
||||
/// The pieces inside the marquee(s): while one of them is selected, the cut is in use.
|
||||
inside: Vec<ElementId>,
|
||||
}
|
||||
|
||||
impl Default for Session {
|
||||
@@ -252,7 +325,7 @@ impl Session {
|
||||
scene: 0,
|
||||
frame: 0,
|
||||
layer,
|
||||
selection: Vec::new(),
|
||||
selection: Selection::default(),
|
||||
revision: 1,
|
||||
state,
|
||||
saved_state: Some(state),
|
||||
@@ -267,6 +340,9 @@ impl Session {
|
||||
motion_edit: None,
|
||||
plugins: anicraft_plugins::Registry::default(),
|
||||
step_label: None,
|
||||
provisional: None,
|
||||
pending_cut: None,
|
||||
gesture_cut: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,16 +380,35 @@ impl Session {
|
||||
/// Starts coalescing: every mutating command until [`Session::end_gesture`] becomes a single
|
||||
/// undo step labelled `label` (used for drags, so a move is one step, not sixty).
|
||||
pub fn begin_gesture(&mut self, label: &str) {
|
||||
if self.gesture.is_none() {
|
||||
self.gesture = Some(self.snapshot(label));
|
||||
if self.gesture.is_some() {
|
||||
return;
|
||||
}
|
||||
// On a marquee's cut, the step (if the gesture makes one) starts from before the cut.
|
||||
let cut = self.live_cut().map(|p| (history::Snapshot { label: label.to_string(), ..p.before.clone() }, p.cut.clone()));
|
||||
match cut {
|
||||
Some((before, doc)) => {
|
||||
self.gesture_cut = Some(doc);
|
||||
self.gesture = Some(before);
|
||||
}
|
||||
None => self.gesture = Some(self.snapshot(label)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the open gesture, recording one undo step if the document changed.
|
||||
pub fn end_gesture(&mut self) {
|
||||
if let Some(before) = self.gesture.take()
|
||||
&& self.doc != before.doc
|
||||
{
|
||||
let cut = self.gesture_cut.take();
|
||||
let Some(before) = self.gesture.take() else { return };
|
||||
if let Some(cut) = &cut {
|
||||
if self.doc == *cut {
|
||||
// Nothing used the marquee's cut: it stays provisional.
|
||||
if let Some(p) = &self.provisional {
|
||||
self.state = p.state;
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.provisional = None;
|
||||
}
|
||||
if self.doc != before.doc {
|
||||
self.history.record(before, &self.doc);
|
||||
}
|
||||
}
|
||||
@@ -349,12 +444,22 @@ impl Session {
|
||||
{
|
||||
return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message)));
|
||||
}
|
||||
self.settle_cut(id, params);
|
||||
if !spec.mutates {
|
||||
return (spec.run)(self, params);
|
||||
let r = (spec.run)(self, params);
|
||||
self.settle_cut(id, params);
|
||||
return r;
|
||||
}
|
||||
let mut before = self.snapshot(spec.label);
|
||||
// An edit on a marquee's cut records its step from before the cut (ADR 0041).
|
||||
let cut = self.live_cut().map(|p| (history::Snapshot { label: spec.label.to_string(), ..p.before.clone() }, p.cut.clone()));
|
||||
let rollback = cut.as_ref().map(|_| self.snapshot(spec.label));
|
||||
let mut before = match &cut {
|
||||
Some((b, _)) => b.clone(),
|
||||
None => self.snapshot(spec.label),
|
||||
};
|
||||
// A command must never observe a display list of the state it is changing.
|
||||
self.dl_cache.replace(None);
|
||||
self.pending_cut = None;
|
||||
self.motion_edit = None;
|
||||
self.step_label = None;
|
||||
let result = (spec.run)(self, params);
|
||||
@@ -368,26 +473,105 @@ impl Session {
|
||||
if let Some(label) = self.step_label.take() {
|
||||
before.label = label;
|
||||
}
|
||||
let pending = self.pending_cut.take();
|
||||
match result {
|
||||
Ok(v) => {
|
||||
// O(changed): unchanged subtrees compare by pointer.
|
||||
if self.doc != before.doc {
|
||||
let changed = match &cut {
|
||||
Some((_, doc)) => self.doc != *doc,
|
||||
// O(changed): unchanged subtrees compare by pointer.
|
||||
None => self.doc != before.doc,
|
||||
};
|
||||
if changed {
|
||||
self.state = history::fresh_state();
|
||||
self.revision += 1;
|
||||
if self.gesture.is_none() {
|
||||
self.history.record(before, &self.doc);
|
||||
match pending.filter(|_| self.gesture.is_none()) {
|
||||
// A marquee's cut: provisional, no step (yet).
|
||||
Some((origin, inside)) => self.begin_cut(before, cut.is_some(), origin, inside),
|
||||
None => {
|
||||
if cut.is_some() {
|
||||
self.provisional = None;
|
||||
}
|
||||
if self.gesture.is_none() && self.doc != before.doc {
|
||||
self.history.record(before, &self.doc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.fix_selection();
|
||||
Ok(v)
|
||||
}
|
||||
Err(e) => {
|
||||
self.restore(before);
|
||||
// Back to the cut, which stays provisional, or to before the command.
|
||||
self.restore(rollback.unwrap_or(before));
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The marquee's cut, while nothing has changed since it.
|
||||
fn live_cut(&self) -> Option<&Provisional> {
|
||||
self.provisional.as_ref().filter(|p| p.state == self.state && self.gesture.is_none())
|
||||
}
|
||||
|
||||
/// Keeps a marquee's cut provisional. `before` is the document before it; `chained` when
|
||||
/// it cut a provisional cut again (Shift), whose pieces then lead back to the shapes the
|
||||
/// first cut took.
|
||||
fn begin_cut(&mut self, before: history::Snapshot, chained: bool, origin: Vec<(ElementId, ElementId)>, inside: Vec<ElementId>) {
|
||||
let (mut origin, mut inside) = (origin, inside);
|
||||
if chained && let Some(p) = self.provisional.take() {
|
||||
inside.extend(p.inside.iter().copied());
|
||||
for o in &mut origin {
|
||||
if let Some(&(_, first)) = p.origin.iter().find(|(piece, _)| *piece == o.1) {
|
||||
o.1 = first;
|
||||
}
|
||||
}
|
||||
let new: Vec<ElementId> = origin.iter().map(|o| o.0).collect();
|
||||
origin.extend(p.origin.into_iter().filter(|(piece, _)| !new.contains(piece)));
|
||||
}
|
||||
// A marquee alone leaves the document as it was saved.
|
||||
if self.saved_state == Some(before.state) {
|
||||
self.saved_state = Some(self.state);
|
||||
}
|
||||
self.provisional = Some(Provisional { before, cut: self.doc.clone(), state: self.state, origin, inside });
|
||||
}
|
||||
|
||||
/// Takes back a provisional cut that the selection has let go of (none of the pieces inside
|
||||
/// the marquee is selected), and before saving, undo, redo or a new marquee.
|
||||
fn settle_cut(&mut self, id: &str, params: &Value) {
|
||||
if self.gesture.is_none() && self.provisional.as_ref().is_some_and(|p| p.state != self.state) {
|
||||
self.provisional = None;
|
||||
}
|
||||
let Some(p) = self.live_cut() else { return };
|
||||
let held = self.selection.ids().any(|s| p.inside.contains(&s));
|
||||
let fresh_marquee = id == "raw.select_rect" && params.get("add").and_then(Value::as_bool) != Some(true);
|
||||
if !held || fresh_marquee || id.starts_with("file.") || id == "edit.undo" || id == "edit.redo" {
|
||||
self.heal_cut();
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts the document back as it was before a provisional cut. Selected pieces become the
|
||||
/// shapes they were cut from.
|
||||
fn heal_cut(&mut self) {
|
||||
let Some(p) = self.provisional.take() else { return };
|
||||
if p.state != self.state || self.gesture.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut sel = Selection::default();
|
||||
for (layer, id) in self.selection.iter() {
|
||||
let id = p.origin.iter().find(|(piece, _)| *piece == id).map_or(id, |o| o.1);
|
||||
sel.insert(layer, id);
|
||||
}
|
||||
if self.saved_state == Some(p.state) {
|
||||
self.saved_state = Some(p.before.state);
|
||||
}
|
||||
self.doc = p.before.doc;
|
||||
self.state = p.before.state;
|
||||
self.selection = sel;
|
||||
self.dl_cache.replace(None);
|
||||
self.revision += 1;
|
||||
self.fix_selection();
|
||||
}
|
||||
|
||||
/// Runs a command inside another one (a plug-in's requests during `plugin.run`): checked
|
||||
/// and atomic like [`Session::execute`], but it records no undo step of its own, so the
|
||||
/// outer command stays one step.
|
||||
@@ -405,6 +589,7 @@ impl Session {
|
||||
self.dl_cache.replace(None);
|
||||
let result = (spec.run)(self, params);
|
||||
self.dl_cache.replace(None);
|
||||
self.pending_cut = None;
|
||||
match result {
|
||||
Ok(v) => {
|
||||
// Later requests must see this change (display list, hit tests): new state.
|
||||
@@ -424,6 +609,10 @@ impl Session {
|
||||
/// Puts the document back where the open gesture started, keeping the gesture open. A
|
||||
/// live preview re-runs from the same start on every change, and Cancel leaves no step.
|
||||
pub fn revert_gesture(&mut self) {
|
||||
if self.gesture_cut.is_some() {
|
||||
// Back to before the marquee's cut: it is gone.
|
||||
self.provisional = None;
|
||||
}
|
||||
let Some(g) = &self.gesture else { return };
|
||||
if g.doc == self.doc && g.selection == self.selection {
|
||||
return;
|
||||
@@ -463,6 +652,7 @@ impl Session {
|
||||
|
||||
pub fn undo(&mut self) -> Result<Value> {
|
||||
self.end_gesture();
|
||||
self.heal_cut();
|
||||
let cur = self.snapshot("");
|
||||
let s = self.history.undo(cur).ok_or_else(|| EngineError::State("nothing to undo".into()))?;
|
||||
let label = s.label.clone();
|
||||
@@ -474,6 +664,7 @@ impl Session {
|
||||
|
||||
pub fn redo(&mut self) -> Result<Value> {
|
||||
self.end_gesture();
|
||||
self.heal_cut();
|
||||
let cur = self.snapshot("");
|
||||
let s = self.history.redo(cur).ok_or_else(|| EngineError::State("nothing to redo".into()))?;
|
||||
let label = s.label.clone();
|
||||
@@ -534,28 +725,10 @@ impl Session {
|
||||
/// Topmost element under `p` (stage space) on a visible, unlocked layer. A bounding-box
|
||||
/// test rejects almost every item before any curve is flattened.
|
||||
pub fn hit_test(&self, p: Vec2, slop: f32) -> Option<(LayerId, ElementId)> {
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
let dl = self.display_list();
|
||||
for item in dl.items.iter().rev() {
|
||||
let hw = item.stroke.as_ref().map_or(0.0, |s| s.reach() * item.transform.mean_scale());
|
||||
let bounds = item.path.bounds().transformed(&item.transform).inflate(hw + slop);
|
||||
if !bounds.contains(p) {
|
||||
continue;
|
||||
}
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
let Some(layer) = tl.layer(item.layer) else { continue };
|
||||
if layer.locked || tl.locked_by_folder(layer.id) {
|
||||
continue;
|
||||
}
|
||||
// Masked-away parts cannot be picked.
|
||||
if item.clip.is_some_and(|c| !dl.clip_contains(c, p)) {
|
||||
continue;
|
||||
}
|
||||
let inside = item.fill.is_some() && item.path.contains(p, &item.transform, item.fill_rule);
|
||||
if inside || item.path.distance_to_edge(p, &item.transform) <= hw + slop {
|
||||
return Some((item.layer, item.element));
|
||||
}
|
||||
}
|
||||
None
|
||||
let i = pick_index(&dl, p, slop, |_, it| tl.layer(it.layer).is_some_and(|layer| !layer.locked && !tl.locked_by_folder(layer.id)))?;
|
||||
dl.items.get(i).map(|it| (it.layer, it.element))
|
||||
}
|
||||
|
||||
/// Stage-space bounds of a top-level element at the playhead.
|
||||
@@ -568,24 +741,6 @@ impl Session {
|
||||
r
|
||||
}
|
||||
|
||||
/// Bounds of the whole selection.
|
||||
pub fn selection_bounds(&self) -> Rect {
|
||||
self.selection.iter().fold(Rect::EMPTY, |r, id| r.union(&self.element_bounds(*id)))
|
||||
}
|
||||
|
||||
/// Drops selected ids that no longer exist on the active layer at the playhead.
|
||||
pub fn fix_selection(&mut self) {
|
||||
self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1));
|
||||
if self.doc.timeline(self.scene).layer(self.layer).is_none() {
|
||||
self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id);
|
||||
}
|
||||
if self.selection.is_empty() {
|
||||
return;
|
||||
}
|
||||
let ids: Vec<ElementId> = self.visible_elements().iter().map(|e| e.id).collect();
|
||||
self.selection.retain(|s| ids.contains(s));
|
||||
}
|
||||
|
||||
pub fn set_frame(&mut self, frame: u32) {
|
||||
self.frame = frame.min(MAX_FRAME);
|
||||
self.fix_selection();
|
||||
@@ -601,20 +756,24 @@ impl Session {
|
||||
/// The keyframe on the active layer that edits at the playhead should change. Creates a
|
||||
/// keyframe when the playhead is inside a tween (auto-key) or past the layer's end.
|
||||
pub(crate) fn editable_keyframe(&mut self) -> Result<&mut Keyframe> {
|
||||
self.editable_keyframe_in(false)
|
||||
self.editable_keyframe_in(KeyEdit::Artwork)
|
||||
}
|
||||
|
||||
/// [`Session::editable_keyframe`]; with `camera`, on the camera layer (which holds only the
|
||||
/// camera: every other edit is refused there, ADR 0027).
|
||||
pub(crate) fn editable_keyframe_in(&mut self, camera: bool) -> Result<&mut Keyframe> {
|
||||
/// [`Session::editable_keyframe`] for `what`: the camera layer holds only the camera (ADR
|
||||
/// 0027) and an armature layer only its posed armature (ADR 0043); every other edit is
|
||||
/// refused there.
|
||||
pub(crate) fn editable_keyframe_in(&mut self, what: KeyEdit) -> Result<&mut Keyframe> {
|
||||
let frame = self.frame;
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
if let Some(l) = tl.layer(self.layer) {
|
||||
if l.kind == LayerKind::Folder {
|
||||
return Err(EngineError::State(format!("'{}' is a folder; pick a layer inside it to draw on", l.name)));
|
||||
}
|
||||
if (l.kind == LayerKind::Camera) != camera {
|
||||
return Err(EngineError::State(if camera { "that is not the camera layer".into() } else { format!("'{}' is the camera layer: it holds the camera, not artwork. Pick another layer to draw on, or move the camera with the Camera tool", l.name) }));
|
||||
if (l.kind == LayerKind::Camera) != (what == KeyEdit::Camera) {
|
||||
return Err(EngineError::State(if what == KeyEdit::Camera { "that is not the camera layer".into() } else { format!("'{}' is the camera layer: it holds the camera, not artwork. Pick another layer to draw on, or move the camera with the Camera tool", l.name) }));
|
||||
}
|
||||
if (l.kind == LayerKind::Armature) != (what == KeyEdit::Pose) {
|
||||
return Err(EngineError::State(if what == KeyEdit::Pose { "that is not an armature layer".into() } else { format!("'{}' is an armature layer: it holds the armature's instances, posed by their bones. Drag a bone (or an instance) to pose it, drag the root instance to move it all, or pick another layer to draw on", l.name) }));
|
||||
}
|
||||
if tl.locked_by_folder(l.id) {
|
||||
return Err(EngineError::State(format!("layer '{}' is in a locked folder", l.name)));
|
||||
@@ -651,7 +810,7 @@ impl Session {
|
||||
|
||||
/// Selected elements in the editable keyframe (copy-on-write: only these are cloned).
|
||||
pub(crate) fn selected_elements_mut(&mut self) -> Result<Vec<&mut Element>> {
|
||||
let sel = self.selection.clone();
|
||||
let sel: std::collections::HashSet<ElementId> = self.selection.on(self.layer).into_iter().collect();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
@@ -683,7 +842,8 @@ impl Session {
|
||||
"scenes": self.doc.scenes.iter().map(|s| json!({"name": s.name, "frames": s.timeline.frame_count()})).collect::<Vec<_>>(),
|
||||
"movie_frames": self.doc.frame_count(),
|
||||
"layer": self.layer.0,
|
||||
"selection": self.selection.iter().map(|e| e.0).collect::<Vec<_>>(),
|
||||
"selection": self.selection.id_list(),
|
||||
"selection_layers": self.selected_layers().iter().map(|l| l.0).collect::<Vec<_>>(),
|
||||
"layers": layers,
|
||||
"library": symbols,
|
||||
"sounds": sounds,
|
||||
@@ -695,6 +855,17 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Session::editable_keyframe_in`] is asked to edit.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum KeyEdit {
|
||||
/// Artwork: any layer but the camera and armature layers.
|
||||
Artwork,
|
||||
/// The camera, on the camera layer.
|
||||
Camera,
|
||||
/// A pose, on an armature layer.
|
||||
Pose,
|
||||
}
|
||||
|
||||
/// Short human label for an element (properties panel, library, CLI).
|
||||
pub fn element_label(doc: &Document, e: &Element) -> String {
|
||||
let kind = match &e.kind {
|
||||
@@ -724,6 +895,8 @@ mod motion_tests;
|
||||
#[cfg(test)]
|
||||
mod motion_path_tests;
|
||||
#[cfg(test)]
|
||||
mod motion_pin_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_tests;
|
||||
#[cfg(test)]
|
||||
mod tests_sound;
|
||||
@@ -736,8 +909,14 @@ mod tests_script;
|
||||
#[cfg(test)]
|
||||
mod tests_camera;
|
||||
#[cfg(test)]
|
||||
mod tests_bone;
|
||||
#[cfg(test)]
|
||||
mod merge_tests;
|
||||
#[cfg(test)]
|
||||
mod raw_tests;
|
||||
#[cfg(test)]
|
||||
mod rawsub_tests;
|
||||
#[cfg(test)]
|
||||
mod brush_tests;
|
||||
#[cfg(test)]
|
||||
mod web_tests;
|
||||
@@ -745,3 +924,5 @@ mod web_tests;
|
||||
mod erase_tests;
|
||||
#[cfg(test)]
|
||||
mod eyedropper_tests;
|
||||
#[cfg(test)]
|
||||
mod selection_tests;
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Paint, Shape, Stroke};
|
||||
use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Paint, Shape, Stroke, Timeline};
|
||||
use anicraft_geom::planar::{self, Item, SNAP};
|
||||
use anicraft_geom::{Affine, Path, PathCmd, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
@@ -13,23 +13,26 @@ use std::sync::Arc;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("draw.drop", "Drop", "", None, "{} the selected raw shapes cut and join the raw shapes they touch (after a move)", true, drop as crate::RunFn),
|
||||
c("draw.drop", "Drop", "", None, "{} the selected raw shapes cut and join the raw shapes they touch (after a move), on each layer", true, (|s, p| s.each_layer(true, |s| drop(s, p))) as crate::RunFn),
|
||||
c("element.select_connected", "Select Connected", "", None, "{x, y, add?, slop?} a raw stroke and the strokes joined to it, or a raw fill and the strokes on and in it", false, select_connected),
|
||||
]
|
||||
}
|
||||
|
||||
/// A raw shape the merge can take: a solid fill (or none) and a stroke of one width (or none).
|
||||
/// A raw shape the merge can take: any fill (solid, gradient or bitmap: the paint is carried
|
||||
/// into each piece, ADR 0042) or none, and a stroke of one width or none. A width profile runs
|
||||
/// along the whole stroke, so cutting it would need its length carried through the merge; those
|
||||
/// strokes stay whole, as objects, for now.
|
||||
pub(crate) fn mergeable(e: &Element) -> Option<&Shape> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(s) if s.merge && matches!(s.fill, None | Some(Paint::Solid(_))) && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s),
|
||||
ElementKind::Shape(s) if s.merge && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a new shape with this style can join the drawing (other paints and width profiles are
|
||||
/// Whether a new shape with this style can join the drawing (strokes with a width profile are
|
||||
/// drawn as objects for now).
|
||||
pub(crate) fn can_merge(fill: Option<&Paint>, stroke: Option<&Stroke>) -> bool {
|
||||
matches!(fill, None | Some(Paint::Solid(_))) && stroke.is_none_or(|st| st.profile.is_none())
|
||||
pub(crate) fn can_merge(stroke: Option<&Stroke>) -> bool {
|
||||
stroke.is_none_or(|st| st.profile.is_none())
|
||||
}
|
||||
|
||||
pub(crate) fn reach(s: &Shape, m: &Affine) -> Rect {
|
||||
@@ -113,6 +116,27 @@ const ERASED: u32 = u32::MAX;
|
||||
/// and returns them with the ids of the pieces whose topmost source part was marked. `None` when
|
||||
/// there is too much to merge at once.
|
||||
pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec<Arc<Element>>, Vec<ElementId>)> {
|
||||
remerge_with(s, parts, None).map(|r| (r.out, r.picked))
|
||||
}
|
||||
|
||||
/// What [`remerge_with`] makes.
|
||||
pub(crate) struct Remerged {
|
||||
pub out: Vec<Arc<Element>>,
|
||||
/// Pieces whose topmost source part was marked.
|
||||
pub picked: Vec<ElementId>,
|
||||
/// Pieces inside the cutter (ADR 0041).
|
||||
pub inside: Vec<ElementId>,
|
||||
/// Each piece and the index in `parts` of its topmost source.
|
||||
pub from: Vec<(ElementId, usize)>,
|
||||
}
|
||||
|
||||
/// [`remerge`], cutting along `cutter` too when there is one ([`planar::merge_cut`]).
|
||||
pub(crate) fn remerge_with(s: &mut Session, parts: &[Part], cutter: Option<&Path>) -> Option<Remerged> {
|
||||
remerge_doc(&mut s.doc, parts, cutter)
|
||||
}
|
||||
|
||||
/// [`remerge_with`] for any document (new pieces take ids from `doc`).
|
||||
fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Option<Remerged> {
|
||||
// Style tables: equal entries are one style to the merge.
|
||||
let mut fills: Vec<(Paint, ColorEffect)> = Vec::new();
|
||||
let mut strokes: Vec<(Stroke, ColorEffect)> = Vec::new();
|
||||
@@ -124,8 +148,10 @@ pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec<Arc<Elemen
|
||||
Part::Shape(e, mark) => {
|
||||
let Some(sh) = mergeable(e) else { continue };
|
||||
paths.push(sh.path.transformed(&e.transform));
|
||||
let fill = sh.fill.clone().map(|f| index_of(&mut fills, (f, e.color)));
|
||||
let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (Stroke { width: st.width * e.transform.mean_scale(), ..st }, e.color)));
|
||||
// Gradients and bitmaps are placed in keyframe space, so every piece shows its
|
||||
// part of the paint where it was.
|
||||
let fill = sh.fill.as_ref().map(|f| fill_index(&mut fills, (f.transformed(&e.transform), e.color)));
|
||||
let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (st.scaled(e.transform.mean_scale()), e.color)));
|
||||
styles.push((fill, stroke, sh.fill_rule));
|
||||
marked.push(*mark);
|
||||
}
|
||||
@@ -137,9 +163,14 @@ pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec<Arc<Elemen
|
||||
}
|
||||
}
|
||||
let items: Vec<Item> = paths.iter().zip(&styles).map(|(path, &(fill, stroke, fill_rule))| Item { path, fill, fill_rule, stroke }).collect();
|
||||
let merged = planar::merge(&items)?;
|
||||
let merged = match cutter {
|
||||
Some(c) => planar::merge_cut(&items, c)?,
|
||||
None => planar::merge(&items)?,
|
||||
};
|
||||
// Item numbers back to part numbers (parts that are not raw shapes made no item).
|
||||
let part_of: Vec<usize> = parts.iter().enumerate().filter(|(_, p)| !matches!(p, Part::Shape(e, _) if mergeable(e).is_none())).map(|(i, _)| i).collect();
|
||||
let mut out: Vec<Arc<Element>> = Vec::with_capacity(merged.fills.len() + merged.strokes.len());
|
||||
let mut picked = Vec::new();
|
||||
let (mut picked, mut inside, mut from) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for (piece, is_fill) in merged.fills.iter().map(|p| (p, true)).chain(merged.strokes.iter().map(|p| (p, false))) {
|
||||
let (fill, stroke, color) = if is_fill {
|
||||
// Erased regions (and anything without a style) are left out.
|
||||
@@ -151,19 +182,25 @@ pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec<Arc<Elemen
|
||||
};
|
||||
// Local origin at the centre of the piece, as the drawing tools place shapes.
|
||||
let c = piece.path.bounds().center();
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let id = ElementId(doc.alloc_id());
|
||||
if marked.get(piece.item).copied().unwrap_or(false) {
|
||||
picked.push(id);
|
||||
}
|
||||
if piece.inside {
|
||||
inside.push(id);
|
||||
}
|
||||
if let Some(&part) = part_of.get(piece.item) {
|
||||
from.push((id, part));
|
||||
}
|
||||
out.push(Arc::new(Element {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: Affine::translate(c.x, c.y),
|
||||
color,
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill, stroke, fill_rule: Default::default(), merge: true }),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill: fill.map(|f| f.transformed(&Affine::translate(-c.x, -c.y))), stroke, fill_rule: Default::default(), merge: true }),
|
||||
}));
|
||||
}
|
||||
Some((out, picked))
|
||||
Some(Remerged { out, picked, inside, from })
|
||||
}
|
||||
|
||||
/// Replaces the keyframe's elements at `taken` (ascending indices) with `out`, placed where the
|
||||
@@ -195,6 +232,33 @@ fn add_whole(kf: &mut anicraft_doc::Keyframe, els: Vec<Element>, order: Order) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill table's entry for `v`: paints that differ only by rounding (a gradient carried into a
|
||||
/// piece and back) are one style, so pieces of one fill join again.
|
||||
fn fill_index(table: &mut Vec<(Paint, ColorEffect)>, v: (Paint, ColorEffect)) -> u32 {
|
||||
match table.iter().position(|x| x.1 == v.1 && same_paint(&x.0, &v.0)) {
|
||||
Some(i) => i as u32,
|
||||
None => {
|
||||
table.push(v);
|
||||
(table.len() - 1) as u32
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two paints look the same (positions within a thousandth of a unit).
|
||||
pub(crate) fn same_paint(a: &Paint, b: &Paint) -> bool {
|
||||
const EPS: f32 = 1e-3;
|
||||
let near = |p: Vec2, q: Vec2| p.distance(q) <= EPS;
|
||||
match (a, b) {
|
||||
(Paint::Solid(x), Paint::Solid(y)) => x == y,
|
||||
(Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => near(*s0, *s1) && near(*e0, *e1) && a == b,
|
||||
(Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => near(*c0, *c1) && (r0 - r1).abs() <= EPS && a == b,
|
||||
(Paint::Bitmap { bitmap: b0, repeat: r0, matrix: m0 }, Paint::Bitmap { bitmap: b1, repeat: r1, matrix: m1 }) => {
|
||||
b0 == b1 && r0 == r1 && m0.m.iter().zip(m1.m).all(|(x, y)| (x - y).abs() <= EPS * x.abs().max(y.abs()).max(1.0))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn index_of<T: PartialEq>(table: &mut Vec<T>, v: T) -> u32 {
|
||||
match table.iter().position(|x| *x == v) {
|
||||
Some(i) => i as u32,
|
||||
@@ -208,7 +272,7 @@ fn index_of<T: PartialEq>(table: &mut Vec<T>, v: T) -> u32 {
|
||||
/// `draw.drop`: the selected raw shapes go back into the drawing, on top (Animate merges a moved
|
||||
/// shape when it is let go).
|
||||
fn drop(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
let sel = s.selection.on(s.layer);
|
||||
let kf = s.editable_keyframe()?;
|
||||
let mut moving = Vec::new();
|
||||
kf.elements.retain(|e| {
|
||||
@@ -224,8 +288,128 @@ fn drop(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
let mut keep: Vec<ElementId> = sel.into_iter().filter(|id| !moving.iter().any(|e| e.id == *id)).collect();
|
||||
keep.extend(merge_in(s, moving)?);
|
||||
s.selection = keep;
|
||||
Ok(json!({"dropped": n, "selected": s.selection.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
s.select_only(keep);
|
||||
Ok(json!({"dropped": n, "selected": s.selection.id_list()}))
|
||||
}
|
||||
|
||||
// ----- the Paint Bucket and imported drawings (ADR 0042) ---------------------------------------
|
||||
|
||||
/// The probe's fill style: what is left of it after the merge is empty area.
|
||||
const PROBE: u32 = u32::MAX - 1;
|
||||
|
||||
/// The empty area around `at` that the raw strokes and fills of `els` close off, as Animate's
|
||||
/// Paint Bucket fills it: exactly up to the lines and fill edges, holes and all. `None` when the
|
||||
/// raw shapes leave it open (it reaches past them), when `at` is on a fill, or when there is too
|
||||
/// much to merge at once.
|
||||
///
|
||||
/// A fill under everything (the probe) is merged with the raw shapes: what remains of it are the
|
||||
/// empty areas, divided by every line and fill edge, and the one under `at` is the answer unless
|
||||
/// it reaches the probe's border. The probe starts as a small window around `at`, with only the
|
||||
/// shapes that reach into it, and grows while the area reaches its border, so a fill costs what
|
||||
/// is near it rather than the whole drawing (shapes wholly outside a window cannot touch an area
|
||||
/// inside it).
|
||||
pub(crate) fn enclosed_area(els: &[Arc<Element>], at: Vec2) -> Option<Path> {
|
||||
let raw: Vec<(&Element, &Shape, Rect)> = els.iter().filter_map(|e| mergeable(e).map(|sh| (e.as_ref(), sh, reach(sh, &e.transform)))).collect();
|
||||
let area = raw.iter().fold(Rect::EMPTY, |r, (_, _, b)| r.union(b));
|
||||
if area.is_empty() || !area.contains(at) {
|
||||
return None;
|
||||
}
|
||||
let all = area.inflate(8.0);
|
||||
let mut half = 64.0f32;
|
||||
loop {
|
||||
let window = Rect::new(at.x - half, at.y - half, at.x + half, at.y + half);
|
||||
let last = window.min.x <= all.min.x && window.min.y <= all.min.y && window.max.x >= all.max.x && window.max.y >= all.max.y;
|
||||
let outer = if last { all } else { window };
|
||||
let near: Vec<&(&Element, &Shape, Rect)> = raw.iter().filter(|(_, _, b)| !b.intersect(&outer).is_empty()).collect();
|
||||
match probe(&near, &outer, at)? {
|
||||
Some(path) => return Some(path),
|
||||
None if last => return None,
|
||||
// It reaches the window's border: look wider.
|
||||
None => half *= 4.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One probe merge over `outer`: `Some(Some(area))` when the empty area at `at` is closed off
|
||||
/// inside it, `Some(None)` when it reaches the border, `None` when `at` is not in an empty area
|
||||
/// or the merge declines.
|
||||
fn probe(raw: &[&(&Element, &Shape, Rect)], outer: &Rect, at: Vec2) -> Option<Option<Path>> {
|
||||
let rect = Path::rect(outer.min.x, outer.min.y, outer.width(), outer.height());
|
||||
let paths: Vec<Path> = raw.iter().map(|(e, sh, _)| sh.path.transformed(&e.transform)).collect();
|
||||
let mut items = vec![Item { path: &rect, fill: Some(PROBE), fill_rule: anicraft_geom::FillRule::NonZero, stroke: None }];
|
||||
for (i, ((_, sh, _), path)) in raw.iter().map(|x| **x).zip(&paths).enumerate() {
|
||||
let n = u32::try_from(i).ok()?;
|
||||
items.push(Item { path, fill: sh.fill.as_ref().map(|_| n), fill_rule: sh.fill_rule, stroke: sh.stroke.as_ref().map(|_| n) });
|
||||
}
|
||||
let merged = planar::merge(&items)?;
|
||||
let piece = merged.fills.into_iter().find(|p| p.style == PROBE && p.path.contains(at, &Affine::IDENTITY, anicraft_geom::FillRule::default()))?;
|
||||
let b = piece.path.bounds();
|
||||
let open = b.min.x <= outer.min.x + 1.0 || b.min.y <= outer.min.y + 1.0 || b.max.x >= outer.max.x - 1.0 || b.max.y >= outer.max.y - 1.0;
|
||||
Some((!open).then_some(piece.path))
|
||||
}
|
||||
|
||||
/// Merges every keyframe's raw shapes in `doc` into one merged drawing each (scenes and
|
||||
/// symbols): what an imported Animate file's raw shapes need, as their styles arrive one shape
|
||||
/// per style. Keyframes with too much to merge at once keep their shapes as they are. Returns
|
||||
/// how many keyframes changed.
|
||||
pub(crate) fn merge_document(doc: &mut Document) -> usize {
|
||||
let mut n = 0;
|
||||
let mut scenes = doc.scenes.clone();
|
||||
for sc in scenes.iter_mut() {
|
||||
let mut tl = sc.timeline.clone();
|
||||
let k = merge_timeline(doc, &mut tl);
|
||||
if k > 0 {
|
||||
Arc::make_mut(sc).timeline = tl;
|
||||
n += k;
|
||||
}
|
||||
}
|
||||
let mut library = doc.library.clone();
|
||||
for sym in library.iter_mut() {
|
||||
let mut tl = sym.timeline.clone();
|
||||
let k = merge_timeline(doc, &mut tl);
|
||||
if k > 0 {
|
||||
Arc::make_mut(sym).timeline = tl;
|
||||
n += k;
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
doc.scenes = scenes;
|
||||
doc.library = library;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn merge_timeline(doc: &mut Document, tl: &mut Timeline) -> usize {
|
||||
let mut n = 0;
|
||||
for layer in tl.layers.iter_mut() {
|
||||
if !layer.keyframes.iter().any(|k| k.elements.iter().any(|e| mergeable(e).is_some())) {
|
||||
continue;
|
||||
}
|
||||
let layer = Arc::make_mut(layer);
|
||||
// A tween pairs its keyframes' shapes in order, so the keyframes it joins keep theirs.
|
||||
let shape_tween = |k: &anicraft_doc::Keyframe| k.tween.is_some() || k.motion.is_some();
|
||||
let morphing: Vec<bool> = (0..layer.keyframes.len()).map(|i| layer.keyframes.get(i).is_some_and(|k| shape_tween(k)) || i.checked_sub(1).and_then(|j| layer.keyframes.get(j)).is_some_and(|k| shape_tween(k))).collect();
|
||||
for (kf, morph) in layer.keyframes.iter_mut().zip(morphing) {
|
||||
let idx: Vec<usize> = kf.elements.iter().enumerate().filter(|(_, e)| mergeable(e).is_some()).map(|(i, _)| i).collect();
|
||||
if idx.is_empty() || morph {
|
||||
continue;
|
||||
}
|
||||
let kf = Arc::make_mut(kf);
|
||||
let existing = kf.elements.clone();
|
||||
let parts: Vec<Part> = idx.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), false)).collect();
|
||||
let Some(rm) = remerge_doc(doc, &parts, None) else { continue };
|
||||
let at = idx.first().copied().unwrap_or(0);
|
||||
for &i in idx.iter().rev() {
|
||||
if i < kf.elements.len() {
|
||||
kf.elements.remove(i);
|
||||
}
|
||||
}
|
||||
let at = at.min(kf.elements.len());
|
||||
kf.elements.splice(at..at, rm.out);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The ends of every open subpath (where raw strokes join), in keyframe space.
|
||||
@@ -305,10 +489,6 @@ fn select_connected(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
for id in picked {
|
||||
if !s.selection.contains(&id) {
|
||||
s.selection.push(id);
|
||||
}
|
||||
}
|
||||
Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
s.selection.extend_on(s.layer, picked);
|
||||
Ok(json!({"selected": s.selection.id_list()}))
|
||||
}
|
||||
@@ -125,3 +125,19 @@ fn double_click_selects_connected_strokes_or_a_fill_with_its_outline() {
|
||||
let r = run(&mut s, "element.select_connected", json!({"x": 350, "y": 0}));
|
||||
assert_eq!(r["selected"].as_array().map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashed_raw_strokes_keep_their_style_when_cut() {
|
||||
let mut s = blank();
|
||||
// A dashed, butt-capped, mitred square outline, then a solid line across it.
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000", "stroke_width": 2, "cap": "none", "join": "miter", "dash": [6, 3]}));
|
||||
run(&mut s, "draw.line", json!({"x0": -20, "y0": 50, "x1": 120, "y1": 50, "stroke": "#000000", "stroke_width": 2}));
|
||||
let strokes: Vec<anicraft_doc::Stroke> = shapes(&s).into_iter().filter_map(|x| x.stroke).collect();
|
||||
let dashed = strokes.iter().filter(|st| st.style.dash == anicraft_doc::Dash::dashed(6.0, 3.0)).count();
|
||||
assert!(dashed >= 5, "the cut sides are pieces, all still dashed: {dashed} of {}", strokes.len());
|
||||
assert!(strokes.iter().filter(|st| st.style.dash.is_some()).all(|st| st.style.cap == anicraft_doc::Cap::Butt && st.style.join == anicraft_doc::Join::Miter));
|
||||
assert!(strokes.iter().any(|st| st.style.is_default()), "the solid line stays solid, a style of its own");
|
||||
// Saved and loaded, the pieces keep it.
|
||||
let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap_or_default()).unwrap_or_default();
|
||||
assert_eq!(back, s.doc);
|
||||
}
|
||||
@@ -154,13 +154,14 @@ fn moving_the_object_on_a_path_reshapes_the_path() {
|
||||
s.set_frame(23);
|
||||
run(&mut s, "element.translate", json!({"dx": 10, "dy": 0}));
|
||||
assert!(pos(&mut s, 23).distance(Vec2::new(115.0, 5.0)) < 1e-3);
|
||||
// In between: the path bends through where the object was put; no key is added.
|
||||
let before = keys(&s);
|
||||
// In between: an anchor where the object was put, pinned to that frame (ADR 0049; ADR 0030
|
||||
// bent the path instead and added no key).
|
||||
let want = pos(&mut s, 9) + Vec2::new(0.0, 40.0);
|
||||
s.set_frame(9);
|
||||
run(&mut s, "element.translate", json!({"dx": 0, "dy": 40}));
|
||||
assert!(pos(&mut s, 9).distance(want) < 0.01, "{:?} vs {want:?}", pos(&mut s, 9));
|
||||
assert_eq!(keys(&s), before, "the timing keeps its keys");
|
||||
assert!(pos(&mut s, 9).distance(want) < 1e-3, "{:?} vs {want:?}", pos(&mut s, 9));
|
||||
assert_eq!(keys(&s), Some(vec![0, 9, 23]), "a position key on the pinned frame");
|
||||
assert_eq!(motion(&s).pins, vec![anicraft_doc::Pin { frame: 9, anchor: 1 }]);
|
||||
assert!(pos(&mut s, 0).distance(Vec2::new(0.0, 25.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(115.0, 5.0)) < 1e-3, "the ends stay");
|
||||
// A drag on the stage is a gesture: one undo step however many moves.
|
||||
let steps = s.history_len();
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Motion path anchors pinned to frames (ADR 0049) through the command registry: auto-key
|
||||
//! pinning where the object is put, `motion.pin_point` / `motion.unpin_point`, the X/Y keys of a
|
||||
//! pinned frame as its anchor's place, point edits keeping pins on their anchors, F6, undo and
|
||||
//! the file round trip.
|
||||
|
||||
use super::*;
|
||||
use anicraft_doc::{Pin, Property};
|
||||
use anicraft_geom::Vec2;
|
||||
use anicraft_geom::edit::ANCHOR;
|
||||
use serde_json::json;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn fails(s: &mut Session, id: &str, p: Value) -> String {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => panic!("{id} {p} should fail, gave {v}"),
|
||||
Err(e) => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 10 × 10 square centred on (5, 5) with a motion tween over frames 0..24 travelling the hump
|
||||
/// from (5, 5) up and over to (105, 5), reached on frame 23.
|
||||
fn on_hump() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
run(&mut s, "timeline.create_motion_tween", json!({}));
|
||||
s.set_frame(23);
|
||||
run(&mut s, "element.translate", json!({"dx": 100, "dy": 0}));
|
||||
s.set_frame(0);
|
||||
run(&mut s, "motion.set_path", json!({"d": "M5 5 C38 -60 72 -60 105 5"}));
|
||||
s
|
||||
}
|
||||
|
||||
fn pos(s: &mut Session, frame: u32) -> Vec2 {
|
||||
s.set_frame(frame);
|
||||
s.visible_elements().first().map(|e| e.transform.translation()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn motion(s: &Session) -> &anicraft_doc::MotionTween {
|
||||
s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.as_ref()).expect("motion tween")
|
||||
}
|
||||
|
||||
fn anchor(s: &Session, i: usize) -> Vec2 {
|
||||
motion(s).path.as_ref().and_then(|p| p.point(i, ANCHOR)).expect("anchor")
|
||||
}
|
||||
|
||||
fn key_frames(s: &Session, p: Property) -> Vec<u32> {
|
||||
motion(s).track(p).map(|t| t.keys.iter().map(|k| k.frame).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_object_at_a_middle_frame_pins_an_anchor_there() {
|
||||
let mut s = on_hump();
|
||||
let was = pos(&mut s, 9);
|
||||
// A drag on the stage: one undo step however many moves, one pin.
|
||||
let steps = s.history_len();
|
||||
s.set_frame(9);
|
||||
s.begin_gesture("Move");
|
||||
for _ in 0..4 {
|
||||
run(&mut s, "element.translate", json!({"dx": 5, "dy": 10}));
|
||||
}
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
let want = was + Vec2::new(20.0, 40.0);
|
||||
assert!(pos(&mut s, 9).distance(want) < 1e-3, "{:?} vs {want:?}", pos(&mut s, 9));
|
||||
assert!(anchor(&s, 1).distance(want) < 1e-3, "the new anchor is where the object was put");
|
||||
assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }]);
|
||||
assert!(pos(&mut s, 0).distance(Vec2::new(5.0, 5.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 5.0)) < 1e-3, "the ends stay");
|
||||
// motion.info reports every anchor tied to a frame, ends included.
|
||||
let info = run(&mut s, "motion.info", json!({}));
|
||||
let pins: Vec<(u64, u64, bool)> = info["pins"].as_array().unwrap().iter().map(|p| (p["anchor"].as_u64().unwrap(), p["frame"].as_u64().unwrap(), p["end"].as_bool().unwrap())).collect();
|
||||
assert_eq!(pins, vec![(0, 0, true), (1, 9, false), (2, 23, true)]);
|
||||
// A later frame pins a later anchor; the first pin holds.
|
||||
s.set_frame(16);
|
||||
run(&mut s, "element.translate", json!({"dx": 0, "dy": -30}));
|
||||
assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }, Pin { frame: 16, anchor: 2 }]);
|
||||
assert!(pos(&mut s, 9).distance(want) < 1e-3);
|
||||
assert!(pos(&mut s, 16).distance(anchor(&s, 2)) < 1e-3);
|
||||
// Undo takes the pin back with its anchor and keys.
|
||||
s.undo().expect("undo");
|
||||
assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }]);
|
||||
assert_eq!(key_frames(&s, Property::X), vec![0, 9, 23]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_after_the_last_position_key_carries_the_path_on() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
run(&mut s, "timeline.create_motion_tween", json!({}));
|
||||
s.set_frame(12);
|
||||
run(&mut s, "element.translate", json!({"dx": 60, "dy": 0}));
|
||||
run(&mut s, "motion.set_path", json!({"d": "M5 5 C25 -30 45 -30 65 5"}));
|
||||
let before: Vec<Vec2> = (0..=12).map(|f| pos(&mut s, f)).collect();
|
||||
s.set_frame(20);
|
||||
run(&mut s, "element.translate", json!({"dx": 40, "dy": 40}));
|
||||
assert!(pos(&mut s, 20).distance(Vec2::new(105.0, 45.0)) < 1e-3);
|
||||
assert_eq!(motion(&s).position_range(), Some((0, 20)));
|
||||
assert_eq!(motion(&s).pins, vec![Pin { frame: 12, anchor: 1 }], "the old end stays pinned to its frame");
|
||||
for (f, b) in before.iter().enumerate() {
|
||||
assert!(pos(&mut s, f as u32).distance(*b) < 1e-2, "frame {f} as it was");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pin_and_unpin_an_anchor_by_command() {
|
||||
let mut s = on_hump();
|
||||
let v = run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.5}));
|
||||
assert_eq!(v["anchor"], 1);
|
||||
let unpinned = motion(&s).clone();
|
||||
let off = pos(&mut s, 6);
|
||||
assert!(off.distance(anchor(&s, 1)) > 5.0, "an anchor alone is reached when the timing says");
|
||||
let steps = s.history_len();
|
||||
let v = run(&mut s, "motion.pin_point", json!({"anchor": 1, "frame": 6}));
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
assert_eq!((v["anchor"].as_u64(), v["frame"].as_u64()), (Some(1), Some(6)));
|
||||
assert_eq!(v["pins"].as_array().map(Vec::len), Some(3));
|
||||
assert!(pos(&mut s, 6).distance(anchor(&s, 1)) < 1e-3, "passed exactly on its frame");
|
||||
assert_eq!(key_frames(&s, Property::Y), vec![0, 6, 23]);
|
||||
// What can't be pinned is refused with the reason.
|
||||
assert!(fails(&mut s, "motion.pin_point", json!({"anchor": 0, "frame": 6})).contains("always pinned"));
|
||||
assert!(fails(&mut s, "motion.pin_point", json!({"anchor": 7, "frame": 6})).contains("no such anchor"));
|
||||
assert!(fails(&mut s, "motion.unpin_point", json!({"anchor": 2})).contains("always pinned"));
|
||||
assert!(fails(&mut s, "motion.unpin_point", json!({"frame": 3})).contains("no anchor is pinned to frame 4"));
|
||||
// Unpinning (by anchor or by frame) gives the tween back as it was.
|
||||
run(&mut s, "motion.unpin_point", json!({"anchor": 1}));
|
||||
assert_eq!(*motion(&s), unpinned);
|
||||
assert!(pos(&mut s, 6).distance(off) < 1e-3, "ADR 0038's timing again");
|
||||
run(&mut s, "motion.pin_point", json!({"anchor": 1, "frame": 6}));
|
||||
run(&mut s, "motion.unpin_point", json!({"frame": 6}));
|
||||
assert_eq!(*motion(&s), unpinned);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pin_point_without_an_anchor_pins_where_the_object_is() {
|
||||
let mut s = on_hump();
|
||||
let was = pos(&mut s, 10);
|
||||
let v = run(&mut s, "motion.pin_point", json!({"frame": 10}));
|
||||
assert_eq!(v["anchor"], 1);
|
||||
assert!(pos(&mut s, 10).distance(was) < 0.01, "nothing moves on that frame");
|
||||
assert!(anchor(&s, 1).distance(was) < 0.01);
|
||||
// Outside the motion, or on an end: refused.
|
||||
assert!(fails(&mut s, "motion.pin_point", json!({"frame": 0})).contains("outside the motion"));
|
||||
// A straight motion's middle keys are pinned as soon as its path is the tween's own.
|
||||
let mut t = Session::default();
|
||||
run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
run(&mut t, "timeline.create_motion_tween", json!({}));
|
||||
t.set_frame(10);
|
||||
run(&mut t, "element.translate", json!({"dx": 100, "dy": 0}));
|
||||
t.set_frame(20);
|
||||
run(&mut t, "element.translate", json!({"dx": 0, "dy": 100}));
|
||||
let info = run(&mut t, "motion.info", json!({}));
|
||||
assert_eq!(info["pins"].as_array().map(Vec::len), Some(3), "shown pinned while straight");
|
||||
run(&mut t, "motion.pin_point", json!({"frame": 15}));
|
||||
assert_eq!(motion(&t).pins, vec![Pin { frame: 10, anchor: 1 }, Pin { frame: 15, anchor: 2 }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinned_frames_x_and_y_keys_are_its_anchors_place() {
|
||||
let mut s = on_hump();
|
||||
run(&mut s, "motion.pin_point", json!({"frame": 8}));
|
||||
let a = anchor(&s, 1);
|
||||
// The Motion Editor sets X on the pinned frame: the anchor moves, and the object with it.
|
||||
let v = run(&mut s, "motion.set_key", json!({"property": "x", "frame": 8, "value": a.x + 12.0}));
|
||||
assert_eq!(v["anchor"], 1);
|
||||
assert!(anchor(&s, 1).distance(a + Vec2::new(12.0, 0.0)) < 1e-3);
|
||||
assert!(pos(&mut s, 8).distance(a + Vec2::new(12.0, 0.0)) < 1e-3);
|
||||
// And the ends: X on the last frame moves the path's end.
|
||||
run(&mut s, "motion.set_key", json!({"property": "y", "frame": 23, "value": 25.0}));
|
||||
assert!(anchor(&s, 2).distance(Vec2::new(105.0, 25.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 25.0)) < 1e-3);
|
||||
// Removing the pinned frame's X key lets the pin go, with its Y key.
|
||||
let v = run(&mut s, "motion.remove_key", json!({"property": "x", "frame": 8}));
|
||||
assert_eq!(v["unpinned"], 1);
|
||||
assert_eq!(v["removed"], json!(["x", "y"]));
|
||||
assert!(motion(&s).pins.is_empty() && !key_frames(&s, Property::Y).contains(&8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_edits_keep_pins_on_their_anchors() {
|
||||
let mut s = on_hump();
|
||||
run(&mut s, "motion.pin_point", json!({"frame": 14}));
|
||||
let pinned = anchor(&s, 1);
|
||||
// A point added before the pinned anchor: the pin follows it to index 2.
|
||||
run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.5}));
|
||||
assert_eq!(motion(&s).pins, vec![Pin { frame: 14, anchor: 2 }]);
|
||||
assert!(pos(&mut s, 14).distance(pinned) < 1e-3);
|
||||
// Deleting the point before it keeps the pin; deleting the pinned point lets it go.
|
||||
let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]}));
|
||||
assert_eq!(v["unpinned"], 0);
|
||||
assert_eq!(motion(&s).pins, vec![Pin { frame: 14, anchor: 1 }]);
|
||||
assert!(pos(&mut s, 14).distance(pinned) < 1e-3);
|
||||
let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]}));
|
||||
assert_eq!(v["unpinned"], 1);
|
||||
assert!(motion(&s).pins.is_empty() && key_frames(&s, Property::X) == vec![0, 23], "its keys went with it");
|
||||
// Straighten forgets the pins; their keys stay as the straight path's corners.
|
||||
run(&mut s, "motion.pin_point", json!({"frame": 14}));
|
||||
run(&mut s, "motion.clear_path", json!({}));
|
||||
assert!(motion(&s).pins.is_empty() && key_frames(&s, Property::X).contains(&14));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_keyframe_inside_a_path_tween_pins_the_path_there() {
|
||||
let mut s = on_hump();
|
||||
let was = pos(&mut s, 11);
|
||||
s.set_frame(11);
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
assert_eq!(motion(&s).pins, vec![Pin { frame: 11, anchor: 1 }]);
|
||||
assert!(pos(&mut s, 11).distance(was) < 0.01, "{:?} vs {was:?}", pos(&mut s, 11));
|
||||
assert!(key_frames(&s, Property::Rotation).contains(&11), "every other property keyed too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pins_round_trip_through_the_file_format() {
|
||||
let mut s = on_hump();
|
||||
run(&mut s, "motion.pin_point", json!({"frame": 7}));
|
||||
let text = format::to_json(&s.doc).expect("save");
|
||||
assert!(text.contains("\"pins\""));
|
||||
let back = format::from_json(&text).expect("load");
|
||||
assert_eq!(back, s.doc);
|
||||
// A path tween from before pins writes none and reads back the same.
|
||||
let plain = on_hump();
|
||||
let text = format::to_json(&plain.doc).expect("save");
|
||||
assert!(!text.contains("\"pins\""));
|
||||
assert_eq!(format::from_json(&text).expect("load"), plain.doc);
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
//! Onion skin and Edit Multiple Frames (ADR 0047).
|
||||
//!
|
||||
//! **Onion skin** draws the frames around the playhead under it, faded: frames before it in the
|
||||
//! *past* colour, frames after it in the *future* colour, each fainter the farther it is (when
|
||||
//! fading is on). Which frames are shown is set by two markers: they follow the playhead
|
||||
//! (`before` and `after` frames of it) or stay where they were put (anchored). Options: tint or
|
||||
//! the artwork's own colours, outlines only, keyframes only.
|
||||
//!
|
||||
//! **Edit Multiple Frames** shows the artwork on every keyframe within the markers at full
|
||||
//! strength, as if on one frame, and `frames.edit_multiple` moves it: the elements chosen (or all
|
||||
//! of them) on each of those keyframes, as one undo step.
|
||||
//!
|
||||
//! Both are *view* settings: the shell keeps an [`OnionSkin`] and passes it with each render job
|
||||
//! (keyed by [`OnionSkin::key`], so the frame cache keeps working), and the composition here is a
|
||||
//! pure function of the document, the frame and the settings. Only the moves change the
|
||||
//! document, through the command.
|
||||
//!
|
||||
//! Behaviour learned from Adobe's public help pages on onion skinning and from watching the
|
||||
//! program; nothing was copied.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline};
|
||||
use anicraft_geom::{Affine, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Most frames onion skin or Edit Multiple Frames draws besides the playhead's (the nearest
|
||||
/// ones are kept): each is one more evaluation of the scene.
|
||||
pub const MAX_EXTRA_FRAMES: usize = 120;
|
||||
/// Opacity of the nearest onion frame, and of the farthest when fading by distance.
|
||||
pub const NEAR_ALPHA: f32 = 0.5;
|
||||
pub const FAR_ALPHA: f32 = 0.12;
|
||||
/// How much of the past or future colour tints an onion frame (the rest is its own colour, so
|
||||
/// fills and lines inside it stay apart).
|
||||
pub const TINT_AMOUNT: f32 = 0.8;
|
||||
/// The marker presets (Onion 2, Onion 5): frames on each side of the playhead.
|
||||
pub const PRESETS: [u32; 2] = [2, 5];
|
||||
|
||||
/// Where the onion markers are.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Markers {
|
||||
/// `before` frames before the playhead to `after` frames after it, following it.
|
||||
Relative { before: u32, after: u32 },
|
||||
/// Fixed frames (0-based, inclusive), whatever the playhead does. `last` beyond the end
|
||||
/// reaches the end however long the timeline gets (Onion All).
|
||||
Anchored { first: u32, last: u32 },
|
||||
}
|
||||
|
||||
/// Onion skin and Edit Multiple Frames settings (view state the shell owns).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct OnionSkin {
|
||||
/// Onion skin is on: frames around the playhead show under it.
|
||||
pub ghosts: bool,
|
||||
/// Edit Multiple Frames is on: keyframes within the markers show at full strength (and
|
||||
/// onion frames are not drawn).
|
||||
pub edit_multiple: bool,
|
||||
pub markers: Markers,
|
||||
/// Tint onion frames with `past` and `future`; off, they keep their own colours.
|
||||
pub tint: bool,
|
||||
pub past: Rgba,
|
||||
pub future: Rgba,
|
||||
/// Fainter with distance from the playhead; off, every onion frame has [`NEAR_ALPHA`].
|
||||
pub fade: bool,
|
||||
/// Onion frames as hairline outlines in their colour.
|
||||
pub outlines: bool,
|
||||
/// Only frames where a keyframe starts (on each layer, its own keyframes).
|
||||
pub keyframes_only: bool,
|
||||
}
|
||||
|
||||
impl Default for OnionSkin {
|
||||
fn default() -> Self {
|
||||
OnionSkin {
|
||||
ghosts: true,
|
||||
edit_multiple: false,
|
||||
markers: Markers::Relative { before: 2, after: 2 },
|
||||
tint: true,
|
||||
past: Rgba::hex(0x4f8dff),
|
||||
future: Rgba::hex(0x4cd07d),
|
||||
fade: true,
|
||||
outlines: false,
|
||||
keyframes_only: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Most frames a marker reaches from the playhead.
|
||||
pub const MAX_REACH: u32 = MAX_FRAME;
|
||||
|
||||
impl OnionSkin {
|
||||
/// Whether it changes what the stage shows.
|
||||
pub fn shows(&self) -> bool {
|
||||
self.ghosts || self.edit_multiple
|
||||
}
|
||||
|
||||
/// The frames within the markers (0-based, inclusive) for a timeline of `frames` frames
|
||||
/// with the playhead on `playhead`: always inside the timeline, `first <= last`.
|
||||
pub fn range(&self, playhead: u32, frames: u32) -> (u32, u32) {
|
||||
let end = frames.max(1) - 1;
|
||||
match self.markers {
|
||||
Markers::Relative { before, after } => {
|
||||
let p = playhead.min(end);
|
||||
(p.saturating_sub(before.min(MAX_REACH)), p.saturating_add(after.min(MAX_REACH)).min(end))
|
||||
}
|
||||
Markers::Anchored { first, last } => {
|
||||
let (a, b) = (first.min(last), first.max(last));
|
||||
(a.min(end), b.min(end))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors the markers where they are now (`on`), or makes them follow the playhead again,
|
||||
/// the same distance from it (a marker the playhead has passed is moved onto it).
|
||||
pub fn set_anchored(&mut self, on: bool, playhead: u32, frames: u32) {
|
||||
let (first, last) = self.range(playhead, frames);
|
||||
self.markers = match (on, self.markers) {
|
||||
(true, Markers::Relative { .. }) => Markers::Anchored { first, last },
|
||||
(false, Markers::Anchored { .. }) => {
|
||||
let p = playhead.min(frames.max(1) - 1);
|
||||
Markers::Relative { before: p.saturating_sub(first), after: last.saturating_sub(p) }
|
||||
}
|
||||
(_, m) => m,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn anchored(&self) -> bool {
|
||||
matches!(self.markers, Markers::Anchored { .. })
|
||||
}
|
||||
|
||||
/// Onion 2 / Onion 5: `n` frames on each side, following the playhead.
|
||||
pub fn preset(&mut self, n: u32) {
|
||||
self.markers = Markers::Relative { before: n.min(MAX_REACH), after: n.min(MAX_REACH) };
|
||||
}
|
||||
|
||||
/// Onion All: the whole timeline, however long it gets.
|
||||
pub fn all(&mut self) {
|
||||
self.markers = Markers::Anchored { first: 0, last: MAX_FRAME };
|
||||
}
|
||||
|
||||
/// Whether the markers are Onion All's.
|
||||
pub fn is_all(&self) -> bool {
|
||||
self.markers == Markers::Anchored { first: 0, last: MAX_FRAME }
|
||||
}
|
||||
|
||||
/// Moves the start marker (`start`) or the end marker to frame `to`, keeping the range on
|
||||
/// the right side of the playhead when relative, and never past the other marker.
|
||||
pub fn drag_marker(&mut self, start: bool, to: u32, playhead: u32, frames: u32) {
|
||||
let end = frames.max(1) - 1;
|
||||
let to = to.min(end);
|
||||
let (first, last) = self.range(playhead, frames);
|
||||
let p = playhead.min(end);
|
||||
self.markers = match self.markers {
|
||||
Markers::Relative { after, .. } if start => Markers::Relative { before: p.saturating_sub(to.min(p)), after },
|
||||
Markers::Relative { before, .. } => Markers::Relative { before, after: to.max(p) - p },
|
||||
Markers::Anchored { .. } if start => Markers::Anchored { first: to.min(last), last },
|
||||
Markers::Anchored { .. } => Markers::Anchored { first, last: to.max(first) },
|
||||
};
|
||||
}
|
||||
|
||||
/// Opacity of an onion frame `distance` frames from the playhead, on a side whose marker
|
||||
/// is `reach` frames away.
|
||||
pub fn alpha(&self, distance: u32, reach: u32) -> f32 {
|
||||
if !self.fade || reach <= 1 {
|
||||
return NEAR_ALPHA;
|
||||
}
|
||||
let t = (distance.saturating_sub(1) as f32 / (reach - 1) as f32).clamp(0.0, 1.0);
|
||||
NEAR_ALPHA * (1.0 - t) + FAR_ALPHA * t
|
||||
}
|
||||
|
||||
/// The colour effect an onion frame gets, and the outline colour (when outlines are on).
|
||||
pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorEffect, Option<Rgba>) {
|
||||
let alpha = self.alpha(distance, reach);
|
||||
let color = if past { self.past } else { self.future };
|
||||
let (tint, tint_amount) = if self.tint { (color, TINT_AMOUNT) } else { (Rgba::WHITE, 0.0) };
|
||||
let outline = self.outlines.then(|| color.with_alpha(alpha * color.a.clamp(0.0, 1.0)));
|
||||
(ColorEffect { alpha, tint, tint_amount }, outline)
|
||||
}
|
||||
|
||||
/// A hash of everything that changes the picture, for render-cache keys.
|
||||
pub fn key(&self) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
(self.ghosts, self.edit_multiple, self.markers, self.tint, self.fade, self.outlines, self.keyframes_only).hash(&mut h);
|
||||
for c in [self.past, self.future] {
|
||||
[c.r, c.g, c.b, c.a].map(f32::to_bits).hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// One extra frame to draw under the playhead's: frame `frame`, only `layers`' artwork.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Extra {
|
||||
pub frame: u32,
|
||||
pub layers: Vec<LayerId>,
|
||||
/// An onion frame before the playhead (`Some(true)`), after it (`Some(false)`), or an Edit
|
||||
/// Multiple Frames keyframe at full strength (`None`).
|
||||
pub past: Option<bool>,
|
||||
/// Frames from the playhead.
|
||||
pub distance: u32,
|
||||
}
|
||||
|
||||
/// Whether onion skin draws `layer` (Animate doesn't onion-skin locked layers).
|
||||
fn ghosted(tl: &Timeline, i: usize) -> bool {
|
||||
tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder && !tl.locked_by_folder(l.id) && !tl.hidden_by_folder(i))
|
||||
}
|
||||
|
||||
/// Whether Edit Multiple Frames shows and edits `layer`'s other keyframes: it is shown and
|
||||
/// unlocked, and holds artwork (not a folder, the camera or an armature posed by its bones).
|
||||
pub fn multi_editable(tl: &Timeline, i: usize) -> bool {
|
||||
ghosted(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature))
|
||||
}
|
||||
|
||||
/// The onion frames to draw for the playhead on `playhead`, farthest first (nearest on top),
|
||||
/// past and future taking turns at each distance.
|
||||
pub fn onion_frames(tl: &Timeline, playhead: u32, skin: &OnionSkin) -> Vec<Extra> {
|
||||
let (first, last) = skin.range(playhead, tl.frame_count());
|
||||
let layers: Vec<usize> = (0..tl.layers.len()).filter(|&i| ghosted(tl, i)).collect();
|
||||
if layers.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out: Vec<Extra> = Vec::new();
|
||||
// Nearest first, so the cap keeps the nearest; reversed at the end.
|
||||
let reach = playhead.saturating_sub(first).max(last.saturating_sub(playhead));
|
||||
for d in 1..=reach {
|
||||
if out.len() >= MAX_EXTRA_FRAMES {
|
||||
break;
|
||||
}
|
||||
// Future first: the list is reversed below, so at each distance the past frame is drawn
|
||||
// first.
|
||||
for (past, f) in [(false, playhead.checked_add(d)), (true, playhead.checked_sub(d))] {
|
||||
let Some(f) = f.filter(|f| (first..=last).contains(f)) else { continue };
|
||||
let ids: Vec<LayerId> = if skin.keyframes_only {
|
||||
// A layer's keyframe starting there; the one the playhead is on only when it
|
||||
// tweens (otherwise it looks the same as the playhead's frame).
|
||||
layers.iter().filter_map(|&i| tl.layers.get(i)).filter(|l| l.keyframe_starting_at(f).and_then(|k| l.keyframes.get(k)).is_some_and(|k| !k.covers(playhead) || k.tween.is_some() || k.motion.is_some())).map(|l| l.id).collect()
|
||||
} else {
|
||||
layers.iter().filter_map(|&i| tl.layers.get(i)).map(|l| l.id).collect()
|
||||
};
|
||||
if !ids.is_empty() && out.len() < MAX_EXTRA_FRAMES {
|
||||
out.push(Extra { frame: f, layers: ids, past: Some(past), distance: d });
|
||||
}
|
||||
}
|
||||
}
|
||||
out.reverse();
|
||||
out
|
||||
}
|
||||
|
||||
/// The keyframes Edit Multiple Frames draws besides the playhead's: on each editable layer,
|
||||
/// every keyframe whose span reaches into `first..=last` except the one under the playhead,
|
||||
/// drawn as it looks on its first frame. Grouped by that frame, in frame order.
|
||||
pub fn multi_frames(tl: &Timeline, playhead: u32, first: u32, last: u32) -> Vec<Extra> {
|
||||
let mut at: BTreeMap<u32, Vec<LayerId>> = BTreeMap::new();
|
||||
for (i, l) in tl.layers.iter().enumerate() {
|
||||
if !multi_editable(tl, i) {
|
||||
continue;
|
||||
}
|
||||
for k in l.keyframes.iter().filter(|k| k.start <= last && k.end() > first && !k.covers(playhead)) {
|
||||
at.entry(k.start).or_default().push(l.id);
|
||||
}
|
||||
}
|
||||
let mut out: Vec<Extra> = at.into_iter().map(|(frame, layers)| Extra { frame, layers, past: None, distance: frame.abs_diff(playhead) }).collect();
|
||||
if out.len() > MAX_EXTRA_FRAMES {
|
||||
// Keep the nearest, still in frame order.
|
||||
let mut by: Vec<u32> = out.iter().map(|e| e.distance).collect();
|
||||
by.sort_unstable();
|
||||
let cut = by.get(MAX_EXTRA_FRAMES - 1).copied().unwrap_or(0);
|
||||
let mut kept = 0usize;
|
||||
out.retain(|e| {
|
||||
let keep = e.distance <= cut && kept < MAX_EXTRA_FRAMES;
|
||||
kept += usize::from(keep);
|
||||
keep
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Keeps only `layers`' items (and the mask artwork their clips need, which draws nothing).
|
||||
fn keep_layers(dl: &mut DisplayList, layers: &[LayerId]) {
|
||||
let set: HashSet<LayerId> = layers.iter().copied().collect();
|
||||
dl.items.retain(|i| set.contains(&i.layer) || (i.masks.is_some() && i.group.is_none()));
|
||||
}
|
||||
|
||||
/// The parts as one list, layer by layer: each layer's items from every part, in part order,
|
||||
/// then the next layer up. So a frame before or after the playhead shows under the playhead's
|
||||
/// artwork *on its own layer* and over the layers below, as in Animate, and an opaque
|
||||
/// background never hides it. Also says which part each item came from.
|
||||
///
|
||||
/// Reordering items is safe: a group's run lies within one layer (it stays unbroken), and the
|
||||
/// renderers take mask artwork apart from what they draw, whatever its place in the list.
|
||||
fn interleave(tl: &Timeline, parts: Vec<DisplayList>) -> (DisplayList, Vec<usize>) {
|
||||
let n = tl.layers.len();
|
||||
let rank: std::collections::HashMap<LayerId, usize> = tl.layers.iter().enumerate().map(|(i, l)| (l.id, i)).collect();
|
||||
// Back to front: the bottom layer (the highest index) first; an unknown layer before all.
|
||||
let bucket = |l: LayerId| rank.get(&l).map_or(0, |r| n - r);
|
||||
let total = parts.iter().map(|p| p.items.len()).sum();
|
||||
let mut dl = DisplayList::default();
|
||||
let mut iters = Vec::with_capacity(parts.len());
|
||||
for part in parts {
|
||||
// Clips and groups renumbered as `DisplayList::append` does.
|
||||
let (base, gbase) = (dl.clip_parents.len() as u32, dl.groups.len() as u32);
|
||||
let shift = move |c: Option<u32>| c.map(|c| c + base);
|
||||
let gshift = move |g: Option<u32>| g.map(|g| g + gbase);
|
||||
dl.clip_parents.extend(part.clip_parents.into_iter().map(shift));
|
||||
dl.groups.extend(part.groups.into_iter().map(|g| anicraft_doc::Group { parent: gshift(g.parent), clip: shift(g.clip), ..g }));
|
||||
iters.push(
|
||||
part.items
|
||||
.into_iter()
|
||||
.map(move |mut i| {
|
||||
i.clip = shift(i.clip);
|
||||
i.masks = shift(i.masks);
|
||||
i.group = gshift(i.group);
|
||||
i
|
||||
})
|
||||
.peekable(),
|
||||
);
|
||||
}
|
||||
// Each part is already back to front, layer by layer: one merge, each item moved once.
|
||||
let mut items = Vec::with_capacity(total);
|
||||
let mut from = Vec::with_capacity(total);
|
||||
for b in 0..=n {
|
||||
for (k, it) in iters.iter_mut().enumerate() {
|
||||
while let Some(x) = it.next_if(|x| bucket(x.layer) <= b) {
|
||||
items.push(x);
|
||||
from.push(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
// (Nothing is left unless a part was out of layer order; keep it rather than drop it.)
|
||||
for (k, it) in iters.into_iter().enumerate() {
|
||||
for x in it {
|
||||
items.push(x);
|
||||
from.push(k);
|
||||
}
|
||||
}
|
||||
dl.items = items;
|
||||
(dl, from)
|
||||
}
|
||||
|
||||
/// Scene `scene` at its frame `local` with what `skin` adds (nothing for `None`): onion frames,
|
||||
/// or Edit Multiple Frames' keyframes, each under the playhead's artwork on its own layer.
|
||||
/// `eval` evaluates one frame of the scene (with or without its camera).
|
||||
pub fn compose(doc: &Document, scene: usize, local: u32, skin: Option<&OnionSkin>, eval: impl Fn(usize, u32) -> DisplayList + Sync) -> DisplayList {
|
||||
let now = eval(scene, local);
|
||||
let Some(skin) = skin.filter(|s| s.shows()) else { return now };
|
||||
let tl = doc.timeline(scene);
|
||||
let (first, last) = skin.range(local, tl.frame_count());
|
||||
let extras = if skin.edit_multiple { multi_frames(tl, local, first, last) } else { onion_frames(tl, local, skin) };
|
||||
if extras.is_empty() {
|
||||
return now;
|
||||
}
|
||||
// The frames are independent: evaluated in parallel, kept in order.
|
||||
use rayon::prelude::*;
|
||||
let mut parts: Vec<DisplayList> = extras.par_iter().map(|e| eval(scene, e.frame)).collect();
|
||||
for (part, e) in parts.iter_mut().zip(&extras) {
|
||||
keep_layers(part, &e.layers);
|
||||
if let Some(past) = e.past {
|
||||
let reach = if past { local.saturating_sub(first) } else { last.saturating_sub(local) };
|
||||
let (fx, outline) = skin.look(past, e.distance, reach);
|
||||
for item in &mut part.items {
|
||||
item.color = item.color.concat(&fx);
|
||||
if outline.is_some() && item.masks.is_none() {
|
||||
item.outline = outline;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
parts.push(now);
|
||||
interleave(tl, parts).0
|
||||
}
|
||||
|
||||
// ----- Edit Multiple Frames: artwork, picking and moves ------------------------------------
|
||||
|
||||
/// An element on one keyframe: its layer, the keyframe's first frame and its id (an element
|
||||
/// keeps its id from keyframe to keyframe, so the frame says which copy).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct FrameItem {
|
||||
pub layer: LayerId,
|
||||
pub frame: u32,
|
||||
pub element: ElementId,
|
||||
}
|
||||
|
||||
impl FrameItem {
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!([self.layer.0, self.frame, self.element.0])
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// What Edit Multiple Frames shows in `first..=last`, layer by layer as the stage draws it
|
||||
/// (each keyframe as it looks on its first frame, the playhead's as it looks there), with
|
||||
/// the keyframe start of each item's layer (`None`: a layer it doesn't edit).
|
||||
fn multi_list(&self, first: u32, last: u32) -> (DisplayList, Vec<Option<u32>>) {
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
let mut parts = Vec::new();
|
||||
let mut starts: Vec<Vec<(LayerId, u32)>> = Vec::new();
|
||||
for e in multi_frames(tl, self.frame, first, last) {
|
||||
let mut dl = anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame);
|
||||
keep_layers(&mut dl, &e.layers);
|
||||
parts.push(dl);
|
||||
starts.push(e.layers.iter().map(|l| (*l, e.frame)).collect());
|
||||
}
|
||||
// The playhead's frame: every editable layer, at the start of its keyframe there.
|
||||
let now: Vec<(LayerId, u32)> = tl.layers.iter().enumerate().filter(|(i, _)| multi_editable(tl, *i)).filter_map(|(_, l)| l.keyframe_at(self.frame).map(|k| (l.id, k.start))).collect();
|
||||
let mut dl = (*self.display_list()).clone();
|
||||
keep_layers(&mut dl, &now.iter().map(|(l, _)| *l).collect::<Vec<_>>());
|
||||
parts.push(dl);
|
||||
starts.push(now);
|
||||
let (dl, from) = interleave(tl, parts);
|
||||
let frames = dl.items.iter().zip(&from).map(|(it, &k)| starts.get(k).and_then(|s| s.iter().find(|(l, _)| *l == it.layer)).map(|(_, f)| *f)).collect();
|
||||
(dl, frames)
|
||||
}
|
||||
|
||||
/// Every element Edit Multiple Frames shows in `first..=last`, with its stage bounds (the
|
||||
/// playhead's elements as they look there), back to front.
|
||||
pub fn multi_frame_items(&self, first: u32, last: u32) -> Vec<(FrameItem, Rect)> {
|
||||
let (first, last) = (first.min(last), first.max(last));
|
||||
let mut out: Vec<(FrameItem, Rect)> = Vec::new();
|
||||
let mut index: std::collections::HashMap<FrameItem, usize> = std::collections::HashMap::new();
|
||||
let (dl, frames) = self.multi_list(first, last);
|
||||
{
|
||||
for (item, frame) in dl.items.iter().zip(frames) {
|
||||
let Some(frame) = frame else { continue };
|
||||
let key = FrameItem { layer: item.layer, frame, element: item.element };
|
||||
let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach);
|
||||
let b = item.path.bounds().inflate(pad).transformed(&item.transform);
|
||||
match index.get(&key).and_then(|&i| out.get_mut(i)) {
|
||||
Some((_, r)) => *r = r.union(&b),
|
||||
None => {
|
||||
index.insert(key, out.len());
|
||||
out.push((key, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The topmost element Edit Multiple Frames shows under `p` in `first..=last`.
|
||||
pub fn multi_frame_pick(&self, first: u32, last: u32, p: Vec2, slop: f32) -> Option<FrameItem> {
|
||||
let (first, last) = (first.min(last), first.max(last));
|
||||
let (dl, frames) = self.multi_list(first, last);
|
||||
let i = crate::pick_index(&dl, p, slop, |i, _| frames.get(i).copied().flatten().is_some())?;
|
||||
let item = dl.items.get(i)?;
|
||||
Some(FrameItem { layer: item.layer, frame: frames.get(i).copied().flatten()?, element: item.element })
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("frames.artwork", "Artwork on Multiple Frames", "", None, "{first, last} lists every element Edit Multiple Frames shows in frames first..=last (0-based): [layer, frame (its keyframe's first frame), id] with stage bounds; the playhead's elements as they look there", false, artwork as crate::RunFn),
|
||||
c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..]} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; one undo step", true, edit_multiple),
|
||||
]
|
||||
}
|
||||
|
||||
/// The `first` and `last` params, in order.
|
||||
fn range_param(p: &Value) -> Result<(u32, u32)> {
|
||||
let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)")));
|
||||
let (a, b) = (req("first")?, req("last")?);
|
||||
if a.max(b) > MAX_FRAME {
|
||||
return Err(EngineError::Param(format!("frames go up to {MAX_FRAME}")));
|
||||
}
|
||||
Ok((a.min(b), a.max(b)))
|
||||
}
|
||||
|
||||
fn artwork(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let items: Vec<Value> = s.multi_frame_items(first, last).into_iter().map(|(it, b)| json!({"layer": it.layer.0, "frame": it.frame, "id": it.element.0, "bounds": [b.min.x, b.min.y, b.max.x, b.max.y]})).collect();
|
||||
Ok(json!({"first": first, "last": last, "items": items}))
|
||||
}
|
||||
|
||||
/// Most items `frames.edit_multiple` takes.
|
||||
const MAX_ITEMS: usize = 100_000;
|
||||
|
||||
fn items_param(p: &Value) -> Result<Option<Vec<FrameItem>>> {
|
||||
let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into());
|
||||
let list = v.as_array().ok_or_else(bad)?;
|
||||
if list.len() > MAX_ITEMS {
|
||||
return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items")));
|
||||
}
|
||||
list.iter()
|
||||
.map(|t| {
|
||||
let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?;
|
||||
let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad);
|
||||
let frame = u32::try_from(n(1)?).map_err(|_| bad())?;
|
||||
Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) })
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
fn edit_multiple(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT {
|
||||
return Err(EngineError::Param("the move is too large".into()));
|
||||
}
|
||||
let shown: Vec<FrameItem> = s.multi_frame_items(first, last).into_iter().map(|(it, _)| it).collect();
|
||||
let items = match items_param(p)? {
|
||||
Some(list) => {
|
||||
let have: HashSet<FrameItem> = shown.iter().copied().collect();
|
||||
if let Some(bad) = list.iter().find(|it| !have.contains(it)) {
|
||||
return Err(EngineError::State(format!(
|
||||
"element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)",
|
||||
bad.element.0, bad.layer.0, bad.frame
|
||||
)));
|
||||
}
|
||||
list
|
||||
}
|
||||
None => shown,
|
||||
};
|
||||
// One pass per keyframe: (layer, keyframe start) → its ids.
|
||||
let mut by_key: BTreeMap<(LayerId, u32), HashSet<ElementId>> = BTreeMap::new();
|
||||
for it in &items {
|
||||
by_key.entry((it.layer, it.frame)).or_default().insert(it.element);
|
||||
}
|
||||
let mv = Affine::translate(d.x, d.y);
|
||||
let mut moved = 0usize;
|
||||
for ((layer, start), ids) in &by_key {
|
||||
let l = s.layer_mut(Some(*layer))?;
|
||||
let Some(ki) = l.keyframe_starting_at(*start) else { continue };
|
||||
let Some(kf) = l.keyframe_mut(ki) else { continue };
|
||||
// A motion tween's object carries its path and X/Y keys along (refused, with nothing
|
||||
// changed, if they would leave the stage's range).
|
||||
if let Some(m) = kf.motion.as_mut()
|
||||
&& ids.contains(&m.target)
|
||||
&& d != Vec2::ZERO
|
||||
&& !m.translate(d)
|
||||
{
|
||||
return Err(EngineError::State("the motion path would move out of range".into()));
|
||||
}
|
||||
for e in kf.elements_mut_where(|id| ids.contains(&id)) {
|
||||
e.transform = mv.mul(&e.transform);
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
Ok(json!({"moved": moved, "keyframes": by_key.len(), "dx": d.x, "dy": d.y}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "onion_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,431 @@
|
||||
//! Onion skin and Edit Multiple Frames (ADR 0047): markers, tint and fade, outlines, keyframes
|
||||
//! only, the composed display list and its render, and moves on several keyframes.
|
||||
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use anicraft_doc::{DisplayItem, ElementId, LayerId, Rgba, evaluate_scene, sample};
|
||||
use anicraft_render::{View, render};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// One layer, a 20 × 20 drawing object walking right: keyframes on frames 0, 4 and 8 (the last
|
||||
/// one frame long) with it at x = 10, 50 and 90 (y = 10). The playhead is on frame 4.
|
||||
fn walk() -> (Session, LayerId, ElementId) {
|
||||
let mut s = Session::default();
|
||||
let layer = s.layer;
|
||||
let id = ElementId(run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap());
|
||||
for f in [4, 8] {
|
||||
run(&mut s, "timeline.goto", json!({"frame": f}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
run(&mut s, "element.select", json!({"ids": [id.0]}));
|
||||
run(&mut s, "element.translate", json!({"dx": 40, "dy": 0}));
|
||||
}
|
||||
run(&mut s, "timeline.goto", json!({"frame": 4}));
|
||||
assert_eq!(s.frame_count(), 9);
|
||||
(s, layer, id)
|
||||
}
|
||||
|
||||
/// The left edge of `id` on the keyframe of `layer` starting at `start`.
|
||||
fn x_at(s: &Session, layer: LayerId, start: u32, id: ElementId) -> f32 {
|
||||
let l = s.doc.timeline(s.scene).layer(layer).unwrap();
|
||||
let k = l.keyframes.iter().find(|k| k.start == start).unwrap();
|
||||
let e = k.elements.iter().find(|e| e.id == id).unwrap();
|
||||
e.bounds(&s.doc).min.x
|
||||
}
|
||||
|
||||
fn left(i: &DisplayItem) -> f32 {
|
||||
i.path.bounds().transformed(&i.transform).min.x
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_stay_inside_the_timeline() {
|
||||
let mut o = OnionSkin::default();
|
||||
assert_eq!(o.range(0, 10), (0, 2), "nothing before frame 1");
|
||||
assert_eq!(o.range(9, 10), (7, 9), "nothing after the last frame");
|
||||
assert_eq!(o.range(50, 10), (7, 9), "a playhead past the end counts as the last frame");
|
||||
assert_eq!(o.range(0, 0), (0, 0));
|
||||
o.markers = Markers::Relative { before: u32::MAX, after: u32::MAX };
|
||||
assert_eq!(o.range(5, 10), (0, 9));
|
||||
o.markers = Markers::Anchored { first: 8, last: 3 };
|
||||
assert_eq!(o.range(0, 10), (3, 8), "anchored markers in order, whatever the playhead");
|
||||
o.markers = Markers::Anchored { first: 400, last: 900 };
|
||||
assert_eq!(o.range(0, 10), (9, 9));
|
||||
o.all();
|
||||
assert!(o.is_all() && o.anchored());
|
||||
assert_eq!(o.range(4, 10), (0, 9));
|
||||
assert_eq!(o.range(4, 500), (0, 499), "Onion All grows with the timeline");
|
||||
o.preset(5);
|
||||
assert!(!o.anchored() && !o.is_all());
|
||||
assert_eq!(o.range(10, 100), (5, 15));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_drag_and_anchor() {
|
||||
let mut o = OnionSkin::default();
|
||||
o.drag_marker(true, 1, 6, 20);
|
||||
assert_eq!(o.range(6, 20), (1, 8));
|
||||
o.drag_marker(true, 9, 6, 20);
|
||||
assert_eq!(o.range(6, 20), (6, 8), "the start marker stops at the playhead");
|
||||
o.drag_marker(false, 50, 6, 20);
|
||||
assert_eq!(o.range(6, 20), (6, 19), "the end marker stops at the last frame");
|
||||
o.drag_marker(false, 2, 6, 20);
|
||||
assert_eq!(o.range(6, 20), (6, 6));
|
||||
// Anchoring keeps the frames; the playhead then moves without them.
|
||||
o.preset(2);
|
||||
o.set_anchored(true, 6, 20);
|
||||
assert_eq!((o.range(6, 20), o.range(15, 20)), ((4, 8), (4, 8)));
|
||||
o.drag_marker(true, 12, 15, 20);
|
||||
assert_eq!(o.range(15, 20), (8, 8), "never past the other marker");
|
||||
o.drag_marker(false, 3, 15, 20);
|
||||
assert_eq!(o.range(15, 20), (8, 8));
|
||||
o.drag_marker(false, 12, 15, 20);
|
||||
assert_eq!(o.range(15, 20), (8, 12));
|
||||
// Following the playhead again: the same distances from it...
|
||||
o.set_anchored(false, 10, 20);
|
||||
assert_eq!(o.markers, Markers::Relative { before: 2, after: 2 });
|
||||
// ...and a marker the playhead has passed lands on it.
|
||||
o.set_anchored(true, 10, 20);
|
||||
o.set_anchored(false, 15, 20);
|
||||
assert_eq!(o.range(15, 20), (8, 15));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn onion_frames_fade_by_distance_in_their_colours() {
|
||||
let o = OnionSkin::default();
|
||||
assert_eq!(o.alpha(1, 5), NEAR_ALPHA);
|
||||
assert_eq!(o.alpha(5, 5), FAR_ALPHA);
|
||||
assert!((o.alpha(3, 5) - (NEAR_ALPHA + FAR_ALPHA) / 2.0).abs() < 1e-6);
|
||||
assert!((1..5).all(|d| o.alpha(d, 5) > o.alpha(d + 1, 5)), "fainter with each frame");
|
||||
assert_eq!(o.alpha(1, 1), NEAR_ALPHA);
|
||||
assert_eq!(o.alpha(9, 5), FAR_ALPHA, "never fainter than the farthest");
|
||||
let flat = OnionSkin { fade: false, ..o };
|
||||
assert!((1..=5).all(|d| flat.alpha(d, 5) == NEAR_ALPHA));
|
||||
|
||||
let (past, line) = o.look(true, 1, 2);
|
||||
assert_eq!((past.tint, past.tint_amount, past.alpha, line), (o.past, TINT_AMOUNT, NEAR_ALPHA, None));
|
||||
let (future, _) = o.look(false, 2, 2);
|
||||
assert_eq!((future.tint, future.alpha), (o.future, FAR_ALPHA));
|
||||
let (own, _) = OnionSkin { tint: false, ..o }.look(true, 1, 2);
|
||||
assert_eq!(own.tint_amount, 0.0, "untinted frames keep their own colours");
|
||||
let (_, line) = OnionSkin { outlines: true, ..o }.look(false, 2, 2);
|
||||
assert_eq!(line, Some(o.future.with_alpha(FAR_ALPHA)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_setting_is_in_the_key() {
|
||||
let o = OnionSkin::default();
|
||||
let variants = [
|
||||
OnionSkin { ghosts: false, ..o },
|
||||
OnionSkin { edit_multiple: true, ..o },
|
||||
OnionSkin { markers: Markers::Relative { before: 2, after: 3 }, ..o },
|
||||
OnionSkin { markers: Markers::Anchored { first: 0, last: 2 }, ..o },
|
||||
OnionSkin { tint: false, ..o },
|
||||
OnionSkin { past: Rgba::hex(0x123456), ..o },
|
||||
OnionSkin { future: Rgba::hex(0x123456), ..o },
|
||||
OnionSkin { fade: false, ..o },
|
||||
OnionSkin { outlines: true, ..o },
|
||||
OnionSkin { keyframes_only: true, ..o },
|
||||
];
|
||||
let mut keys: Vec<u64> = variants.iter().map(OnionSkin::key).collect();
|
||||
keys.push(o.key());
|
||||
let n = keys.len();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
assert_eq!(keys.len(), n);
|
||||
assert_eq!(o.key(), OnionSkin::default().key());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn onion_frames_come_farthest_first_and_skip_locked_layers() {
|
||||
let (mut s, a, _) = walk();
|
||||
let b = LayerId(run(&mut s, "layer.new", json!({"name": "Locked"}))["layer"].as_u64().unwrap());
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 100, "w": 9, "h": 9, "object": true}));
|
||||
run(&mut s, "timeline.insert_frame", json!({"count": 8}));
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": b.0}));
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let got: Vec<(u32, Option<bool>, u32)> = onion_frames(tl, 4, &OnionSkin::default()).iter().map(|e| (e.frame, e.past, e.distance)).collect();
|
||||
assert_eq!(got, vec![(2, Some(true), 2), (6, Some(false), 2), (3, Some(true), 1), (5, Some(false), 1)]);
|
||||
assert!(onion_frames(tl, 4, &OnionSkin::default()).iter().all(|e| e.layers == vec![a]), "locked layers are not onion-skinned");
|
||||
// At the first frame there is no past.
|
||||
assert!(onion_frames(tl, 0, &OnionSkin::default()).iter().all(|e| e.past == Some(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyframes_only_shows_each_layers_own_keyframes() {
|
||||
let (mut s, a, _) = walk();
|
||||
let b = LayerId(run(&mut s, "layer.new", json!({"name": "B"}))["layer"].as_u64().unwrap());
|
||||
run(&mut s, "timeline.goto", json!({"frame": 0}));
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 100, "w": 9, "h": 9, "object": true}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 2}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
run(&mut s, "timeline.insert_frame", json!({"count": 6}));
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let skin = OnionSkin { keyframes_only: true, markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() };
|
||||
let mut got: Vec<(u32, Vec<LayerId>)> = onion_frames(tl, 4, &skin).into_iter().map(|e| (e.frame, e.layers)).collect();
|
||||
got.sort_by_key(|(f, _)| *f);
|
||||
// Frame 0 is a keyframe on both layers, frame 8 on A. B's keyframe on 2 is the one under the
|
||||
// playhead and doesn't tween: it would only repeat what the playhead shows, so it is left out.
|
||||
assert_eq!(got, vec![(0, vec![b, a]), (8, vec![a])]);
|
||||
// With all frames, every frame in range is there.
|
||||
let all = onion_frames(tl, 4, &OnionSkin { keyframes_only: false, ..skin }).len();
|
||||
let (f0, f1) = skin.range(4, tl.frame_count());
|
||||
assert_eq!(all as u32, f1 - f0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composed_onion_frames_are_tinted_faded_and_under_the_playhead() {
|
||||
let (s, _, _) = walk();
|
||||
let skin = OnionSkin::default();
|
||||
let dl = compose(&s.doc, 0, 4, Some(&skin), |sc, f| evaluate_scene(&s.doc, sc, f));
|
||||
// Frames 2, 6, 3, 5 under frame 4: the keyframes there hold the rectangle at 10, 50, 10, 50.
|
||||
let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect();
|
||||
assert_eq!(got, vec![(10.0, FAR_ALPHA, TINT_AMOUNT), (50.0, FAR_ALPHA, TINT_AMOUNT), (10.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, 1.0, 0.0)]);
|
||||
assert_eq!(dl.items.first().map(|i| i.color.tint), Some(skin.past));
|
||||
assert_eq!(dl.items.get(1).map(|i| i.color.tint), Some(skin.future));
|
||||
// Off, or None: the frame alone.
|
||||
let off = OnionSkin { ghosts: false, ..skin };
|
||||
assert_eq!(compose(&s.doc, 0, 4, Some(&off), |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1);
|
||||
assert_eq!(compose(&s.doc, 0, 4, None, |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1);
|
||||
}
|
||||
|
||||
/// The pixel at (x, y), premultiplied RGBA8.
|
||||
fn px(rgba: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] {
|
||||
let i = ((y * w + x) * 4) as usize;
|
||||
[rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_mode_draws_onion_frames_as_edges_only() {
|
||||
let (s, _, _) = walk();
|
||||
let view = View { transform: Affine::IDENTITY, width: 120, height: 40, background: Some(Rgba::WHITE) };
|
||||
let draw = |skin: &OnionSkin| {
|
||||
let dl = compose(&s.doc, 0, 4, Some(skin), |sc, f| evaluate_scene(&s.doc, sc, f));
|
||||
render(&dl, &view).unwrap().0.to_premul_rgba8()
|
||||
};
|
||||
let filled = draw(&OnionSkin { markers: Markers::Relative { before: 4, after: 0 }, ..OnionSkin::default() });
|
||||
let lines = draw(&OnionSkin { markers: Markers::Relative { before: 4, after: 0 }, outlines: true, ..OnionSkin::default() });
|
||||
const WHITE: [u8; 4] = [255; 4];
|
||||
// Inside the onion rectangle (frames 0–3 hold it at 10..30): tinted when filled, the stage
|
||||
// when outlined; on its left edge (x = 10), the outline shows.
|
||||
assert_ne!(px(&filled, 120, 20, 20), WHITE);
|
||||
assert_eq!(px(&lines, 120, 20, 20), WHITE);
|
||||
assert_ne!(px(&lines, 120, 10, 20), WHITE);
|
||||
let edge = px(&lines, 120, 10, 20);
|
||||
assert!(edge[2] > edge[0], "in the past colour (blue): {edge:?}");
|
||||
// The playhead's frame (x = 50..70) is drawn as it is, either way.
|
||||
assert_eq!(px(&lines, 120, 60, 20), [0, 0, 0, 255]);
|
||||
assert_eq!(px(&filled, 120, 60, 20), [0, 0, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_multiple_frames_shows_keyframes_within_the_markers_at_full_strength() {
|
||||
let (mut s, a, id) = walk();
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let near = OnionSkin { edit_multiple: true, ..OnionSkin::default() };
|
||||
// ±2 around 4 is frames 2..6: the keyframe on 0 reaches into it (to frame 3), the one on 8
|
||||
// doesn't; the one on 4 is the playhead's.
|
||||
assert_eq!(multi_frames(tl, 4, 2, 6).iter().map(|e| e.frame).collect::<Vec<_>>(), vec![0]);
|
||||
let dl = compose(&s.doc, 0, 4, Some(&near), |sc, f| evaluate_scene(&s.doc, sc, f));
|
||||
assert_eq!(dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect::<Vec<_>>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]);
|
||||
let wide = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..near };
|
||||
let dl = compose(&s.doc, 0, 4, Some(&wide), |sc, f| evaluate_scene(&s.doc, sc, f));
|
||||
assert_eq!(dl.items.iter().map(left).collect::<Vec<_>>(), vec![10.0, 90.0, 50.0], "other keyframes in frame order, the playhead's on top");
|
||||
// What it shows is what it lists, each with its keyframe's first frame.
|
||||
let items: Vec<(FrameItem, f32)> = s.multi_frame_items(0, 8).into_iter().map(|(it, b)| (it, b.min.x)).collect();
|
||||
let item = |frame| FrameItem { layer: a, frame, element: id };
|
||||
assert_eq!(items, vec![(item(0), 10.0), (item(8), 90.0), (item(4), 50.0)]);
|
||||
let v = run(&mut s, "frames.artwork", json!({"first": 8, "last": 0}));
|
||||
assert_eq!(v["items"].as_array().map(Vec::len), Some(3));
|
||||
assert_eq!(v["items"][1], json!({"layer": a.0, "frame": 8, "id": id.0, "bounds": [90.0, 10.0, 110.0, 30.0]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_on_multiple_frames_moves_each_keyframe_and_undoes_in_one_step() {
|
||||
let (mut s, a, id) = walk();
|
||||
let steps = s.history_len();
|
||||
let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 5, "dy": 7}));
|
||||
assert_eq!((v["moved"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3)));
|
||||
assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [15.0, 55.0, 95.0]);
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
s.undo().unwrap();
|
||||
assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [10.0, 50.0, 90.0], "one undo takes back every keyframe");
|
||||
// Only the items given.
|
||||
run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": -10, "dy": 0, "items": [[a.0, 8, id.0]]}));
|
||||
assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [10.0, 50.0, 80.0]);
|
||||
// A drag: many small moves in one gesture are one step.
|
||||
let steps = s.history_len();
|
||||
s.begin_gesture("Move");
|
||||
for _ in 0..10 {
|
||||
run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 4, "dx": 1, "dy": 0}));
|
||||
}
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [20.0, 60.0, 80.0], "the keyframe on 8 is outside frames 0..4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moves_refuse_what_edit_multiple_frames_does_not_show() {
|
||||
let (mut s, a, id) = walk();
|
||||
let before = s.doc.clone();
|
||||
let e = s.execute("frames.edit_multiple", &json!({"first": 0, "last": 3, "dx": 5, "dy": 0, "items": [[a.0, 8, id.0]]}));
|
||||
assert!(e.is_err(), "the keyframe on 8 is outside the markers");
|
||||
assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 8, 999]]})).is_err());
|
||||
assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 8]]})).is_err());
|
||||
assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "dx": 5, "dy": 0})).is_err());
|
||||
assert!(s.doc == before);
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": a.0}));
|
||||
assert!(s.multi_frame_items(0, 8).is_empty(), "nothing on a locked layer");
|
||||
assert_eq!(run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 5, "dy": 0}))["moved"], json!(0));
|
||||
assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 0, id.0]]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_finds_artwork_on_every_keyframe_shown() {
|
||||
let (s, a, id) = walk();
|
||||
let at = |x: f32| s.multi_frame_pick(0, 8, Vec2::new(x, 20.0), 1.0);
|
||||
assert_eq!(at(100.0), Some(FrameItem { layer: a, frame: 8, element: id }));
|
||||
assert_eq!(at(60.0), Some(FrameItem { layer: a, frame: 4, element: id }));
|
||||
assert_eq!(at(20.0), Some(FrameItem { layer: a, frame: 0, element: id }));
|
||||
assert_eq!(at(150.0), None);
|
||||
assert_eq!(s.multi_frame_pick(2, 6, Vec2::new(100.0, 20.0), 1.0), None, "outside the markers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_motion_tweens_path_and_keys_move_with_its_object() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "object": true}));
|
||||
run(&mut s, "timeline.insert_frame", json!({"count": 9}));
|
||||
run(&mut s, "timeline.create_motion_tween", json!({}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 9}));
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "element.translate", json!({"dx": 100, "dy": 0}));
|
||||
let x_on = |s: &Session, f: u32| evaluate_scene(&s.doc, 0, f).items.first().map(left).unwrap_or(f32::NAN);
|
||||
let before: Vec<f32> = (0..10).map(|f| x_on(&s, f)).collect();
|
||||
run(&mut s, "timeline.goto", json!({"frame": 0}));
|
||||
let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 9, "dx": 10, "dy": 0}));
|
||||
assert_eq!(v["moved"], json!(1));
|
||||
let after: Vec<f32> = (0..10).map(|f| x_on(&s, f)).collect();
|
||||
for (b, a) in before.iter().zip(&after) {
|
||||
assert!((a - b - 10.0).abs() < 1e-3, "{before:?} → {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_setting_composes_and_renders_on_the_sample() {
|
||||
let doc = sample::demo();
|
||||
let n = doc.timeline(0).frame_count();
|
||||
let view = View { transform: Affine::scale(0.1, 0.1), width: 128, height: 72, background: Some(doc.stage.background) };
|
||||
let mut count = 0;
|
||||
for bits in 0u32..64 {
|
||||
let mut o = OnionSkin { ghosts: bits & 1 != 0, edit_multiple: bits & 2 != 0, tint: bits & 4 != 0, fade: bits & 8 != 0, outlines: bits & 16 != 0, keyframes_only: bits & 32 != 0, ..OnionSkin::default() };
|
||||
for (i, f) in [0, n / 2, n - 1, n + 40].into_iter().enumerate() {
|
||||
match i {
|
||||
1 => o.all(),
|
||||
2 => o.markers = Markers::Anchored { first: n + 5, last: 1 },
|
||||
3 => o.preset(5),
|
||||
_ => {}
|
||||
}
|
||||
let dl = compose(&doc, 0, f.min(n - 1), Some(&o), |sc, fr| evaluate_scene(&doc, sc, fr));
|
||||
count += dl.items.len();
|
||||
if bits % 7 == 0 {
|
||||
assert!(render(&dl, &view).is_ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(count > 0);
|
||||
}
|
||||
|
||||
/// Measures the stage's cost with onion skin ±5 at 1080p, through the tiled path the stage uses
|
||||
/// (one scene evaluation per frame, tiles in parallel), and that a second look is a cache hit:
|
||||
/// `cargo test --release -p anicraft-engine onion_timings -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn onion_timings() {
|
||||
use crate::render_service::{RenderService, make_job};
|
||||
for doc in [sample::demo(), sample::stress(20, 100, 48)] {
|
||||
println!("-- {} items on a frame", evaluate_scene(&doc, 0, 30).items.len());
|
||||
timings_of(&doc);
|
||||
}
|
||||
// The cache: the same frame and settings again are hits, other settings keyed apart.
|
||||
let doc = sample::demo();
|
||||
let five = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() };
|
||||
let view = View { transform: Affine::scale(1.5, 1.5), width: 256, height: 256, background: Some(doc.stage.background) };
|
||||
let jobs = |o: &OnionSkin| (0..40).map(|i| make_job(1, &doc, 30, View { transform: Affine::translate(-(i as f32) * 10.0, 0.0).mul(&view.transform), ..view }, Some(o))).collect::<Vec<_>>();
|
||||
let svc = RenderService::new(1 << 30, None);
|
||||
let first = svc.render_now_batch(jobs(&five));
|
||||
let t = std::time::Instant::now();
|
||||
let again = svc.request_batch(jobs(&five));
|
||||
let hit = t.elapsed().as_secs_f32() * 1000.0;
|
||||
assert!(again.iter().all(Option::is_some) && first.len() == again.len());
|
||||
let outlined = svc.request_batch(jobs(&OnionSkin { outlines: true, ..five }));
|
||||
assert!(outlined.iter().all(Option::is_none), "other settings are other pictures");
|
||||
println!("cache: {} tiles, second look {hit:.3} ms, all hits", again.len());
|
||||
}
|
||||
|
||||
fn timings_of(doc: &anicraft_doc::Document) {
|
||||
use crate::render_service::{make_job, render_batch};
|
||||
let (w, h) = (1920u32, 1080u32);
|
||||
let z = w as f32 / doc.stage.width as f32;
|
||||
let tile = 256u32;
|
||||
let jobs = |onion: Option<&OnionSkin>, frame: u32| -> Vec<crate::render_service::FrameJob> {
|
||||
let mut v = Vec::new();
|
||||
for ty in 0..h.div_ceil(tile) {
|
||||
for tx in 0..w.div_ceil(tile) {
|
||||
let view = View { transform: Affine::translate(-((tx * tile) as f32), -((ty * tile) as f32)).mul(&Affine::scale(z, z)), width: tile.min(w - tx * tile), height: tile.min(h - ty * tile), background: Some(doc.stage.background) };
|
||||
v.push(make_job(1, doc, frame, view, onion));
|
||||
}
|
||||
}
|
||||
v
|
||||
};
|
||||
let five = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() };
|
||||
let cases: [(&str, Option<OnionSkin>); 5] = [
|
||||
("off", None),
|
||||
("±5, tinted, fading", Some(five)),
|
||||
("±5, outlines", Some(OnionSkin { outlines: true, ..five })),
|
||||
("±5, keyframes only", Some(OnionSkin { keyframes_only: true, ..five })),
|
||||
("Edit Multiple Frames ±5", Some(OnionSkin { edit_multiple: true, ..five })),
|
||||
];
|
||||
for (name, o) in cases {
|
||||
let mut best = f32::MAX;
|
||||
for frame in [12u32, 30, 48] {
|
||||
let t = std::time::Instant::now();
|
||||
let _ = render_batch(&jobs(o.as_ref(), frame));
|
||||
best = best.min(t.elapsed().as_secs_f32() * 1000.0);
|
||||
}
|
||||
let t = std::time::Instant::now();
|
||||
let items = crate::render_service::display_list_with_onion(doc, 30, o.as_ref()).items.len();
|
||||
let eval = t.elapsed().as_secs_f32() * 1000.0;
|
||||
println!("{name}: 1080p {best:.1} ms (best of frames 12, 30, 48), scene {eval:.2} ms, {items} items on frame 30");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_frames_sit_on_their_own_layer_over_an_opaque_background() {
|
||||
// The sample's sky (locked) and hills cover the stage: frames before or after the playhead
|
||||
// must show over them, under the playhead's artwork on their own layer only.
|
||||
let doc = sample::demo();
|
||||
let tl = doc.timeline(0);
|
||||
let rank = |l: LayerId| tl.layers.iter().position(|x| x.id == l).unwrap();
|
||||
for o in [OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }, OnionSkin { edit_multiple: true, markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }] {
|
||||
let dl = compose(&doc, 0, 12, Some(&o), |sc, f| evaluate_scene(&doc, sc, f));
|
||||
let plain = evaluate_scene(&doc, 0, 12);
|
||||
assert!(dl.items.len() > plain.items.len());
|
||||
// Back to front: layer by layer, bottom first.
|
||||
assert!(dl.items.windows(2).all(|w| rank(w[0].layer) >= rank(w[1].layer)), "items are grouped by layer, bottom up");
|
||||
// On each layer, its own extra frames come before (under) the playhead's artwork.
|
||||
let ball = plain.items.last().unwrap().layer;
|
||||
let on_ball: Vec<&DisplayItem> = dl.items.iter().filter(|i| i.layer == ball).collect();
|
||||
assert!(on_ball.len() > 1);
|
||||
assert_eq!(on_ball.last().map(|i| (i.color.alpha, i.color.tint_amount)), Some((1.0, 0.0)), "the playhead's ball is on top");
|
||||
}
|
||||
// Rendered: the ball on frame 1 (top left of its path) shows over the sky, in Edit Multiple
|
||||
// Frames at full strength.
|
||||
let view = View { transform: Affine::IDENTITY, width: 1280, height: 720, background: Some(Rgba::WHITE) };
|
||||
let multi = OnionSkin { edit_multiple: true, markers: Markers::Relative { before: 12, after: 0 }, ..OnionSkin::default() };
|
||||
let with = render(&compose(&doc, 0, 12, Some(&multi), |sc, f| evaluate_scene(&doc, sc, f)), &view).unwrap().0.to_premul_rgba8();
|
||||
let without = render(&evaluate_scene(&doc, 0, 12), &view).unwrap().0.to_premul_rgba8();
|
||||
assert_ne!(px(&with, 1280, 200, 260), px(&without, 1280, 200, 260), "the ball on frame 1 is visible");
|
||||
}
|
||||
@@ -146,3 +146,86 @@ pub fn opt_profile(p: &Value, key: &str) -> Result<Option<Option<WidthProfile>>>
|
||||
Some(_) => Err(bad(key, want)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the stroke style params take (`stroke.set_style`, `element.set_stroke`, the drawing
|
||||
/// commands, `paint.ink`).
|
||||
pub const STROKE_STYLE_PARAMS: &str = "cap?: none|round|square, join?: miter|round|bevel, miter? (limit, 1..=100), style?: solid|dashed|dotted, dash? ([on, off, ..] lengths; implies dashed), dash_offset?, dot_spacing? (implies dotted)";
|
||||
|
||||
/// The stroke style params (ADR 0046) applied to `base`, for a stroke `width` wide (which sizes
|
||||
/// a new dash pattern or dot spacing); `None` when none are given.
|
||||
pub fn opt_stroke_style(p: &Value, base: &anicraft_doc::StrokeStyle, width: f32) -> Result<Option<anicraft_doc::StrokeStyle>> {
|
||||
use anicraft_doc::stroke_style::{MAX_DASH_ENTRIES, MAX_DASH_LENGTH, MAX_MITER_LIMIT, MIN_MITER_LIMIT};
|
||||
use anicraft_doc::{Cap, Dash, DashKind, Join};
|
||||
let keys = ["cap", "join", "miter", "style", "dash", "dash_offset", "dot_spacing"];
|
||||
if !keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut st = base.clone();
|
||||
if let Some(c) = opt_str(p, "cap")? {
|
||||
st.cap = Cap::from_key(c).ok_or_else(|| bad("cap", "none, round or square"))?;
|
||||
}
|
||||
if let Some(j) = opt_str(p, "join")? {
|
||||
st.join = Join::from_key(j).ok_or_else(|| bad("join", "miter, round or bevel"))?;
|
||||
}
|
||||
if let Some(m) = opt_f32(p, "miter")? {
|
||||
if !(MIN_MITER_LIMIT..=MAX_MITER_LIMIT).contains(&m) {
|
||||
return Err(bad("miter", &format!("a miter limit in {MIN_MITER_LIMIT}..={MAX_MITER_LIMIT}")));
|
||||
}
|
||||
st.miter_limit = m;
|
||||
}
|
||||
let len_ok = |v: f32| (0.0..=MAX_DASH_LENGTH).contains(&v);
|
||||
let dash = match p.get("dash") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::Array(list)) => {
|
||||
if list.is_empty() || list.len() > MAX_DASH_ENTRIES {
|
||||
return Err(bad("dash", &format!("a list of 1 to {MAX_DASH_ENTRIES} lengths")));
|
||||
}
|
||||
let mut v = Vec::with_capacity(list.len());
|
||||
for x in list {
|
||||
match x.as_f64().filter(|f| f.is_finite()).map(|f| f as f32) {
|
||||
Some(f) if len_ok(f) => v.push(f),
|
||||
_ => return Err(bad("dash", &format!("lengths in 0..={MAX_DASH_LENGTH}"))),
|
||||
}
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
Some(_) => return Err(bad("dash", "a list of [on, off, ..] lengths")),
|
||||
};
|
||||
let offset = opt_f32(p, "dash_offset")?;
|
||||
if offset.is_some_and(|o| o.abs() > MAX_DASH_LENGTH) {
|
||||
return Err(bad("dash_offset", &format!("in -{MAX_DASH_LENGTH}..={MAX_DASH_LENGTH}")));
|
||||
}
|
||||
let spacing = opt_f32(p, "dot_spacing")?;
|
||||
if spacing.is_some_and(|s| !len_ok(s)) {
|
||||
return Err(bad("dot_spacing", &format!("in 0..={MAX_DASH_LENGTH}")));
|
||||
}
|
||||
let kind = match opt_str(p, "style")? {
|
||||
Some(k) => DashKind::from_key(k).ok_or_else(|| bad("style", "solid, dashed or dotted"))?,
|
||||
None if dash.is_some() || offset.is_some() => DashKind::Dashed,
|
||||
None if spacing.is_some() => DashKind::Dotted,
|
||||
None => st.dash_kind(),
|
||||
};
|
||||
// A new pattern is sized by the stroke: dashes three widths long with two-width gaps, dots
|
||||
// one width apart.
|
||||
let w = if width.is_finite() { width.clamp(0.0, MAX_DASH_LENGTH) } else { 1.0 };
|
||||
st.dash = match kind {
|
||||
DashKind::Solid => None,
|
||||
DashKind::Dashed => {
|
||||
let (lengths, old_offset) = match &st.dash {
|
||||
Some(Dash::Dashed { lengths, offset }) => (lengths.to_vec(), *offset),
|
||||
_ => (vec![(3.0 * w).max(2.0), (2.0 * w).max(2.0)], 0.0),
|
||||
};
|
||||
let lengths = dash.unwrap_or(lengths);
|
||||
let d = Dash::Dashed { lengths: lengths.into(), offset: offset.unwrap_or(old_offset) }.sanitized();
|
||||
Some(d.ok_or_else(|| bad("dash", "a pattern with a gap (some off length above 0)"))?)
|
||||
}
|
||||
DashKind::Dotted => {
|
||||
let old = match &st.dash {
|
||||
Some(Dash::Dotted { spacing }) => *spacing,
|
||||
_ => w.max(2.0),
|
||||
};
|
||||
Dash::dotted(spacing.unwrap_or(old))
|
||||
}
|
||||
};
|
||||
Ok(Some(st.sanitized()))
|
||||
}
|
||||
@@ -9,9 +9,9 @@
|
||||
//! its scripts, so a script that loops forever costs one frame's budget, then stops with a
|
||||
//! message.
|
||||
|
||||
use anicraft_doc::actions::{Action, MAX_ACTIONS, PluginScript, check_actions};
|
||||
use anicraft_doc::actions::{Action, CompileResult, FrameScript, MAX_ACTIONS, PluginScript, check_actions};
|
||||
use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step};
|
||||
use anicraft_doc::{Document, player};
|
||||
use anicraft_doc::{Document, LayerKind, SymbolKind, Timeline, player};
|
||||
use anicraft_geom::Vec2;
|
||||
use anicraft_plugins::{Host, Kind, Limits, Registry};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -187,8 +187,12 @@ pub const MAX_MOVIE_OUTPUT: usize = 10_000;
|
||||
pub const MAX_MOVIE_SOUNDS: usize = 4_096;
|
||||
|
||||
impl Movie {
|
||||
/// The movie at its first frame. The Output starts with a line for each kept script: which
|
||||
/// run and which are skipped and why (ADR 0013 tier 2), said once rather than each time the
|
||||
/// playhead passes.
|
||||
pub fn start(doc: &Document, scripts: &mut dyn ScriptHost) -> Movie {
|
||||
let mut m = Movie { state: PlayerState::default(), output: Vec::new(), sounds: Vec::new() };
|
||||
m.output.extend(script_summary(doc).into_iter().map(|l| (0, l)));
|
||||
let s = player::start(doc, scripts);
|
||||
m.take(s);
|
||||
m
|
||||
@@ -246,3 +250,70 @@ pub fn parse_events(v: &Value) -> Result<Vec<Event>, String> {
|
||||
other => return Err(format!("unknown event type '{other}' (move, down, up, click or leave)")),
|
||||
})
|
||||
}
|
||||
|
||||
/// A kept script (ADR 0013) and where it is.
|
||||
pub struct KeptScript<'a> {
|
||||
/// "Scene 1 › Actions, frame 1" (frames 1-based, as the app shows them).
|
||||
pub place: String,
|
||||
/// The timeline runs frame scripts there (a scene or a movie clip, on a layer that plays).
|
||||
pub plays: bool,
|
||||
pub compiled: &'a CompileResult,
|
||||
}
|
||||
|
||||
impl KeptScript<'_> {
|
||||
/// It runs when the movie plays.
|
||||
pub fn runs(&self) -> bool {
|
||||
self.plays && self.compiled.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Most kept scripts listed.
|
||||
pub const MAX_LISTED_SCRIPTS: usize = 1_000;
|
||||
|
||||
fn layer_plays(tl: &Timeline, index: usize) -> bool {
|
||||
tl.layers.get(index).is_some_and(|l| l.visible && !matches!(l.kind, LayerKind::Folder | LayerKind::Guide)) && !tl.hidden_by_folder(index)
|
||||
}
|
||||
|
||||
/// Every kept script in the document: the scenes' first, then the symbols'.
|
||||
pub fn kept_scripts(doc: &Document) -> Vec<KeptScript<'_>> {
|
||||
let scenes = doc.scenes.iter().map(|s| (s.name.as_str(), &s.timeline, true));
|
||||
let symbols = doc.library.iter().map(|s| (s.name.as_str(), &s.timeline, s.kind == SymbolKind::MovieClip));
|
||||
let mut out = Vec::new();
|
||||
for (name, tl, runs) in scenes.chain(symbols) {
|
||||
for (index, layer) in tl.layers.iter().enumerate() {
|
||||
for k in &layer.keyframes {
|
||||
let Some(FrameScript::Source(src)) = &k.script else { continue };
|
||||
if out.len() >= MAX_LISTED_SCRIPTS {
|
||||
return out;
|
||||
}
|
||||
out.push(KeptScript { place: format!("{name} › {}, frame {}", layer.name, u64::from(k.start) + 1), plays: runs && layer_plays(tl, index), compiled: src.compiled() });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The Output's opening lines: each kept script that runs (and what in it is ignored), and
|
||||
/// each that doesn't, with why.
|
||||
pub fn script_summary(doc: &Document) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
for k in kept_scripts(doc) {
|
||||
match (k.plays, k.compiled) {
|
||||
(false, _) => lines.push(format!("Frame script not run: {}: graphic and button timelines, guide layers and hidden layers don't run frame scripts", k.place)),
|
||||
(true, Ok(c)) => {
|
||||
lines.push(format!("Frame script runs: {}", k.place));
|
||||
lines.extend(c.notes.iter().map(|n| format!("Frame script at {}: {n}", k.place)));
|
||||
}
|
||||
(true, Err(problems)) => {
|
||||
let first = problems.first().map_or_else(String::new, ToString::to_string);
|
||||
let more = match problems.len() {
|
||||
0 | 1 => String::new(),
|
||||
2 => " (and 1 more problem: see the Actions panel)".into(),
|
||||
n => format!(" (and {} more problems: see the Actions panel)", n - 1),
|
||||
};
|
||||
lines.push(format!("Frame script not run: {}: {first}{more}", k.place));
|
||||
}
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
//! The Selection tool on raw shapes (ADR 0041) through the commands: bending, shared points,
|
||||
//! snapping and the marquee.
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{Element, ElementKind};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
/// A blank document drawing raw shapes, with a 100 × 80 rectangle (fill and outline) at the origin.
|
||||
fn rect_session() -> Session {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.object_drawing", json!({"on": false}));
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
s
|
||||
}
|
||||
|
||||
fn raw(s: &Session) -> Vec<Arc<Element>> {
|
||||
s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect()
|
||||
}
|
||||
|
||||
fn is_fill(e: &Element) -> bool {
|
||||
matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())
|
||||
}
|
||||
|
||||
fn count(s: &Session) -> (usize, usize) {
|
||||
let r = raw(s);
|
||||
(r.iter().filter(|e| is_fill(e)).count(), r.iter().filter(|e| !is_fill(e)).count())
|
||||
}
|
||||
|
||||
fn polylines(e: &Element) -> Vec<anicraft_geom::Polyline> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.path.flatten(&e.transform, 0.01),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn area(e: &Element) -> f32 {
|
||||
polylines(e)
|
||||
.iter()
|
||||
.map(|pl| {
|
||||
let n = pl.points.len();
|
||||
(0..n).map(|i| pl.points[i].cross(pl.points[(i + 1) % n])).sum::<f32>() * 0.5
|
||||
})
|
||||
.sum::<f32>()
|
||||
.abs()
|
||||
}
|
||||
|
||||
fn length(e: &Element) -> f32 {
|
||||
polylines(e).iter().map(|pl| pl.points.windows(2).map(|w| w[0].distance(w[1])).sum::<f32>()).sum()
|
||||
}
|
||||
|
||||
fn fill_area(s: &Session) -> f32 {
|
||||
raw(s).iter().filter(|e| is_fill(e)).map(|e| area(e)).sum()
|
||||
}
|
||||
|
||||
/// Stage-space anchors of a raw shape.
|
||||
fn anchors(e: &Element) -> Vec<Vec2> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.path.anchors().into_iter().map(|(_, p)| e.transform.apply(p)).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every stroke end lies on a fill corner or another stroke's end: the drawing is still joined
|
||||
/// (for drawings without loose ends).
|
||||
fn joined(s: &Session) -> bool {
|
||||
let r = raw(s);
|
||||
let corners: Vec<Vec2> = r.iter().flat_map(|e| anchors(e)).collect();
|
||||
r.iter().filter(|e| !is_fill(e)).all(|e| {
|
||||
let a = anchors(e);
|
||||
[a.first(), a.last()].into_iter().flatten().all(|p| corners.iter().filter(|q| q.distance(*p) < 1e-3).count() >= 2)
|
||||
})
|
||||
}
|
||||
|
||||
fn has_anchor(s: &Session, p: Vec2) -> usize {
|
||||
raw(s).iter().filter(|e| anchors(e).iter().any(|q| q.distance(p) < 1e-3)).count()
|
||||
}
|
||||
|
||||
// ----- bending -----------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn dragging_a_segment_bends_it_through_the_dragged_point_and_the_fill_follows() {
|
||||
let mut s = rect_session();
|
||||
let history = s.history_len();
|
||||
// Drag the top edge's middle up 30: the edge becomes a curve through (50, −30).
|
||||
let r = run(&mut s, "path.bend_segment", json!({"x": 50, "y": 0, "dx": 0, "dy": -30}));
|
||||
assert_eq!(r["merged"], true);
|
||||
assert!((r["x"].as_f64().unwrap_or(0.0) - 50.0).abs() < 1e-3 && (r["y"].as_f64().unwrap_or(0.0) + 30.0).abs() < 1e-3, "{r}");
|
||||
assert_eq!(count(&s), (1, 4), "still a fill and four sides");
|
||||
// The top is a curve through the dragged point.
|
||||
let top = raw(&s).into_iter().find(|e| !is_fill(e) && polylines(e).iter().any(|pl| pl.points.iter().any(|p| p.y < -29.0)));
|
||||
let Some(top) = top else { panic!("no bent stroke") };
|
||||
// (A symmetric pull: the dragged point is the curve's peak.)
|
||||
let peak = polylines(&top).iter().flat_map(|pl| pl.points.clone()).min_by(|a, b| a.y.total_cmp(&b.y)).unwrap_or(Vec2::ZERO);
|
||||
assert!((peak.y + 30.0).abs() < 0.02 && (peak.x - 50.0).abs() < 2.0, "the curve peaks at the dragged point: {peak:?}");
|
||||
// The fill bulges with it, by exactly the area under the cubic: L·(h₁ + h₂)/4 with both
|
||||
// handles raised 40 (a pull of 30 at the middle needs 30 / 0.75).
|
||||
assert!((fill_area(&s) - (8000.0 + 100.0 * 80.0 / 4.0)).abs() < 2.0, "{}", fill_area(&s));
|
||||
assert!(joined(&s));
|
||||
// One undo step takes it back.
|
||||
assert_eq!(s.history_len(), history + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!((fill_area(&s) - 8000.0).abs() < 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_straight_segment_stays_straight_until_it_is_dragged() {
|
||||
let mut s = rect_session();
|
||||
run(&mut s, "path.bend_segment", json!({"x": 50, "y": 0, "dx": 0, "dy": -30}));
|
||||
// The other three sides are still lines.
|
||||
let lines = raw(&s).iter().filter(|e| !is_fill(e)).filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.path.cmds.iter().all(|c| !matches!(c, anicraft_geom::PathCmd::CubicTo(..))))).count();
|
||||
assert_eq!(lines, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_in_steps_bends_like_one_move_and_merges_at_the_end() {
|
||||
let mut s = rect_session();
|
||||
s.begin_gesture("Bend");
|
||||
let first = run(&mut s, "path.bend_segment", json!({"x": 100, "y": 40, "dx": 10, "dy": 0, "merge": false}));
|
||||
let (id, cmd, t) = (first["id"].clone(), first["cmd"].clone(), first["t"].clone());
|
||||
// Later steps name the segment and pass the point where it now is.
|
||||
run(&mut s, "path.bend_segment", json!({"x": 110, "y": 40, "dx": 10, "dy": 0, "id": id, "cmd": cmd, "t": t, "merge": false}));
|
||||
let ids: Vec<u64> = raw(&s).iter().map(|e| e.id.0).collect();
|
||||
run(&mut s, "raw.merge", json!({"ids": ids}));
|
||||
s.end_gesture();
|
||||
let far = raw(&s).iter().flat_map(|e| polylines(e)).flat_map(|pl| pl.points).fold(0.0f32, |m, p| m.max(p.x));
|
||||
assert!((far - 120.0).abs() < 0.1, "the side's middle went to x = 120: {far}");
|
||||
assert!(joined(&s));
|
||||
assert!((fill_area(&s) - (8000.0 + 80.0 * (2.0 * 20.0 / 0.75) / 4.0)).abs() < 2.0, "{}", fill_area(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bending_an_object_bends_only_it() {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#00ff00", "stroke": null}));
|
||||
let r = run(&mut s, "path.bend_segment", json!({"x": 0, "y": 40, "dx": -20, "dy": 0}));
|
||||
assert_eq!(r["merged"], false);
|
||||
assert_eq!(r["changed"].as_array().map(Vec::len), Some(1), "objects don't share edges");
|
||||
// The closing edge of an object's outline can be bent too.
|
||||
let areas: Vec<f32> = s.visible_elements().iter().map(|e| area(e)).collect();
|
||||
assert!(areas.iter().any(|a| (a - 8000.0).abs() < 0.5) && areas.iter().any(|a| (a - (8000.0 + 80.0 * (40.0 / 0.75) / 4.0)).abs() < 2.0), "{areas:?}");
|
||||
}
|
||||
|
||||
// ----- shared points ------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn moving_a_corner_moves_every_shape_that_shares_it() {
|
||||
let mut s = rect_session();
|
||||
let history = s.history_len();
|
||||
let r = run(&mut s, "raw.move_point", json!({"x": 100, "y": 0, "to_x": 130, "to_y": -20}));
|
||||
assert_eq!(r["moved"], 3, "the fill and the two sides that meet there: {r}");
|
||||
let to = Vec2::new(130.0, -20.0);
|
||||
assert_eq!(has_anchor(&s, Vec2::new(100.0, 0.0)), 0, "nothing stays behind");
|
||||
assert_eq!(has_anchor(&s, to), 3);
|
||||
assert!(joined(&s));
|
||||
// The fill is the quadrilateral through the new corner (shoelace).
|
||||
let quad = [Vec2::new(0.0, 0.0), to, Vec2::new(100.0, 80.0), Vec2::new(0.0, 80.0)];
|
||||
let want = (0..4).map(|i| quad[i].cross(quad[(i + 1) % 4])).sum::<f32>().abs() * 0.5;
|
||||
assert!((fill_area(&s) - want).abs() < 0.5, "{} vs {want}", fill_area(&s));
|
||||
assert_eq!(s.history_len(), history + 1, "one undo step");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(has_anchor(&s, Vec2::new(100.0, 0.0)), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_ending_on_an_edge_drags_the_edge_with_it() {
|
||||
let mut s = rect_session();
|
||||
// A line from inside the rectangle up to its top edge: they meet at (50, 0).
|
||||
run(&mut s, "draw.line", json!({"x0": 50, "y0": -40, "x1": 50, "y1": 0, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let r = run(&mut s, "raw.move_point", json!({"x": 50, "y": -40, "to_x": 50, "to_y": -60}));
|
||||
assert_eq!(r["moved"], 1, "a free end moves alone");
|
||||
// The point where it meets the edge: the fill and both halves of the top move with it.
|
||||
let r = run(&mut s, "raw.move_point", json!({"x": 50, "y": 0, "to_x": 50, "to_y": 10}));
|
||||
assert!(r["moved"].as_u64().unwrap_or(0) >= 3, "{r}");
|
||||
assert!(has_anchor(&s, Vec2::new(50.0, 10.0)) >= 3);
|
||||
assert_eq!(has_anchor(&s, Vec2::new(50.0, 0.0)), 0, "nothing stays behind");
|
||||
// The fill lost the triangle the dent took: 100 wide, 10 deep.
|
||||
assert!((fill_area(&s) - (8000.0 - 0.5 * 100.0 * 10.0)).abs() < 0.5, "{}", fill_area(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_drag_passes_its_points_on_and_merges_at_the_end() {
|
||||
let mut s = rect_session();
|
||||
s.begin_gesture("Move Point");
|
||||
let r = run(&mut s, "raw.move_point", json!({"x": 0, "y": 80, "to_x": -5, "to_y": 85, "merge": false}));
|
||||
let points = r["points"].clone();
|
||||
assert_eq!(points.as_array().map(Vec::len), Some(3));
|
||||
run(&mut s, "raw.move_point", json!({"x": -5, "y": 85, "to_x": -10, "to_y": 90, "points": points, "merge": false}));
|
||||
let ids: Vec<u64> = raw(&s).iter().map(|e| e.id.0).collect();
|
||||
run(&mut s, "raw.merge", json!({"ids": ids}));
|
||||
s.end_gesture();
|
||||
assert_eq!(has_anchor(&s, Vec2::new(-10.0, 90.0)), 3);
|
||||
assert!(joined(&s));
|
||||
}
|
||||
|
||||
// ----- snapping -------------------------------------------------------------------------------------
|
||||
|
||||
/// A raw rectangle and a separate raw line whose free end is dragged.
|
||||
fn snap_session() -> Session {
|
||||
let mut s = rect_session();
|
||||
run(&mut s, "draw.line", json!({"x0": 200, "y0": 0, "x1": 300, "y1": 0, "stroke": "#0000ff"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dragged_point_snaps_within_ten_screen_pixels_at_any_zoom() {
|
||||
// The drop point is 8 document units from the rectangle's corner (100, 0).
|
||||
let drop = json!({"x": 200, "y": 0, "to_x": 108, "to_y": 0});
|
||||
for (zoom, snaps) in [(1.0, true), (2.0, false), (0.5, true), (4.0, false), (0.8, true)] {
|
||||
let mut s = snap_session();
|
||||
let mut p = drop.clone();
|
||||
p["snap"] = json!(10.0 / zoom);
|
||||
let r = run(&mut s, "raw.move_point", p);
|
||||
assert_eq!(r["snapped"].is_object(), snaps, "zoom {zoom}: {r}");
|
||||
if snaps {
|
||||
assert_eq!(r["snapped"]["to"], "point");
|
||||
assert_eq!(has_anchor(&s, Vec2::new(100.0, 0.0)), 4, "zoom {zoom}: the line's end joined the corner");
|
||||
} else {
|
||||
assert_eq!(has_anchor(&s, Vec2::new(108.0, 0.0)), 1, "zoom {zoom}: where it was let go");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dragged_point_snaps_onto_a_line_without_changing_the_line() {
|
||||
let mut s = snap_session();
|
||||
// 6 units below the rectangle's bottom edge, away from its corners.
|
||||
let r = run(&mut s, "raw.move_point", json!({"x": 200, "y": 0, "to_x": 40, "to_y": 86, "snap": 10}));
|
||||
assert_eq!(r["snapped"]["to"], "line", "{r}");
|
||||
assert!((r["y"].as_f64().unwrap_or(0.0) - 80.0).abs() < 1e-3);
|
||||
// The bottom is still straight along y = 80 and the fill the same.
|
||||
assert!((fill_area(&s) - 8000.0).abs() < 0.5, "{}", fill_area(&s));
|
||||
let bottom: Vec<Vec2> = raw(&s).iter().flat_map(|e| anchors(e)).filter(|p| (p.y - 80.0).abs() < 1.0).collect();
|
||||
assert!(bottom.iter().all(|p| (p.y - 80.0).abs() < 1e-3), "{bottom:?}");
|
||||
assert!(has_anchor(&s, Vec2::new(40.0, 80.0)) >= 2, "the edge gained a point where the line meets it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dragged_selection_snaps_its_nearest_corner() {
|
||||
let mut s = snap_session();
|
||||
// Select the loose line and drag it by its left end towards the rectangle's corner.
|
||||
run(&mut s, "element.pick", json!({"x": 250, "y": 0}));
|
||||
let r = run(&mut s, "element.translate", json!({"dx": -93, "dy": 4, "snap": 10, "from": [107, 4]}));
|
||||
assert_eq!(r["snapped"]["to"], "point", "{r}");
|
||||
assert!((r["dx"].as_f64().unwrap_or(0.0) + 100.0).abs() < 1e-3 && r["dy"].as_f64().unwrap_or(1.0).abs() < 1e-3, "{r}");
|
||||
// Out of reach, nothing snaps.
|
||||
let r = run(&mut s, "element.translate", json!({"dx": 0, "dy": -40, "snap": 10, "from": [100, -40]}));
|
||||
assert!(r["snapped"].is_null(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_key_nudges_join_ends_within_point_two_at_their_midpoint() {
|
||||
let mut s = snap_session();
|
||||
// Nudge the loose line left until its end is 0.15 from the corner (100, 0) and drop it, as
|
||||
// the arrow keys do at 1000 % (0.1 per press).
|
||||
run(&mut s, "element.pick", json!({"x": 250, "y": 0}));
|
||||
run(&mut s, "element.translate", json!({"dx": -99.85, "dy": 0}));
|
||||
run(&mut s, "draw.drop", json!({}));
|
||||
let mid = Vec2::new(100.075, 0.0);
|
||||
assert_eq!(has_anchor(&s, mid), 4, "the corner and the end meet halfway");
|
||||
assert_eq!(has_anchor(&s, Vec2::new(100.0, 0.0)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_key_nudges_put_an_end_onto_a_line_that_stays_straight() {
|
||||
let mut s = rect_session();
|
||||
run(&mut s, "draw.line", json!({"x0": 40, "y0": -60, "x1": 40, "y1": -10, "stroke": "#0000ff"}));
|
||||
// Down until the end is 0.12 above the top edge, then let go.
|
||||
run(&mut s, "element.translate", json!({"dx": 0, "dy": 9.88}));
|
||||
run(&mut s, "draw.drop", json!({}));
|
||||
let top: Vec<Vec2> = raw(&s).iter().flat_map(|e| anchors(e)).filter(|p| p.y.abs() < 1.0).collect();
|
||||
assert!(top.iter().all(|p| p.y.abs() < 1e-4), "the top stays on y = 0: {top:?}");
|
||||
assert!(has_anchor(&s, Vec2::new(40.0, 0.0)) >= 2, "the end is on the edge");
|
||||
assert!((fill_area(&s) - 8000.0).abs() < 0.5);
|
||||
}
|
||||
|
||||
// ----- the marquee ----------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_marquee_selects_the_parts_under_it_and_the_parts_add_up() {
|
||||
let mut s = rect_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 20, "h": 20, "object": true}));
|
||||
run(&mut s, "draw.rect", json!({"x": 150, "y": 50, "w": 200, "h": 10, "object": true}));
|
||||
let history = s.history_len();
|
||||
let dirty = s.is_dirty();
|
||||
// The right half of the rectangle, the small object wholly, the long one not.
|
||||
let r = run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 330, "y1": 45}));
|
||||
assert_eq!(r["cut"], 3, "part of the fill, of the top and of the right side: {r}");
|
||||
let sel = s.selection.clone();
|
||||
let els = s.visible_elements();
|
||||
let chosen: Vec<&Arc<Element>> = els.iter().filter(|e| sel.has_id(e.id)).collect();
|
||||
assert!(chosen.iter().any(|e| matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge && (area(e) - 400.0).abs() < 0.5)), "the object inside");
|
||||
assert!(!chosen.iter().any(|e| (area(e) - 2000.0).abs() < 0.5), "not the one across the edge");
|
||||
// Inside: 50 × 45 of the fill (y from 0 to 45), the right side's upper 45 and the top's
|
||||
// right 50.
|
||||
let inside: f32 = chosen.iter().filter(|e| is_fill(e) && matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).map(|e| area(e)).sum();
|
||||
assert!((inside - 50.0 * 45.0).abs() < 0.5, "{inside}");
|
||||
let lines: f32 = chosen.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_none())).map(|e| length(e)).sum();
|
||||
assert!((lines - 95.0).abs() < 0.05, "{lines}");
|
||||
// Inside and outside add up to the whole.
|
||||
assert!((fill_area(&s) - 8000.0).abs() < 0.5, "{}", fill_area(&s));
|
||||
let total: f32 = raw(&s).iter().filter(|e| !is_fill(e)).map(|e| length(e)).sum();
|
||||
assert!((total - 360.0).abs() < 0.05, "{total}");
|
||||
// Selecting is not an edit: no undo step, and a saved document stays saved.
|
||||
assert_eq!(s.history_len(), history);
|
||||
assert_eq!(s.is_dirty(), dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letting_go_of_a_marquee_puts_the_drawing_back_whole() {
|
||||
let mut s = rect_session();
|
||||
s.mark_saved();
|
||||
let history = s.history_len();
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200}));
|
||||
assert_eq!(count(&s), (2, 6));
|
||||
assert!(!s.is_dirty());
|
||||
// Clicking empty space: the cut goes, the drawing is as it was.
|
||||
run(&mut s, "element.pick", json!({"x": 500, "y": 500}));
|
||||
assert_eq!(count(&s), (1, 4));
|
||||
assert!(!s.is_dirty());
|
||||
assert_eq!(s.history_len(), history, "a marquee is not an edit");
|
||||
// Clicking the part outside selects the whole shape it came from.
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200}));
|
||||
run(&mut s, "element.pick", json!({"x": 20, "y": 40}));
|
||||
assert_eq!(count(&s), (1, 4));
|
||||
assert_eq!(s.selection.len(), 1);
|
||||
assert!(raw(&s).iter().any(|e| s.selection.has_id(e.id) && is_fill(e) && (area(e) - 8000.0).abs() < 0.5));
|
||||
// A new marquee replaces the old one.
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200}));
|
||||
run(&mut s, "raw.select_rect", json!({"x0": -20, "y0": -20, "x1": 50, "y1": 40}));
|
||||
assert_eq!(count(&s), (2, 6), "cut once, at the new marquee (the corner: a fill and two sides)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_marquee_parts_is_one_undo_step_from_the_whole_drawing() {
|
||||
let mut s = rect_session();
|
||||
let history = s.history_len();
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200}));
|
||||
s.begin_gesture("Move");
|
||||
run(&mut s, "element.translate", json!({"dx": 40, "dy": 0}));
|
||||
run(&mut s, "draw.drop", json!({}));
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), history + 1);
|
||||
// The right half moved away; the left half stayed.
|
||||
assert!((fill_area(&s) - 8000.0).abs() < 0.5);
|
||||
let far = raw(&s).iter().flat_map(|e| anchors(e)).fold(0.0f32, |m, p| m.max(p.x));
|
||||
assert!((far - 140.0).abs() < 1e-3, "{far}");
|
||||
// Undo goes straight back to the whole rectangle.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(count(&s), (1, 4));
|
||||
assert!((fill_area(&s) - 8000.0).abs() < 0.5);
|
||||
// Deleting parts is an edit too.
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200}));
|
||||
run(&mut s, "edit.delete", json!({}));
|
||||
assert!((fill_area(&s) - 4000.0).abs() < 0.5, "{}", fill_area(&s));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(count(&s), (1, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_marquees_add_parts() {
|
||||
let mut s = rect_session();
|
||||
run(&mut s, "raw.select_rect", json!({"x0": -20, "y0": -20, "x1": 30, "y1": 30}));
|
||||
let first = s.selection.len();
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 70, "y0": 50, "x1": 130, "y1": 100, "add": true}));
|
||||
assert!(s.selection.len() > first);
|
||||
assert!((fill_area(&s) - 8000.0).abs() < 0.5);
|
||||
// Letting go heals both cuts.
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
assert_eq!(count(&s), (1, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marquee_over_a_whole_raw_shape_selects_it_without_cutting() {
|
||||
let mut s = rect_session();
|
||||
let r = run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": -10, "x1": 110, "y1": 90}));
|
||||
assert_eq!(r["cut"], 0);
|
||||
assert_eq!(s.selection.len(), 5);
|
||||
assert_eq!(count(&s), (1, 4));
|
||||
}
|
||||
|
||||
// ----- what a drag takes ------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_selection_tool_knows_corners_segments_and_fills() {
|
||||
let mut s = rect_session();
|
||||
let kind = |s: &mut Session, x: f32, y: f32| run(s, "raw.hit", json!({"x": x, "y": y, "slop": 3, "point_slop": 5}))["kind"].clone();
|
||||
assert_eq!(kind(&mut s, 101.0, 2.0), "point", "a corner");
|
||||
assert_eq!(kind(&mut s, 50.0, 1.0), "segment", "an edge");
|
||||
assert_eq!(kind(&mut s, 50.0, 40.0), "fill");
|
||||
assert_eq!(kind(&mut s, 500.0, 40.0), Value::Null);
|
||||
// Once selected, a drag moves it.
|
||||
run(&mut s, "element.pick", json!({"x": 50, "y": 40}));
|
||||
assert_eq!(kind(&mut s, 50.0, 40.0), "object");
|
||||
// An object is an object anywhere on it.
|
||||
run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 20, "h": 20, "object": true}));
|
||||
assert_eq!(kind(&mut s, 300.0, 0.0), "object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_a_fill_moves_only_the_fill() {
|
||||
let mut s = rect_session();
|
||||
// The click-and-drag on a fill: it is selected alone, moved and dropped.
|
||||
run(&mut s, "element.pick", json!({"x": 50, "y": 40}));
|
||||
assert_eq!(s.selection.len(), 1);
|
||||
run(&mut s, "element.translate", json!({"dx": 0, "dy": 200}));
|
||||
run(&mut s, "draw.drop", json!({}));
|
||||
// The outline stayed where it was, now with nothing inside.
|
||||
let strokes: Vec<Vec2> = raw(&s).iter().filter(|e| !is_fill(e)).flat_map(|e| anchors(e)).collect();
|
||||
assert!(strokes.iter().all(|p| p.y <= 80.0 + 1e-3), "{strokes:?}");
|
||||
let fills: Vec<Vec2> = raw(&s).iter().filter(|e| is_fill(e)).flat_map(|e| anchors(e)).collect();
|
||||
assert!(fills.iter().all(|p| p.y >= 200.0 - 1e-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_edits_never_panic_on_odd_input() {
|
||||
let mut s = rect_session();
|
||||
for (id, p) in [
|
||||
("path.bend_segment", json!({"x": 50, "y": 0, "dx": 1e7, "dy": -1e7})),
|
||||
("path.bend_segment", json!({"x": 50, "y": 0, "dx": 1, "dy": 1, "id": 999_999})),
|
||||
("path.bend_segment", json!({"x": 50, "y": 0, "dx": 1, "dy": 1, "cmd": 99, "t": 0.5, "id": raw(&s)[1].id.0})),
|
||||
("raw.move_point", json!({"x": 0, "y": 0, "to_x": 1e7, "to_y": 1e7})),
|
||||
("raw.move_point", json!({"x": 0, "y": 0, "to_x": 1, "to_y": 1, "points": [[1, 2], [3]]})),
|
||||
("raw.move_point", json!({"x": 0, "y": 0, "to_x": 1, "to_y": 1, "points": []})),
|
||||
("raw.move_point", json!({"x": 0, "y": 0, "to_x": 1, "to_y": 1, "points": [[u64::MAX, u64::MAX]]})),
|
||||
("raw.select_rect", json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0})),
|
||||
("raw.select_rect", json!({"x0": -1e7, "y0": -1e7, "x1": 1e7, "y1": 1e7})),
|
||||
("raw.merge", json!({"ids": [u64::MAX]})),
|
||||
] {
|
||||
let _ = s.execute(id, &p);
|
||||
}
|
||||
let _ = anicraft_render::render_frame(&s.doc, 0, 0.1);
|
||||
let _ = Affine::IDENTITY;
|
||||
}
|
||||
|
||||
/// Per-frame cost of the Selection tool's drags on a busy raw drawing (run by hand:
|
||||
/// `cargo test -p anicraft-engine raw_drag_timings -- --ignored --nocapture`).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn raw_drag_timings() {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.object_drawing", json!({"on": false}));
|
||||
// 12 × 12 outlined squares, and lines across every row: 144 fills, ~1,000 stroke pieces.
|
||||
for i in 0..12 {
|
||||
for j in 0..12 {
|
||||
run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
}
|
||||
run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"}));
|
||||
}
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let n = s.visible_elements().len();
|
||||
let time = |s: &mut Session, label: &str, f: &dyn Fn(&mut Session)| {
|
||||
let t = std::time::Instant::now();
|
||||
let reps = 20;
|
||||
for _ in 0..reps {
|
||||
f(s);
|
||||
}
|
||||
eprintln!("{label}: {:.2} ms", t.elapsed().as_secs_f64() * 1000.0 / f64::from(reps));
|
||||
};
|
||||
eprintln!("{n} raw shapes");
|
||||
time(&mut s, "raw_grab (hover)", &|s| {
|
||||
let _ = s.raw_grab(Vec2::new(300.0, 300.0), 3.0, 6.0);
|
||||
});
|
||||
s.begin_gesture("Bend");
|
||||
time(&mut s, "bend frame (no merge)", &|s| {
|
||||
let _ = s.execute("path.bend_segment", &json!({"x": 320, "y": 300, "dx": 0, "dy": -0.5, "merge": false}));
|
||||
});
|
||||
s.end_gesture();
|
||||
let r = run(&mut s, "raw.move_point", json!({"x": 340, "y": 340, "to_x": 341, "to_y": 341, "snap": 10, "merge": false}));
|
||||
let points = r["points"].clone();
|
||||
time(&mut s, "point frame with snapping", &|s| {
|
||||
let _ = s.execute("raw.move_point", &json!({"x": 341, "y": 341, "to_x": 341, "to_y": 341, "snap": 10, "points": points, "merge": false}));
|
||||
});
|
||||
// Once: it replaces the shapes it merges.
|
||||
let ids: Vec<Value> = points.as_array().into_iter().flatten().map(|p| p[0].clone()).collect();
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "raw.merge", json!({"ids": ids}));
|
||||
eprintln!("merge at release: {:.2} ms", t.elapsed().as_secs_f64() * 1000.0);
|
||||
time(&mut s, "marquee cut and heal", &|s| {
|
||||
let _ = s.execute("raw.select_rect", &json!({"x0": 125, "y0": 125, "x1": 425, "y1": 425}));
|
||||
let _ = s.execute("edit.deselect", &json!({}));
|
||||
});
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 0, "y0": 0, "x1": 45, "y1": 45}));
|
||||
time(&mut s, "selection move frame with snapping", &|s| {
|
||||
let _ = s.execute("element.translate", &json!({"dx": 0.5, "dy": 0, "snap": 10, "from": [10, 10]}));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Subselection on raw shapes and merging everywhere (ADR 0042), through the commands.
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{Element, ElementKind, GradientStop, Paint, Rgba};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn raw_session() -> Session {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.object_drawing", json!({"on": false}));
|
||||
s
|
||||
}
|
||||
|
||||
fn raw(s: &Session) -> Vec<Arc<Element>> {
|
||||
s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect()
|
||||
}
|
||||
|
||||
fn fills(s: &Session) -> Vec<Arc<Element>> {
|
||||
raw(s).into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).collect()
|
||||
}
|
||||
|
||||
fn area(e: &Element) -> f32 {
|
||||
let ElementKind::Shape(sh) = &e.kind else { return 0.0 };
|
||||
sh.path
|
||||
.flatten(&e.transform, 0.01)
|
||||
.iter()
|
||||
.map(|pl| {
|
||||
let n = pl.points.len();
|
||||
(0..n).map(|i| pl.points[i].cross(pl.points[(i + 1) % n])).sum::<f32>() * 0.5
|
||||
})
|
||||
.sum::<f32>()
|
||||
.abs()
|
||||
}
|
||||
|
||||
fn fill_color(e: &Element) -> Option<Rgba> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(sh) => match &sh.fill {
|
||||
Some(Paint::Solid(c)) => Some(*c),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ids(v: &Value, key: &str) -> Vec<u64> {
|
||||
v[key].as_array().into_iter().flatten().filter_map(Value::as_u64).collect()
|
||||
}
|
||||
|
||||
fn xy(v: &Value) -> Vec<Vec2> {
|
||||
v.as_array().into_iter().flatten().filter_map(|p| Some(Vec2::new(p.get(0)?.as_f64()? as f32, p.get(1)?.as_f64()? as f32))).collect()
|
||||
}
|
||||
|
||||
fn has(points: &[Vec2], p: (f32, f32)) -> bool {
|
||||
points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 1e-2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_shows_the_anchors_of_everything_connected_once_each() {
|
||||
let mut s = raw_session();
|
||||
// An outlined rectangle, a line from its corner, and a line far away.
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
run(&mut s, "draw.line", json!({"x0": 100, "y0": 80, "x1": 160, "y1": 140, "stroke": "#000000"}));
|
||||
run(&mut s, "draw.line", json!({"x0": 300, "y0": 0, "x1": 400, "y1": 0, "stroke": "#000000"}));
|
||||
// Fill, four sides, the joined line: six shapes. The far line is not connected.
|
||||
assert_eq!(raw(&s).len(), 7);
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 0}));
|
||||
assert_eq!(v["raw"], json!(true));
|
||||
assert_eq!(ids(&v, "selected").len(), 6, "{v}");
|
||||
let anchors = xy(&v["anchors"]);
|
||||
assert_eq!(anchors.len(), 5, "four corners shared by fill and sides, and the line's far end: {anchors:?}");
|
||||
for p in [(0.0, 0.0), (100.0, 0.0), (100.0, 80.0), (0.0, 80.0), (160.0, 140.0)] {
|
||||
assert!(has(&anchors, p), "{p:?} in {anchors:?}");
|
||||
}
|
||||
// The clicked edge's ends (whose handles show).
|
||||
let ends = xy(&v["ends"]);
|
||||
assert!(has(&ends, (0.0, 0.0)) && has(&ends, (100.0, 0.0)), "{ends:?}");
|
||||
// Straight edges have no handles.
|
||||
assert!(v["handles"].as_array().is_some_and(Vec::is_empty));
|
||||
// Inside the fill: the same set, no edge.
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40}));
|
||||
assert_eq!(ids(&v, "selected").len(), 6);
|
||||
assert!(xy(&v["ends"]).is_empty());
|
||||
// The far line alone.
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 350, "y": 0}));
|
||||
assert_eq!(ids(&v, "selected").len(), 1);
|
||||
assert_eq!(xy(&v["anchors"]).len(), 2);
|
||||
// Shift adds; empty space clears.
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40, "add": true}));
|
||||
assert_eq!(ids(&v, "selected").len(), 7);
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 700, "y": 700}));
|
||||
assert!(ids(&v, "selected").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_that_meet_along_an_edge_and_lines_ending_on_an_edge_are_connected() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null}));
|
||||
// A line standing on the blue square's top edge (a T-junction, not a corner).
|
||||
run(&mut s, "draw.line", json!({"x0": 150, "y0": 0, "x1": 150, "y1": -50, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(ids(&v, "selected").len(), 3, "red, blue and the line: {v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_a_handle_changes_the_curve_in_both_shapes_that_share_it() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.ellipse", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 50}));
|
||||
let handles = v["handles"].as_array().cloned().unwrap_or_default();
|
||||
// A circle of four arcs: two handles per arc, each listed once although the fill and the
|
||||
// outline both have it.
|
||||
assert_eq!(handles.len(), 8, "{v}");
|
||||
let h = &handles[0];
|
||||
let (id, cmd, slot) = (h["id"].as_u64().unwrap(), h["cmd"].as_u64().unwrap(), h["slot"].as_u64().unwrap());
|
||||
let before: Vec<Arc<Element>> = raw(&s);
|
||||
s.begin_gesture("Move Handle");
|
||||
let r = run(&mut s, "raw.move_handle", json!({"id": id, "cmd": cmd, "slot": slot, "dx": 20, "dy": -15, "merge": false}));
|
||||
assert_eq!(ids(&r, "changed").len(), 2, "the fill and its outline: {r}");
|
||||
// The edge moved the same way in both: the outline still runs along the fill's edge (to
|
||||
// within the flattening `distance_to_edge` measures with).
|
||||
let changed: Vec<Arc<Element>> = raw(&s).into_iter().filter(|e| ids(&r, "changed").contains(&e.id.0)).collect();
|
||||
let (fill, line) = match (changed.iter().find(|e| fill_color(e).is_some()), changed.iter().find(|e| fill_color(e).is_none())) {
|
||||
(Some(f), Some(l)) => (f.clone(), l.clone()),
|
||||
_ => panic!("a fill and a line changed"),
|
||||
};
|
||||
let ElementKind::Shape(ls) = &line.kind else { panic!() };
|
||||
let ElementKind::Shape(fs) = &fill.kind else { panic!() };
|
||||
for pl in ls.path.flatten(&line.transform, 0.05) {
|
||||
for p in pl.points {
|
||||
assert!(fs.path.distance_to_edge(p, &fill.transform) < 0.3, "{p:?} off the fill's edge");
|
||||
}
|
||||
}
|
||||
assert!(area(&fill) != area(before.iter().find(|e| fill_color(e).is_some()).unwrap()));
|
||||
// Release: they merge again, still joined, in one undo step.
|
||||
run(&mut s, "raw.merge", json!({"ids": ids(&r, "changed")}));
|
||||
s.end_gesture();
|
||||
assert_eq!(fills(&s).len(), 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(raw(&s).iter().map(|e| e.id).collect::<Vec<_>>(), before.iter().map(|e| e.id).collect::<Vec<_>>());
|
||||
// Straight segments have no handles to move.
|
||||
let mut t = raw_session();
|
||||
run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "fill": "#ff0000", "stroke": null}));
|
||||
let id = raw(&t)[0].id.0;
|
||||
assert!(t.execute("raw.move_handle", &json!({"id": id, "cmd": 1, "slot": 1, "dx": 1, "dy": 1})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_anchors_move_together_with_every_shape_that_shares_them() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
// The top edge's two corners, 10 px up (the arrow keys, Shift: one step, merged).
|
||||
run(&mut s, "raw.move_point", json!({"x": 0, "y": 0, "to_x": 0, "to_y": -10, "with": [[100, 0]]}));
|
||||
let f = fills(&s);
|
||||
assert_eq!(f.len(), 1);
|
||||
assert!((area(&f[0]) - 100.0 * 90.0).abs() < 0.5, "{}", area(&f[0]));
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40}));
|
||||
let anchors = xy(&v["anchors"]);
|
||||
assert!(has(&anchors, (0.0, -10.0)) && has(&anchors, (100.0, -10.0)) && anchors.len() == 4, "{anchors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_marquee_takes_whole_connected_shapes_on_the_active_layer_and_selects_the_anchors_inside() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
run(&mut s, "draw.line", json!({"x0": 300, "y0": 0, "x1": 400, "y1": 0, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
// Over the bottom-right corner only.
|
||||
let v = run(&mut s, "raw.subselect_rect", json!({"x0": 90, "y0": 70, "x1": 120, "y1": 100}));
|
||||
assert_eq!(ids(&v, "selected").len(), 5, "the fill and its four sides: {v}");
|
||||
let inside = xy(&v["anchors"]);
|
||||
assert_eq!(inside.len(), 1);
|
||||
assert!(has(&inside, (100.0, 80.0)));
|
||||
// Through the middle of the fill, no anchors inside: the shapes, no anchors.
|
||||
let v = run(&mut s, "raw.subselect_rect", json!({"x0": 40, "y0": 30, "x1": 60, "y1": 50}));
|
||||
assert_eq!(ids(&v, "selected").len(), 5);
|
||||
assert!(xy(&v["anchors"]).is_empty());
|
||||
// Another layer is not reached.
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
let v = run(&mut s, "raw.subselect_rect", json!({"x0": -10, "y0": -10, "x1": 500, "y1": 100}));
|
||||
assert!(ids(&v, "selected").is_empty(), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapping_off_disables_snapping_for_both_tools() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.line", json!({"x0": 200, "y0": 0, "x1": 300, "y1": 0, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let drag_point = |s: &mut Session| run(s, "raw.move_point", json!({"x": 200, "y": 0, "to_x": 104, "to_y": 3, "snap": 10, "merge": false}));
|
||||
// On: the line's end goes onto the rectangle's corner.
|
||||
s.begin_gesture("t");
|
||||
let v = drag_point(&mut s);
|
||||
assert_eq!(v["snapped"]["to"], json!("point"), "{v}");
|
||||
assert!((v["x"].as_f64().unwrap() - 100.0).abs() < 1e-3);
|
||||
s.end_gesture();
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
// Off: it goes where the pointer took it.
|
||||
assert_eq!(run(&mut s, "draw.snap_to_objects", json!({}))["snap_to_objects"], json!(false));
|
||||
let v = drag_point(&mut s);
|
||||
assert!(v["snapped"].is_null(), "{v}");
|
||||
assert!((v["x"].as_f64().unwrap() - 104.0).abs() < 1e-3);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
// A selection move (the Selection tool's, and Subselection's on connected shapes) too.
|
||||
run(&mut s, "raw.subselect", json!({"x": 250, "y": 0}));
|
||||
let v = run(&mut s, "element.translate", json!({"dx": -96, "dy": 3, "snap": 10, "from": [200, 0]}));
|
||||
assert!(v["snapped"].is_null() && (v["dx"].as_f64().unwrap() + 96.0).abs() < 1e-3, "{v}");
|
||||
run(&mut s, "draw.snap_to_objects", json!({"on": true}));
|
||||
let v = run(&mut s, "element.translate", json!({"dx": 1, "dy": -1, "snap": 10, "from": [105, 3]}));
|
||||
assert!(!v["snapped"].is_null(), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paint_bucket_fill_merges_with_an_adjacent_fill_of_its_colour() {
|
||||
let mut s = raw_session();
|
||||
// A red square, and lines that close an area against its right edge.
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.path", json!({"d": "M100 0 L200 0 L200 100 L100 100", "fill": null, "stroke": "#000000"}));
|
||||
let v = run(&mut s, "paint.bucket", json!({"x": 150, "y": 50, "color": "#ff0000"}));
|
||||
assert_eq!(v["merged"], json!(true));
|
||||
assert_eq!(v["exact"], json!(true), "closed by raw lines and a fill edge: filled exactly");
|
||||
let f = fills(&s);
|
||||
assert_eq!(f.len(), 1, "one red fill");
|
||||
assert!((area(&f[0]) - 20_000.0).abs() < 1.0, "{}", area(&f[0]));
|
||||
// Another colour stays its own fill, up to the lines exactly.
|
||||
let mut t = raw_session();
|
||||
run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000"}));
|
||||
run(&mut t, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null}));
|
||||
run(&mut t, "paint.bucket", json!({"x": 50, "y": 50, "color": "#00ff00"}));
|
||||
let f = fills(&t);
|
||||
assert_eq!(f.len(), 2);
|
||||
let green = f.iter().find(|e| fill_color(e) == Rgba::parse_hex("#00ff00")).unwrap();
|
||||
assert!((area(green) - 10_000.0).abs() < 1.0, "{}", area(green));
|
||||
// Recolouring the blue square green joins the two greens (no line between them? there is
|
||||
// one: the square's right side stays, so they stay two).
|
||||
run(&mut t, "paint.bucket", json!({"x": 150, "y": 50, "color": "#00ff00"}));
|
||||
assert_eq!(fills(&t).len(), 2, "the outline's right side divides them");
|
||||
// An open area: nothing is filled.
|
||||
let mut u = raw_session();
|
||||
run(&mut u, "draw.path", json!({"d": "M0 0 L100 0 L100 100", "fill": null, "stroke": "#000000"}));
|
||||
assert!(u.execute("paint.bucket", &json!({"x": 60, "y": 30})).is_err());
|
||||
// Headless sessions (Object Drawing on) keep making an object.
|
||||
let mut o = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut o, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000"}));
|
||||
let v = run(&mut o, "paint.bucket", json!({"x": 50, "y": 50}));
|
||||
assert!(v.get("merged").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recolouring_a_raw_fill_joins_the_fills_of_its_new_colour() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null}));
|
||||
assert_eq!(fills(&s).len(), 2);
|
||||
let v = run(&mut s, "paint.bucket", json!({"x": 150, "y": 50, "color": "#ff0000"}));
|
||||
assert_eq!(v["merged"], json!(true));
|
||||
let f = fills(&s);
|
||||
assert_eq!(f.len(), 1);
|
||||
assert!((area(&f[0]) - 20_000.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_raw_shape_cuts_what_it_lands_on() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 50, "h": 50, "fill": "#0000ff", "stroke": null}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let v = run(&mut s, "edit.paste", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(v["merged"], json!(true));
|
||||
let red = fills(&s).into_iter().find(|e| fill_color(e) == Rgba::parse_hex("#ff0000")).unwrap();
|
||||
assert!((area(&red) - (10_000.0 - 2_500.0)).abs() < 1.0, "the blue square cut a hole: {}", area(&red));
|
||||
assert_eq!(fills(&s).len(), 3);
|
||||
// The pasted piece is selected.
|
||||
assert_eq!(ids(&v, "pasted").len(), 1);
|
||||
// Paste in Place over itself: one blue square there, not two.
|
||||
run(&mut s, "edit.paste_in_place", json!({}));
|
||||
assert_eq!(fills(&s).len(), 3);
|
||||
// Objects on the clipboard still go on top, whole.
|
||||
run(&mut s, "draw.object_drawing", json!({"on": true}));
|
||||
run(&mut s, "draw.rect", json!({"x": 500, "y": 0, "w": 10, "h": 10, "fill": "#00ff00", "stroke": null}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let v = run(&mut s, "edit.paste", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(v["merged"], json!(false));
|
||||
assert_eq!(fills(&s).len(), 3);
|
||||
}
|
||||
|
||||
fn linear() -> Paint {
|
||||
Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(200.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_fills_take_part_in_the_merge() {
|
||||
let mut s = raw_session();
|
||||
s.style.fill_paint = Some(linear());
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null}));
|
||||
assert_eq!(fills(&s).len(), 1, "raw, not an object");
|
||||
// A line across cuts it in two; each half shows its part of the gradient where it was.
|
||||
run(&mut s, "draw.line", json!({"x0": 100, "y0": -20, "x1": 100, "y1": 120, "stroke": "#000000"}));
|
||||
let f = fills(&s);
|
||||
assert_eq!(f.len(), 2);
|
||||
for e in &f {
|
||||
let ElementKind::Shape(sh) = &e.kind else { panic!() };
|
||||
let Some(Paint::Linear { start, end, .. }) = sh.fill.as_ref().map(|p| p.transformed(&e.transform)) else { panic!("{:?}", sh.fill) };
|
||||
assert!(start.distance(Vec2::ZERO) < 1e-3 && end.distance(Vec2::new(200.0, 0.0)) < 1e-3, "{start:?} {end:?}");
|
||||
}
|
||||
// Deleting the line joins the halves again: one gradient fill.
|
||||
let line = raw(&s).into_iter().find(|e| fill_color(e).is_none() && matches!(&e.kind, ElementKind::Shape(sh) if sh.stroke.is_some())).unwrap();
|
||||
s.select_only([line.id]);
|
||||
run(&mut s, "edit.delete", json!({}));
|
||||
let halves: Vec<u64> = fills(&s).iter().map(|e| e.id.0).collect();
|
||||
run(&mut s, "raw.merge", json!({"ids": halves}));
|
||||
assert_eq!(fills(&s).len(), 1);
|
||||
assert!((area(&fills(&s)[0]) - 20_000.0).abs() < 1.0);
|
||||
// A solid fill drawn over it cuts into the gradient as into any fill.
|
||||
run(&mut s, "draw.rect", json!({"x": 50, "y": 25, "w": 50, "h": 50, "fill": "#00ff00", "stroke": null}));
|
||||
let g = fills(&s).into_iter().find(|e| fill_color(e).is_none()).unwrap();
|
||||
assert!((area(&g) - (20_000.0 - 2_500.0)).abs() < 1.0);
|
||||
// A width profile still makes an object.
|
||||
let mut t = raw_session();
|
||||
t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth);
|
||||
run(&mut t, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0}));
|
||||
assert!(raw(&t).is_empty());
|
||||
let _ = Affine::IDENTITY;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subselection_timings() {
|
||||
// 12 × 12 outlined squares and lines across every row (ADR 0041's test drawing).
|
||||
let mut s = raw_session();
|
||||
for i in 0..12 {
|
||||
for j in 0..12 {
|
||||
run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000", "radius": 6}));
|
||||
}
|
||||
run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"}));
|
||||
}
|
||||
// An empty outlined square for the Paint Bucket.
|
||||
run(&mut s, "draw.rect", json!({"x": 700, "y": 0, "w": 40, "h": 40, "fill": null, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let n = s.visible_elements().len();
|
||||
let t = std::time::Instant::now();
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 320, "y": 320}));
|
||||
let click = t.elapsed();
|
||||
let sel: Vec<anicraft_doc::ElementId> = s.selection.ids().collect();
|
||||
let t = std::time::Instant::now();
|
||||
let pts = s.raw_points(&sel);
|
||||
let list = t.elapsed();
|
||||
let h = pts.handles.first().copied().unwrap();
|
||||
s.begin_gesture("Move Handle");
|
||||
let t = std::time::Instant::now();
|
||||
let r = run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 1, "dy": 1, "merge": false}));
|
||||
let frame = t.elapsed();
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "raw.merge", json!({"ids": ids(&r, "changed")}));
|
||||
let merge = t.elapsed();
|
||||
s.end_gesture();
|
||||
let t = std::time::Instant::now();
|
||||
assert_eq!(run(&mut s, "paint.bucket", json!({"x": 720, "y": 20, "color": "#00ff00"}))["exact"], json!(true));
|
||||
let bucket = t.elapsed();
|
||||
let t = std::time::Instant::now();
|
||||
let _ = s.execute("paint.bucket", &json!({"x": 45, "y": 45, "color": "#00ff00"}));
|
||||
let open = t.elapsed();
|
||||
eprintln!(
|
||||
"{n} raw shapes; connected set {} shapes, {} anchors, {} handles; click {:.2} ms, list {:.2} ms, handle frame {:.2} ms, merge {:.2} ms, bucket {:.2} ms (open area {:.2} ms)",
|
||||
ids(&v, "selected").len(),
|
||||
pts.anchors.len(),
|
||||
pts.handles.len(),
|
||||
click.as_secs_f64() * 1e3,
|
||||
list.as_secs_f64() * 1e3,
|
||||
frame.as_secs_f64() * 1e3,
|
||||
merge.as_secs_f64() * 1e3,
|
||||
bucket.as_secs_f64() * 1e3,
|
||||
open.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_eraser_takes_gradient_fills_too() {
|
||||
let mut s = raw_session();
|
||||
s.style.fill_paint = Some(linear());
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null}));
|
||||
let before: f32 = fills(&s).iter().map(|e| area(e)).sum();
|
||||
run(&mut s, "draw.erase", json!({"points": [[100, -20], [100, 120]], "size": 20}));
|
||||
let after: f32 = fills(&s).iter().map(|e| area(e)).sum();
|
||||
assert_eq!(fills(&s).len(), 2, "cut in two");
|
||||
assert!(before - after > 1500.0, "{before} → {after}");
|
||||
}
|
||||
@@ -15,7 +15,8 @@
|
||||
//! a budget of their own, and only the shell knows what they are.
|
||||
|
||||
use crate::history::StateId;
|
||||
use anicraft_doc::{ColorEffect, DisplayList, Document, Rgba, evaluate_scene, evaluate_scene_camera};
|
||||
use crate::onion::OnionSkin;
|
||||
use anicraft_doc::{DisplayList, Document, evaluate_scene, evaluate_scene_camera};
|
||||
use anicraft_render::{RenderStats, View, render};
|
||||
use rayon::prelude::*;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
@@ -35,7 +36,8 @@ pub struct FrameJob {
|
||||
pub doc: Document,
|
||||
pub frame: u32,
|
||||
pub view: View,
|
||||
pub onion: bool,
|
||||
/// Onion skin or Edit Multiple Frames (ADR 0047); `None`: the frame alone.
|
||||
pub onion: Option<OnionSkin>,
|
||||
/// Seen through the scene's camera (View › Preview Through Camera, ADR 0027): what the
|
||||
/// movie shows, rather than the stage as edited.
|
||||
pub camera: bool,
|
||||
@@ -94,15 +96,20 @@ pub enum Raster {
|
||||
/// draws it).
|
||||
pub type Rasterizer = Arc<dyn Fn(&DisplayList, &View) -> Result<(Raster, RenderStats), String> + Send + Sync>;
|
||||
|
||||
/// What onion settings add to a key: nothing when they show nothing.
|
||||
fn onion_key(onion: Option<&OnionSkin>) -> u64 {
|
||||
onion.filter(|o| o.shows()).map_or(0, OnionSkin::key)
|
||||
}
|
||||
|
||||
/// Identity of an evaluated scene: the display list depends on these and nothing else.
|
||||
pub fn scene_key(state: StateId, frame: u32, onion: bool) -> u64 {
|
||||
pub fn scene_key(state: StateId, frame: u32, onion: Option<&OnionSkin>) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
(state, frame, onion).hash(&mut h);
|
||||
(state, frame, onion_key(onion)).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Cache key for a scene seen through a view (a frame or a tile).
|
||||
pub fn frame_key(state: StateId, frame: u32, view: &View, onion: bool) -> u64 {
|
||||
pub fn frame_key(state: StateId, frame: u32, view: &View, onion: Option<&OnionSkin>) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
state.hash(&mut h);
|
||||
frame.hash(&mut h);
|
||||
@@ -114,18 +121,19 @@ pub fn frame_key(state: StateId, frame: u32, view: &View, onion: bool) -> u64 {
|
||||
if let Some(bg) = view.background {
|
||||
[bg.r, bg.g, bg.b, bg.a].map(f32::to_bits).hash(&mut h);
|
||||
}
|
||||
onion.hash(&mut h);
|
||||
onion_key(onion).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// A job whose `scene` is derived from the same inputs as its key.
|
||||
pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
|
||||
FrameJob { key: frame_key(state, frame, &view, onion), raster: 0, scene: scene_key(state, frame, onion), doc: doc.clone(), frame, view, onion, camera: false }
|
||||
pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob {
|
||||
let onion = onion.filter(|o| o.shows()).copied();
|
||||
FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false }
|
||||
}
|
||||
|
||||
/// A job for rasterizer `raster` (from [`RenderService::raster_id`]; 0 is the CPU oracle, and
|
||||
/// gives [`make_job`]'s key), keyed apart from other rasterizers' pictures.
|
||||
pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
|
||||
pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob {
|
||||
let mut j = make_job(state, doc, frame, view, onion);
|
||||
if raster != 0 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
@@ -136,33 +144,16 @@ pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, vie
|
||||
j
|
||||
}
|
||||
|
||||
/// Movie frame `frame`'s display list, with ±2 onion-skin frames (tinted red before, green after)
|
||||
/// underneath, taken from the same scene only.
|
||||
pub fn display_list_with_onion(doc: &Document, frame: u32, onion: bool) -> DisplayList {
|
||||
/// Movie frame `frame`'s display list, with what `onion` adds underneath (onion frames or Edit
|
||||
/// Multiple Frames' keyframes, ADR 0047), taken from the same scene only.
|
||||
pub fn display_list_with_onion(doc: &Document, frame: u32, onion: Option<&OnionSkin>) -> DisplayList {
|
||||
display_list_for(doc, frame, onion, false)
|
||||
}
|
||||
|
||||
/// [`display_list_with_onion`], seen through the scene's camera when `camera` (ADR 0027).
|
||||
pub fn display_list_for(doc: &Document, frame: u32, onion: bool, camera: bool) -> DisplayList {
|
||||
let eval = |scene: usize, f: u32| if camera { evaluate_scene_camera(doc, scene, f) } else { evaluate_scene(doc, scene, f) };
|
||||
let mut dl = DisplayList::default();
|
||||
pub fn display_list_for(doc: &Document, frame: u32, onion: Option<&OnionSkin>, camera: bool) -> DisplayList {
|
||||
let (scene, local) = doc.locate(frame);
|
||||
if onion {
|
||||
let n = i64::from(doc.timeline(scene).frame_count());
|
||||
for (off, tint, alpha) in [(-2i64, 0xff5a5a, 0.12f32), (2, 0x4cd07d, 0.12), (-1, 0xff5a5a, 0.25), (1, 0x4cd07d, 0.25)] {
|
||||
let f = i64::from(local) + off;
|
||||
if f < 0 || f >= n {
|
||||
continue;
|
||||
}
|
||||
let mut ghost = eval(scene, f as u32);
|
||||
for item in &mut ghost.items {
|
||||
item.color = item.color.concat(&ColorEffect { alpha, tint: Rgba::hex(tint), tint_amount: 1.0 });
|
||||
}
|
||||
dl.append(ghost);
|
||||
}
|
||||
}
|
||||
dl.append(eval(scene, local));
|
||||
dl
|
||||
crate::onion::compose(doc, scene, local, onion, |scene, f| if camera { evaluate_scene_camera(doc, scene, f) } else { evaluate_scene(doc, scene, f) })
|
||||
}
|
||||
|
||||
/// Renders a job against an already evaluated scene, on the CPU oracle.
|
||||
@@ -201,7 +192,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>)
|
||||
|
||||
/// Renders a job synchronously, evaluating its scene.
|
||||
pub fn render_job(job: &FrameJob) -> FrameImage {
|
||||
render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion, job.camera))
|
||||
render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion.as_ref(), job.camera))
|
||||
}
|
||||
|
||||
/// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel.
|
||||
@@ -213,7 +204,7 @@ pub fn render_batch(jobs: &[FrameJob]) -> Vec<FrameImage> {
|
||||
fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec<FrameImage> {
|
||||
let mut scenes: HashMap<u64, Arc<DisplayList>> = HashMap::new();
|
||||
for j in jobs {
|
||||
scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion, j.camera)));
|
||||
scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera)));
|
||||
}
|
||||
jobs.par_iter()
|
||||
.map(|j| {
|
||||
@@ -221,7 +212,7 @@ fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec<FrameImage> {
|
||||
let raster = slot.raster.as_ref().filter(|_| j.raster != 0 && j.raster == slot.id);
|
||||
match scenes.get(&j.scene) {
|
||||
Some(dl) => render_job_by(j, dl, raster),
|
||||
None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion, j.camera), raster),
|
||||
None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera), raster),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
@@ -391,7 +382,7 @@ impl RenderService {
|
||||
}
|
||||
|
||||
/// A job for the rasterizer in use ([`make_job_for`] with [`RenderService::raster_id`]).
|
||||
pub fn job(&self, state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
|
||||
pub fn job(&self, state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob {
|
||||
make_job_for(self.raster_id(), state, doc, frame, view, onion)
|
||||
}
|
||||
|
||||
@@ -594,7 +585,7 @@ mod tests {
|
||||
|
||||
fn job(doc: &Document, state: u64, frame: u32) -> FrameJob {
|
||||
let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) };
|
||||
make_job(state, doc, frame, view, false)
|
||||
make_job(state, doc, frame, view, None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -629,7 +620,7 @@ mod tests {
|
||||
let z = 0.37f32; // deliberately odd zoom
|
||||
let (w, h) = ((1280.0 * z).ceil() as u32, (720.0 * z).ceil() as u32);
|
||||
let bg = Some(doc.stage.background);
|
||||
let full = render_job(&make_job(1, &doc, 13, View { transform: Affine::scale(z, z), width: w, height: h, background: bg }, false));
|
||||
let full = render_job(&make_job(1, &doc, 13, View { transform: Affine::scale(z, z), width: w, height: h, background: bg }, None));
|
||||
let t = 128u32;
|
||||
let mut jobs = Vec::new();
|
||||
for ty in 0..h.div_ceil(t) {
|
||||
@@ -640,7 +631,7 @@ mod tests {
|
||||
height: t.min(h - ty * t),
|
||||
background: bg,
|
||||
};
|
||||
jobs.push((tx, ty, make_job(1, &doc, 13, view, false)));
|
||||
jobs.push((tx, ty, make_job(1, &doc, 13, view, None)));
|
||||
}
|
||||
}
|
||||
let batch: Vec<FrameJob> = jobs.iter().map(|(_, _, j)| j.clone()).collect();
|
||||
@@ -698,10 +689,10 @@ mod tests {
|
||||
let doc = sample::demo();
|
||||
let svc = RenderService::new(64 << 20, None);
|
||||
let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) };
|
||||
let cpu = svc.job(1, &doc, 9, view, false);
|
||||
assert_eq!(cpu.key, make_job(1, &doc, 9, view, false).key, "no rasterizer: the oracle's keys");
|
||||
let cpu = svc.job(1, &doc, 9, view, None);
|
||||
assert_eq!(cpu.key, make_job(1, &doc, 9, view, None).key, "no rasterizer: the oracle's keys");
|
||||
// A stand-in GPU that paints everything one colour, and refuses onion-skinned frames.
|
||||
let plain = display_list_with_onion(&doc, 9, false).items.len();
|
||||
let plain = display_list_with_onion(&doc, 9, None).items.len();
|
||||
let flat: Rasterizer = Arc::new(move |dl: &DisplayList, v: &View| {
|
||||
if dl.items.len() > plain {
|
||||
return Err("too much".into());
|
||||
@@ -710,23 +701,23 @@ mod tests {
|
||||
});
|
||||
svc.set_rasterizer(Some(flat));
|
||||
assert!(svc.has_rasterizer());
|
||||
let gpu = svc.job(1, &doc, 9, view, false);
|
||||
let gpu = svc.job(1, &doc, 9, view, None);
|
||||
assert_ne!(gpu.key, cpu.key, "pictures are keyed by who drew them");
|
||||
let img = svc.render_now(gpu.clone());
|
||||
assert!(img.gpu && img.fallback.is_none() && img.rgba_premul[..4] == [10, 20, 30, 255]);
|
||||
// What it refuses, the oracle draws, saying why.
|
||||
let onion = svc.job(1, &doc, 9, view, true);
|
||||
let onion = svc.job(1, &doc, 9, view, Some(&OnionSkin::default()));
|
||||
let img = svc.render_now(onion.clone());
|
||||
assert!(!img.gpu && img.fallback.as_deref() == Some("too much"));
|
||||
assert_eq!(img.rgba_premul, render_job(&make_job(1, &doc, 9, view, true)).rgba_premul);
|
||||
assert_eq!(img.rgba_premul, render_job(&make_job(1, &doc, 9, view, Some(&OnionSkin::default()))).rgba_premul);
|
||||
// Through the worker too; and a job made for an older rasterizer is drawn by the oracle.
|
||||
let ahead = svc.job(1, &doc, 10, view, false);
|
||||
let ahead = svc.job(1, &doc, 10, view, None);
|
||||
svc.prefetch(vec![ahead.clone()]);
|
||||
assert!(svc.wait_for(ahead.key, 10_000).is_some_and(|i| i.gpu));
|
||||
svc.set_rasterizer(None);
|
||||
let stale = FrameJob { key: 77, ..ahead };
|
||||
assert!(!render_batch_by(&[stale], &svc.slot())[0].gpu);
|
||||
assert_eq!(svc.job(1, &doc, 9, view, false).key, cpu.key, "back to the oracle's keys");
|
||||
assert_eq!(svc.job(1, &doc, 9, view, None).key, cpu.key, "back to the oracle's keys");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -773,11 +764,11 @@ mod tests {
|
||||
Ok((Raster::Native { image: Arc::new(7u32), width: v.width + u32::from(bad), height: v.height }, RenderStats::default()))
|
||||
});
|
||||
svc.set_rasterizer(Some(native));
|
||||
let img = svc.render_now(svc.job(1, &doc, 3, view, false));
|
||||
let img = svc.render_now(svc.job(1, &doc, 3, view, None));
|
||||
assert!(img.gpu && img.rgba_premul.is_empty());
|
||||
assert_eq!(img.native.as_ref().and_then(|n| n.downcast_ref::<u32>()), Some(&7));
|
||||
wrong.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let img = svc.render_now(svc.job(1, &doc, 4, view, false));
|
||||
let img = svc.render_now(svc.job(1, &doc, 4, view, None));
|
||||
assert!(!img.gpu && img.native.is_none() && img.fallback.as_deref() == Some("the GPU returned a wrong-sized image"));
|
||||
assert_eq!(img.rgba_premul.len(), 320 * 180 * 4, "the oracle drew it instead");
|
||||
}
|
||||
@@ -794,8 +785,12 @@ mod tests {
|
||||
#[test]
|
||||
fn onion_adds_neighbour_frames() {
|
||||
let doc = sample::demo();
|
||||
let plain = display_list_with_onion(&doc, 10, false).items.len();
|
||||
let onion = display_list_with_onion(&doc, 10, true).items.len();
|
||||
assert_eq!(onion, plain * 5);
|
||||
let plain = display_list_with_onion(&doc, 10, None).items.len();
|
||||
let onion = display_list_with_onion(&doc, 10, Some(&OnionSkin::default())).items.len();
|
||||
// ±2 frames of every unlocked layer (Animate doesn't onion-skin locked ones).
|
||||
let tl = doc.timeline(0);
|
||||
let unlocked = display_list_with_onion(&doc, 10, None).items.iter().filter(|i| tl.layer(i.layer).is_some_and(|l| !l.locked)).count();
|
||||
assert!(unlocked < plain, "the sample has a locked layer");
|
||||
assert_eq!(onion, plain + 4 * unlocked);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
//! The selection (ADR 0044): elements at the playhead, each named with its layer, so one
|
||||
//! selection holds artwork on several layers as in Animate.
|
||||
//!
|
||||
//! Commands see the selection in one of three ways:
|
||||
//! * **per layer** ([`Session::each_layer`]): the command's single-layer body runs once for every
|
||||
//! layer that has selected items, with that layer active and the selection narrowed to it
|
||||
//! (move, delete, duplicate, arrange, filters, colour effects, break apart, …). A selection on
|
||||
//! the active layer alone runs the body exactly as before;
|
||||
//! * **across** the layers: the command reads every selected item with its layer (align and
|
||||
//! distribute, the Free Transform box, copy, convert to symbol, snapping a move);
|
||||
//! * **on the active layer** only, where Animate does the same (Subselection, the Width tool,
|
||||
//! the Eraser's selected fills): [`Selection::on`] with [`Session::layer`].
|
||||
|
||||
use crate::{EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, LayerId, LayerKind, evaluate_layer_elements};
|
||||
use anicraft_geom::Rect;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The selected elements, in the order they were selected, each with its layer.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Selection {
|
||||
items: Vec<(LayerId, ElementId)>,
|
||||
/// The same pairs, for constant-time membership.
|
||||
set: HashSet<(LayerId, ElementId)>,
|
||||
}
|
||||
|
||||
impl PartialEq for Selection {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.items == other.items
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Selection {}
|
||||
|
||||
impl Selection {
|
||||
/// `ids` on `layer`.
|
||||
pub fn only(layer: LayerId, ids: impl IntoIterator<Item = ElementId>) -> Selection {
|
||||
let mut s = Selection::default();
|
||||
s.extend_on(layer, ids);
|
||||
s
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.items.clear();
|
||||
self.set.clear();
|
||||
}
|
||||
|
||||
/// Every `(layer, element)`, in selection order.
|
||||
pub fn iter(&self) -> impl Iterator<Item = (LayerId, ElementId)> + '_ {
|
||||
self.items.iter().copied()
|
||||
}
|
||||
|
||||
/// Every selected element id (ids are unique within a document), in selection order.
|
||||
pub fn ids(&self) -> impl Iterator<Item = ElementId> + '_ {
|
||||
self.items.iter().map(|(_, e)| *e)
|
||||
}
|
||||
|
||||
/// The ids as plain numbers, for command results.
|
||||
pub fn id_list(&self) -> Vec<u64> {
|
||||
self.ids().map(|e| e.0).collect()
|
||||
}
|
||||
|
||||
pub fn first(&self) -> Option<(LayerId, ElementId)> {
|
||||
self.items.first().copied()
|
||||
}
|
||||
|
||||
/// Whether `id` on `layer` is selected.
|
||||
pub fn contains(&self, layer: LayerId, id: ElementId) -> bool {
|
||||
self.set.contains(&(layer, id))
|
||||
}
|
||||
|
||||
/// Whether `id` is selected on any layer.
|
||||
pub fn has_id(&self, id: ElementId) -> bool {
|
||||
self.items.iter().any(|(_, e)| *e == id)
|
||||
}
|
||||
|
||||
/// The selected ids on `layer`, in selection order.
|
||||
pub fn on(&self, layer: LayerId) -> Vec<ElementId> {
|
||||
self.items.iter().filter(|(l, _)| *l == layer).map(|(_, e)| *e).collect()
|
||||
}
|
||||
|
||||
/// The part of the selection on `layer`.
|
||||
pub fn narrowed(&self, layer: LayerId) -> Selection {
|
||||
Selection::only(layer, self.on(layer))
|
||||
}
|
||||
|
||||
/// The layers with selected items, in the order they were first selected on.
|
||||
pub fn layers(&self) -> Vec<LayerId> {
|
||||
let mut out: Vec<LayerId> = Vec::new();
|
||||
for (l, _) in &self.items {
|
||||
if !out.contains(l) {
|
||||
out.push(*l);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Adds `id` on `layer`; false when it already was selected.
|
||||
pub fn insert(&mut self, layer: LayerId, id: ElementId) -> bool {
|
||||
if !self.set.insert((layer, id)) {
|
||||
return false;
|
||||
}
|
||||
self.items.push((layer, id));
|
||||
true
|
||||
}
|
||||
|
||||
pub fn extend_on(&mut self, layer: LayerId, ids: impl IntoIterator<Item = ElementId>) {
|
||||
for id in ids {
|
||||
self.insert(layer, id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, layer: LayerId, id: ElementId) -> bool {
|
||||
if !self.set.remove(&(layer, id)) {
|
||||
return false;
|
||||
}
|
||||
self.items.retain(|x| *x != (layer, id));
|
||||
true
|
||||
}
|
||||
|
||||
/// Selects `id` on `layer`, or lets go of it when it was selected (Shift-click).
|
||||
pub fn toggle(&mut self, layer: LayerId, id: ElementId) {
|
||||
if !self.remove(layer, id) {
|
||||
self.insert(layer, id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn retain(&mut self, mut keep: impl FnMut(LayerId, ElementId) -> bool) {
|
||||
let set = &mut self.set;
|
||||
self.items.retain(|&(l, e)| {
|
||||
let k = keep(l, e);
|
||||
if !k {
|
||||
set.remove(&(l, e));
|
||||
}
|
||||
k
|
||||
});
|
||||
}
|
||||
|
||||
/// Replaces what is selected on `layer` with `ids`, leaving the other layers alone.
|
||||
pub fn set_on(&mut self, layer: LayerId, ids: impl IntoIterator<Item = ElementId>) {
|
||||
self.retain(|l, _| l != layer);
|
||||
self.extend_on(layer, ids);
|
||||
}
|
||||
}
|
||||
|
||||
/// Result keys that are values, not counts: they are not summed over layers.
|
||||
const VALUE_KEYS: &[&str] = &["filters"];
|
||||
|
||||
/// One result for a command that ran on several layers: lists are joined, counts added, other
|
||||
/// values come from the first layer; `layers` lists the layers it ran on.
|
||||
fn merge_results(results: Vec<(LayerId, Value)>) -> Value {
|
||||
let mut out = Map::new();
|
||||
for (_, v) in &results {
|
||||
let Value::Object(m) = v else { continue };
|
||||
for (k, x) in m {
|
||||
match (out.get_mut(k), x) {
|
||||
(None, _) => {
|
||||
out.insert(k.clone(), x.clone());
|
||||
}
|
||||
(Some(Value::Array(a)), Value::Array(b)) => a.extend(b.iter().cloned()),
|
||||
(Some(Value::Number(a)), Value::Number(b)) if !VALUE_KEYS.contains(&k.as_str()) => {
|
||||
if let (Some(p), Some(q)) = (a.as_u64(), b.as_u64()) {
|
||||
*a = p.saturating_add(q).into();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.insert("layers".into(), json!(results.iter().map(|(l, _)| l.0).collect::<Vec<_>>()));
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The elements on `layer` at the playhead (tweens applied).
|
||||
pub fn elements_on(&self, layer: LayerId) -> Vec<Arc<Element>> {
|
||||
self.doc.timeline(self.scene).layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether artwork on `layer` can be selected: it is in this scene, shown and unlocked
|
||||
/// (folders included), and not a folder.
|
||||
pub fn selectable(&self, layer: LayerId) -> bool {
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return false };
|
||||
tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder) && !tl.locked_by_folder(layer) && !tl.hidden_by_folder(i)
|
||||
}
|
||||
|
||||
/// Whether a marquee or Select All gathers artwork from `layer`: a selectable layer with
|
||||
/// artwork on it. The camera layer holds only the camera, and an armature layer's
|
||||
/// instances are posed by their bones, so they are gathered only while active.
|
||||
pub fn gathers(&self, layer: LayerId) -> bool {
|
||||
let kind = self.doc.timeline(self.scene).layer(layer).map(|l| l.kind);
|
||||
self.selectable(layer) && (layer == self.layer || !matches!(kind, Some(LayerKind::Camera | LayerKind::Armature)))
|
||||
}
|
||||
|
||||
/// The layers with selected items, top to bottom.
|
||||
pub fn selected_layers(&self) -> Vec<LayerId> {
|
||||
let mine = self.selection.layers();
|
||||
self.doc.timeline(self.scene).layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect()
|
||||
}
|
||||
|
||||
/// Every selected element as it looks at the playhead, with its layer: layers top to
|
||||
/// bottom, each in stacking order.
|
||||
pub fn selected_elements(&self) -> Vec<(LayerId, Arc<Element>)> {
|
||||
let mut out = Vec::new();
|
||||
for l in self.selected_layers() {
|
||||
out.extend(self.elements_on(l).into_iter().filter(|e| self.selection.contains(l, e.id)).map(|e| (l, e)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Selects `ids` on the active layer, and nothing else.
|
||||
pub fn select_only(&mut self, ids: impl IntoIterator<Item = ElementId>) {
|
||||
self.selection = Selection::only(self.layer, ids);
|
||||
}
|
||||
|
||||
/// Stage-space bounds of element `id` on `layer` at the playhead.
|
||||
pub fn element_bounds_on(&self, layer: LayerId, id: ElementId) -> Rect {
|
||||
let mut r = Rect::EMPTY;
|
||||
for item in self.display_list().items.iter().filter(|i| i.element == id && i.layer == layer) {
|
||||
let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach);
|
||||
r = r.union(&item.path.bounds().inflate(pad).transformed(&item.transform));
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Bounds of the whole selection, over every layer (the Free Transform box).
|
||||
pub fn selection_bounds(&self) -> Rect {
|
||||
let sel: HashSet<(LayerId, ElementId)> = self.selection.iter().collect();
|
||||
let mut r = Rect::EMPTY;
|
||||
for item in self.display_list().items.iter().filter(|i| sel.contains(&(i.layer, i.element))) {
|
||||
let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach);
|
||||
r = r.union(&item.path.bounds().inflate(pad).transformed(&item.transform));
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Drops selected items that are gone at the playhead, or whose layer is gone, hidden or
|
||||
/// locked (a locked or hidden layer is never selected), and keeps the active layer valid.
|
||||
pub fn fix_selection(&mut self) {
|
||||
self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1));
|
||||
if self.doc.timeline(self.scene).layer(self.layer).is_none() {
|
||||
self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id);
|
||||
}
|
||||
if self.selection.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut present: HashMap<LayerId, HashSet<ElementId>> = HashMap::new();
|
||||
for l in self.selection.layers() {
|
||||
if self.selectable(l) {
|
||||
present.insert(l, self.elements_on(l).iter().map(|e| e.id).collect());
|
||||
}
|
||||
}
|
||||
self.selection.retain(|l, id| present.get(&l).is_some_and(|ids| ids.contains(&id)));
|
||||
}
|
||||
|
||||
/// Runs a command's single-layer body once for every layer with selected items, top to
|
||||
/// bottom, with that layer active and the selection narrowed to it; the selection is then
|
||||
/// what the runs left selected, and the active layer stays. A selection on the active layer
|
||||
/// alone (or none) runs the body once, as before.
|
||||
///
|
||||
/// `strict`: every layer must succeed (an error undoes the whole command). Otherwise a layer
|
||||
/// where the edit does not apply (no movie clips for a filter, no text to restyle) is left
|
||||
/// as it was, and the command fails only when it applies nowhere.
|
||||
pub(crate) fn each_layer(&mut self, strict: bool, mut run: impl FnMut(&mut Session) -> Result<Value>) -> Result<Value> {
|
||||
let layers = self.selected_layers();
|
||||
match layers.as_slice() {
|
||||
[] => return run(self),
|
||||
[one] if *one == self.layer => return run(self),
|
||||
_ => {}
|
||||
}
|
||||
let active = self.layer;
|
||||
let full = self.selection.clone();
|
||||
let mut after = Selection::default();
|
||||
let mut results = Vec::new();
|
||||
let mut first_err: Option<EngineError> = None;
|
||||
for l in layers {
|
||||
let before = (!strict).then(|| self.doc.clone());
|
||||
self.layer = l;
|
||||
self.selection = full.narrowed(l);
|
||||
// Each layer's run sees what the runs before it changed.
|
||||
self.dl_cache.replace(None);
|
||||
let r = run(self);
|
||||
// A motion tween's target on this layer turns into property keys now (the session
|
||||
// does this once per command, for one layer).
|
||||
if let Some(edit) = self.motion_edit.take()
|
||||
&& r.is_ok()
|
||||
{
|
||||
crate::cmds_motion::finish_edit(self, edit);
|
||||
}
|
||||
self.dl_cache.replace(None);
|
||||
match r {
|
||||
Ok(v) => {
|
||||
for (sl, id) in self.selection.iter() {
|
||||
after.insert(sl, id);
|
||||
}
|
||||
results.push((l, v));
|
||||
}
|
||||
Err(e) if strict => {
|
||||
self.layer = active;
|
||||
return Err(e);
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(d) = before {
|
||||
self.doc = d;
|
||||
}
|
||||
for (sl, id) in full.narrowed(l).iter() {
|
||||
after.insert(sl, id);
|
||||
}
|
||||
first_err.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.doc.timeline(self.scene).layer(active).is_some() {
|
||||
self.layer = active;
|
||||
}
|
||||
self.selection = after;
|
||||
if results.is_empty() {
|
||||
return Err(first_err.unwrap_or_else(|| EngineError::State("nothing is selected".into())));
|
||||
}
|
||||
Ok(merge_results(results))
|
||||
}
|
||||
|
||||
/// Runs `f` with `layer` active, then makes the active layer what it was.
|
||||
pub(crate) fn with_layer<T>(&mut self, layer: LayerId, f: impl FnOnce(&mut Session) -> T) -> T {
|
||||
let active = self.layer;
|
||||
self.layer = layer;
|
||||
self.dl_cache.replace(None);
|
||||
let r = f(self);
|
||||
if let Some(edit) = self.motion_edit.take() {
|
||||
crate::cmds_motion::finish_edit(self, edit);
|
||||
}
|
||||
self.dl_cache.replace(None);
|
||||
if self.doc.timeline(self.scene).layer(active).is_some() {
|
||||
self.layer = active;
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
//! Selection across layers (ADR 0044): every command that reads the selection, with a selection
|
||||
//! on two layers; the marquee across layers with raw parts; locked and hidden layers.
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, LayerId};
|
||||
use anicraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn el_id(v: &Value) -> ElementId {
|
||||
ElementId(v["element"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Two layers, "Top" over "Bottom", one drawing object on each: Top's at (0, 0) 100 × 100,
|
||||
/// Bottom's at (200, 100) 50 × 50. Both are selected; Top is active.
|
||||
fn two_layers() -> (Session, LayerId, LayerId, ElementId, ElementId) {
|
||||
let mut s = Session::default();
|
||||
let bottom = s.layer;
|
||||
run(&mut s, "layer.rename", json!({"name": "Bottom"}));
|
||||
let b = el_id(&run(&mut s, "draw.rect", json!({"x": 200, "y": 100, "w": 50, "h": 50, "fill": "#00ff00"})));
|
||||
let top = LayerId(run(&mut s, "layer.new", json!({"name": "Top"}))["layer"].as_u64().unwrap());
|
||||
let a = el_id(&run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100})));
|
||||
run(&mut s, "element.select", json!({"ids": [a.0, b.0]}));
|
||||
assert_eq!(s.selected_layers(), vec![top, bottom], "top to bottom");
|
||||
(s, top, bottom, a, b)
|
||||
}
|
||||
|
||||
/// `id` on `layer` at the playhead.
|
||||
fn element(s: &Session, layer: LayerId, id: ElementId) -> Option<Arc<Element>> {
|
||||
s.elements_on(layer).into_iter().find(|e| e.id == id)
|
||||
}
|
||||
|
||||
fn pos(s: &Session, layer: LayerId, id: ElementId) -> (f32, f32) {
|
||||
let t = element(s, layer, id).unwrap().transform.translation();
|
||||
(t.x, t.y)
|
||||
}
|
||||
|
||||
fn bounds(s: &Session, layer: LayerId, id: ElementId) -> Rect {
|
||||
s.element_bounds_on(layer, id)
|
||||
}
|
||||
|
||||
// ----- the model ---------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn select_takes_ids_on_any_layer_and_reports_them() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
assert!(s.selection.contains(top, a) && s.selection.contains(bottom, b));
|
||||
assert_eq!(s.layer, top, "the active layer had some of them: it stays");
|
||||
let info = s.info();
|
||||
assert_eq!(info["selection"], json!([a.0, b.0]));
|
||||
assert_eq!(info["selection_layers"], json!([top.0, bottom.0]));
|
||||
// Only the bottom one: its layer becomes active, as a click on it would.
|
||||
run(&mut s, "element.select", json!({"ids": [b.0]}));
|
||||
assert_eq!(s.layer, bottom);
|
||||
// `add` keeps what was selected; `layer` says where to look.
|
||||
run(&mut s, "element.select", json!({"ids": [a.0], "add": true, "layer": top.0}));
|
||||
assert_eq!(s.selection.len(), 2);
|
||||
assert!(s.execute("element.select", &json!({"ids": [a.0], "layer": bottom.0})).is_err(), "a is not on Bottom");
|
||||
assert!(s.execute("element.select", &json!({"ids": [999_999]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_click_adds_and_removes_across_layers() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
run(&mut s, "element.pick", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, a)]);
|
||||
run(&mut s, "element.pick", json!({"x": 225, "y": 125, "add": true}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, a), (bottom, b)], "Shift keeps the other layer's");
|
||||
assert_eq!(s.layer, bottom, "the clicked layer becomes active");
|
||||
// A plain click on a selected element keeps the selection (so a drag moves it all).
|
||||
run(&mut s, "element.pick", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(s.selection.len(), 2);
|
||||
assert_eq!(s.layer, top);
|
||||
// Shift-click again lets go of it; a plain click elsewhere selects only that.
|
||||
run(&mut s, "element.pick", json!({"x": 50, "y": 50, "add": true}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(bottom, b)]);
|
||||
run(&mut s, "element.pick", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, a)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_or_hidden_layers_are_never_selected() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
// Locking a layer lets go of what was selected on it.
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": bottom.0}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, a)]);
|
||||
assert!(s.execute("element.select", &json!({"ids": [b.0], "add": true})).is_err(), "locked");
|
||||
assert_eq!(run(&mut s, "element.pick", json!({"x": 225, "y": 125, "add": true}))["element"], Value::Null, "a click goes through it");
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, a)], "Select All skips it");
|
||||
run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": -10, "x1": 300, "y1": 300}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, a)], "so does the marquee");
|
||||
// Hiding works the same.
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": bottom.0}));
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
assert_eq!(s.selection.len(), 2);
|
||||
run(&mut s, "layer.toggle_visible", json!({"layer": top.0}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(bottom, b)]);
|
||||
assert!(s.execute("element.select", &json!({"ids": [a.0]})).is_err(), "hidden");
|
||||
// A locked folder locks the layers in it.
|
||||
run(&mut s, "layer.toggle_visible", json!({"layer": top.0}));
|
||||
run(&mut s, "layer.select", json!({"layer": top.0}));
|
||||
let folder = LayerId(run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap());
|
||||
s.doc.timeline_mut(0).layer_mut(top).unwrap().parent = Some(folder);
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": folder.0}));
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(bottom, b)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_to_another_frame_keeps_what_is_there() {
|
||||
let (mut s, top, bottom, a, _) = two_layers();
|
||||
// Bottom ends at frame 1; Top goes on to frame 10.
|
||||
run(&mut s, "timeline.insert_keyframe", json!({"layer": top.0, "frame": 9}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 5}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, a)], "Bottom has nothing at frame 6");
|
||||
assert!(!s.selected_layers().contains(&bottom));
|
||||
}
|
||||
|
||||
// ----- per-layer edits ------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn move_and_nudge_move_both_layers_in_one_step() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
let steps = s.history_len();
|
||||
let (pa, pb) = (pos(&s, top, a), pos(&s, bottom, b));
|
||||
let v = run(&mut s, "element.translate", json!({"dx": 5, "dy": -3}));
|
||||
assert_eq!(v["moved"], 2);
|
||||
assert_eq!(pos(&s, top, a), (pa.0 + 5.0, pa.1 - 3.0));
|
||||
assert_eq!(pos(&s, bottom, b), (pb.0 + 5.0, pb.1 - 3.0));
|
||||
assert_eq!(s.history_len(), steps + 1, "one undo step");
|
||||
// A drag is one gesture: many moves, one step.
|
||||
s.begin_gesture("Move");
|
||||
for _ in 0..10 {
|
||||
run(&mut s, "element.translate", json!({"dx": 1, "dy": 0}));
|
||||
}
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), steps + 2);
|
||||
assert_eq!(pos(&s, bottom, b).0, pb.0 + 15.0);
|
||||
s.undo().unwrap();
|
||||
s.undo().unwrap();
|
||||
assert_eq!((pos(&s, top, a), pos(&s, bottom, b)), (pa, pb));
|
||||
assert_eq!(s.selection.len(), 2, "undo brings the selection back with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_snaps_onto_artwork_on_the_selected_layers() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
// Something unselected on Bottom, just right of Top's square (whose right edge is x = 100).
|
||||
run(&mut s, "layer.select", json!({"layer": bottom.0}));
|
||||
let target = el_id(&run(&mut s, "draw.rect", json!({"x": 104, "y": 0, "w": 20, "h": 20})));
|
||||
run(&mut s, "element.select", json!({"ids": [a.0, b.0]}));
|
||||
assert!(!s.selection.contains(bottom, target));
|
||||
let (pa, pb) = (pos(&s, top, a), pos(&s, bottom, b));
|
||||
let v = run(&mut s, "element.translate", json!({"dx": 1, "dy": 0, "snap": 5, "from": [100, 0]}));
|
||||
assert_eq!(v["snapped"]["to"], "point", "{v}");
|
||||
assert!((pos(&s, top, a).0 - (pa.0 + 4.0)).abs() < 1e-3, "the corner at (100, 0) met the target's at (104, 0)");
|
||||
assert!((pos(&s, bottom, b).0 - (pb.0 + 4.0)).abs() < 1e-3, "and the other layer moved by as much");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_duplicate_and_arrange_work_on_each_layer() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
// Something unselected on each layer, above the selected ones.
|
||||
let above_a = el_id(&run(&mut s, "draw.rect", json!({"x": 500, "y": 0, "w": 10, "h": 10})));
|
||||
run(&mut s, "layer.select", json!({"layer": bottom.0}));
|
||||
let above_b = el_id(&run(&mut s, "draw.rect", json!({"x": 500, "y": 50, "w": 10, "h": 10})));
|
||||
run(&mut s, "element.select", json!({"ids": [a.0, b.0]}));
|
||||
let order = |s: &Session, l: LayerId| s.elements_on(l).iter().map(|e| e.id).collect::<Vec<_>>();
|
||||
run(&mut s, "arrange.bring_to_front", json!({}));
|
||||
assert_eq!(order(&s, top), vec![above_a, a]);
|
||||
assert_eq!(order(&s, bottom), vec![above_b, b]);
|
||||
run(&mut s, "arrange.send_backward", json!({}));
|
||||
assert_eq!(order(&s, top), vec![a, above_a]);
|
||||
assert_eq!(order(&s, bottom), vec![b, above_b]);
|
||||
|
||||
let v = run(&mut s, "edit.duplicate", json!({"dx": 10, "dy": 10}));
|
||||
assert_eq!(v["created"].as_array().unwrap().len(), 2, "{v}");
|
||||
assert_eq!(s.elements_on(top).len(), 3);
|
||||
assert_eq!(s.elements_on(bottom).len(), 3);
|
||||
let copies: Vec<(LayerId, ElementId)> = s.selection.iter().collect();
|
||||
assert_eq!(copies.iter().map(|c| c.0).collect::<Vec<_>>(), vec![top, bottom], "the copies are selected, each on its layer");
|
||||
|
||||
let steps = s.history_len();
|
||||
let v = run(&mut s, "edit.delete", json!({}));
|
||||
assert_eq!(v["deleted"], 2);
|
||||
assert!(s.selection.is_empty());
|
||||
assert_eq!((s.elements_on(top).len(), s.elements_on(bottom).len()), (2, 2));
|
||||
assert_eq!(s.history_len(), steps + 1, "one step");
|
||||
s.undo().unwrap();
|
||||
assert_eq!((s.elements_on(top).len(), s.elements_on(bottom).len()), (3, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_edits_apply_to_each_layer() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
run(&mut s, "element.set_alpha", json!({"alpha": 0.5}));
|
||||
run(&mut s, "element.set_fill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "element.set_stroke", json!({"width": 7}));
|
||||
run(&mut s, "element.rename", json!({"name": "both"}));
|
||||
run(&mut s, "element.set_transform", json!({"rotation": 45}));
|
||||
for (l, id) in [(top, a), (bottom, b)] {
|
||||
let e = element(&s, l, id).unwrap();
|
||||
assert_eq!(e.color.alpha, 0.5);
|
||||
assert_eq!(e.name, "both");
|
||||
assert!((e.transform.decompose().rotation.to_degrees() - 45.0).abs() < 1e-3);
|
||||
let ElementKind::Shape(sh) = &e.kind else { panic!() };
|
||||
assert_eq!(sh.fill.as_ref().map(anicraft_doc::Paint::primary_color), Some(anicraft_doc::Rgba::hex(0xff0000)));
|
||||
assert_eq!(sh.stroke.as_ref().map(|st| st.width), Some(7.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_apply_where_they_can_and_fail_where_nothing_takes_them() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
// Top's square becomes a movie clip; Bottom's stays a shape.
|
||||
run(&mut s, "element.select", json!({"ids": [a.0]}));
|
||||
let clip = ElementId(run(&mut s, "modify.convert_to_symbol", json!({}))["instance"].as_u64().unwrap());
|
||||
run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"}));
|
||||
run(&mut s, "element.select", json!({"ids": [clip.0, b.0]}));
|
||||
let v = run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]}));
|
||||
assert_eq!((v["set"].as_u64(), v["filters"].as_u64()), (Some(1), Some(1)), "one instance, one filter: {v}");
|
||||
assert!(matches!(&element(&s, top, clip).unwrap().kind, ElementKind::Symbol { filters, .. } if filters.len() == 1));
|
||||
run(&mut s, "element.set_blend", json!({"mode": "multiply"}));
|
||||
// Shapes only: nothing to filter anywhere.
|
||||
run(&mut s, "element.select", json!({"ids": [b.0]}));
|
||||
assert!(s.execute("element.set_filters", &json!({"filters": []})).is_err());
|
||||
assert!(element(&s, bottom, b).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tweened_frame_gets_a_keyframe_on_each_layer() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
// Classic tweens over frames 1–10 on both layers.
|
||||
for l in [top, bottom] {
|
||||
run(&mut s, "timeline.insert_keyframe", json!({"layer": l.0, "frame": 9}));
|
||||
run(&mut s, "timeline.create_tween", json!({"layer": l.0, "frame": 0}));
|
||||
}
|
||||
run(&mut s, "timeline.goto", json!({"frame": 4}));
|
||||
run(&mut s, "element.select", json!({"ids": [a.0, b.0]}));
|
||||
assert_eq!(s.selection.len(), 2);
|
||||
run(&mut s, "element.translate", json!({"dx": 0, "dy": 30}));
|
||||
for l in [top, bottom] {
|
||||
let layer = s.doc.timeline(0).layer(l).unwrap();
|
||||
assert!(layer.keyframes.iter().any(|k| k.start == 4), "{}: a key at the playhead", layer.name);
|
||||
}
|
||||
}
|
||||
|
||||
// ----- across the layers ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn align_and_distribute_work_across_layers() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
run(&mut s, "align.left", json!({}));
|
||||
assert!((bounds(&s, top, a).min.x - bounds(&s, bottom, b).min.x).abs() < 1e-3);
|
||||
run(&mut s, "align.bottom", json!({}));
|
||||
assert!((bounds(&s, top, a).max.y - bounds(&s, bottom, b).max.y).abs() < 1e-3);
|
||||
// A third on Bottom: the three centres spread evenly.
|
||||
run(&mut s, "layer.select", json!({"layer": bottom.0}));
|
||||
let c = el_id(&run(&mut s, "draw.rect", json!({"x": 400, "y": 400, "w": 20, "h": 20})));
|
||||
run(&mut s, "element.select", json!({"ids": [a.0, b.0, c.0]}));
|
||||
run(&mut s, "align.distribute_v", json!({}));
|
||||
let mut ys: Vec<f32> = [(top, a), (bottom, b), (bottom, c)].iter().map(|&(l, id)| bounds(&s, l, id).center().y).collect();
|
||||
ys.sort_by(f32::total_cmp);
|
||||
assert!(((ys[1] - ys[0]) - (ys[2] - ys[1])).abs() < 1e-3, "{ys:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_transform_turns_the_combined_box() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
let before = s.selection_bounds();
|
||||
assert_eq!(before, bounds(&s, top, a).union(&bounds(&s, bottom, b)), "one box for the whole selection");
|
||||
let c = before.center();
|
||||
run(&mut s, "modify.rotate_cw", json!({}));
|
||||
let after = s.selection_bounds();
|
||||
assert!((after.center().x - c.x).abs() < 1e-2 && (after.center().y - c.y).abs() < 1e-2, "about the combined centre");
|
||||
assert!((after.width() - before.height()).abs() < 1e-2, "turned a quarter");
|
||||
// modify.transform applies the same matrix on both layers.
|
||||
let (pa, pb) = (pos(&s, top, a), pos(&s, bottom, b));
|
||||
run(&mut s, "modify.transform", json!({"a": 1, "b": 0, "c": 0, "d": 1, "e": 3, "f": 4}));
|
||||
assert_eq!(pos(&s, top, a), (pa.0 + 3.0, pa.1 + 4.0));
|
||||
assert_eq!(pos(&s, bottom, b), (pb.0 + 3.0, pb.1 + 4.0));
|
||||
run(&mut s, "modify.flip_h", json!({}));
|
||||
run(&mut s, "modify.remove_transform", json!({}));
|
||||
for (l, id) in [(top, a), (bottom, b)] {
|
||||
assert!((element(&s, l, id).unwrap().transform.decompose().rotation).abs() < 1e-4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_and_paste_keep_each_layer() {
|
||||
let (mut s, top, bottom, ..) = two_layers();
|
||||
let v = run(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!((v["copied"].as_u64(), v["layers"].as_u64()), (Some(2), Some(2)));
|
||||
// Back where they came from, each on its layer.
|
||||
let v = run(&mut s, "edit.paste_in_place", json!({}));
|
||||
assert_eq!(v["layers"], json!([top.0, bottom.0]), "{v}");
|
||||
assert_eq!((s.elements_on(top).len(), s.elements_on(bottom).len()), (2, 2));
|
||||
assert_eq!(s.selected_layers(), vec![top, bottom], "the pasted copies are selected");
|
||||
// Cut takes both away in one step.
|
||||
let steps = s.history_len();
|
||||
run(&mut s, "edit.cut", json!({}));
|
||||
assert_eq!((s.elements_on(top).len(), s.elements_on(bottom).len()), (1, 1));
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
// Into another document: layers named after the copied ones are made for them.
|
||||
run(&mut s, "file.new", json!({"confirm": true}));
|
||||
let first = s.layer;
|
||||
let v = run(&mut s, "edit.paste", json!({"x": 300, "y": 200}));
|
||||
let layers = s.doc.timeline(0).layers.clone();
|
||||
assert_eq!(layers.len(), 2, "{v}");
|
||||
assert_eq!(layers[0].id, first, "the first copied layer lands on the active one");
|
||||
assert_eq!(layers[1].name, "Bottom", "the next is made, named after the copied one");
|
||||
assert_eq!(s.elements_on(layers[0].id).len(), 1);
|
||||
assert_eq!(s.elements_on(layers[1].id).len(), 1);
|
||||
// One copied layer always goes on the active layer, as before.
|
||||
let lower = s.elements_on(layers[1].id)[0].id;
|
||||
run(&mut s, "element.select", json!({"ids": [lower.0]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "layer.select", json!({"layer": first.0}));
|
||||
run(&mut s, "edit.paste_in_place", json!({}));
|
||||
assert_eq!(s.elements_on(first).len(), 2);
|
||||
assert_eq!(s.selected_layers(), vec![first]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_symbol_keeps_the_layers_inside_and_lands_on_the_topmost() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
let center = s.selection_bounds().center();
|
||||
let px = |s: &Session| anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
let was = px(&s);
|
||||
let steps = s.history_len();
|
||||
let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Both"}));
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
assert_eq!(v["layer"], top.0);
|
||||
let inst = ElementId(v["instance"].as_u64().unwrap());
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, inst)]);
|
||||
assert_eq!(s.layer, top);
|
||||
assert!(element(&s, top, a).is_none() && element(&s, bottom, b).is_none(), "both moved into the symbol");
|
||||
assert!(s.elements_on(bottom).is_empty());
|
||||
let t = element(&s, top, inst).unwrap().transform.translation();
|
||||
assert!((t.x - center.x).abs() < 1e-3 && (t.y - center.y).abs() < 1e-3, "registered at the combined centre");
|
||||
let sym = s.doc.library.iter().find(|x| x.name == "Both").unwrap();
|
||||
let names: Vec<&str> = sym.timeline.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, vec!["Top", "Bottom"], "the layers, as they were stacked");
|
||||
let inside: Vec<ElementId> = sym.timeline.layers.iter().flat_map(|l| l.keyframes[0].elements.iter().map(|e| e.id)).collect();
|
||||
assert_eq!(inside, vec![a, b]);
|
||||
// It looks the same as before.
|
||||
let now = px(&s);
|
||||
for (x, y) in [(225, 125), (50, 50), (150, 150)] {
|
||||
assert_eq!(now.pixel(x, y), was.pixel(x, y), "at ({x}, {y})");
|
||||
}
|
||||
// Break Apart brings both back onto the top layer, selected.
|
||||
let v = run(&mut s, "modify.break_apart", json!({}));
|
||||
assert_eq!(v["created"], 2);
|
||||
assert_eq!(s.selection.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_apart_works_on_each_layer() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
for (l, id) in [(top, a), (bottom, b)] {
|
||||
run(&mut s, "element.select", json!({"ids": [id.0], "layer": l.0}));
|
||||
run(&mut s, "modify.convert_to_symbol", json!({}));
|
||||
}
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
assert_eq!(s.selected_layers(), vec![top, bottom]);
|
||||
let v = run(&mut s, "modify.break_apart", json!({}));
|
||||
assert_eq!(v["created"], 2, "{v}");
|
||||
assert!(s.elements_on(top).iter().chain(s.elements_on(bottom).iter()).all(|e| matches!(e.kind, ElementKind::Shape(_))));
|
||||
assert_eq!(s.selected_layers(), vec![top, bottom]);
|
||||
}
|
||||
|
||||
// ----- the marquee across layers with raw parts (ADR 0041) ------------------------------------
|
||||
|
||||
/// Raw squares on two layers: Top's 0..100, Bottom's 200..300 (both 0..100 high).
|
||||
fn raw_two_layers() -> (Session, LayerId, LayerId) {
|
||||
let mut s = Session::default();
|
||||
s.style.object_drawing = false;
|
||||
let bottom = s.layer;
|
||||
run(&mut s, "draw.rect", json!({"x": 200, "y": 0, "w": 100, "h": 100, "stroke": null}));
|
||||
let top = LayerId(run(&mut s, "layer.new", json!({"name": "Top"}))["layer"].as_u64().unwrap());
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
s.mark_saved();
|
||||
(s, top, bottom)
|
||||
}
|
||||
|
||||
fn area(e: &Element) -> f64 {
|
||||
let ElementKind::Shape(sh) = &e.kind else { return 0.0 };
|
||||
sh.path
|
||||
.flatten(&e.transform, 0.05)
|
||||
.iter()
|
||||
.map(|pl| {
|
||||
let n = pl.points.len();
|
||||
let twice: f64 = (0..n).filter_map(|i| Some(f64::from(pl.points.get(i)?.cross(*pl.points.get((i + 1) % n)?)))).sum();
|
||||
twice * 0.5
|
||||
})
|
||||
.sum::<f64>()
|
||||
.abs()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_marquee_cuts_raw_parts_on_every_layer() {
|
||||
let (mut s, top, bottom) = raw_two_layers();
|
||||
let saved = s.doc.clone();
|
||||
// The lower half of both squares.
|
||||
let v = run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": 50, "x1": 310, "y1": 110}));
|
||||
assert_eq!(v["cut"], 2, "one piece inside on each layer: {v}");
|
||||
assert_eq!(s.selected_layers(), vec![top, bottom]);
|
||||
for l in [top, bottom] {
|
||||
let picked: Vec<Arc<Element>> = s.elements_on(l).into_iter().filter(|e| s.selection.contains(l, e.id)).collect();
|
||||
assert_eq!(picked.len(), 1);
|
||||
assert!((area(&picked[0]) - 5000.0).abs() < 1.0, "half the square: {}", area(&picked[0]));
|
||||
assert_eq!(s.elements_on(l).len(), 2, "cut in two on its own layer");
|
||||
}
|
||||
assert!(!s.is_dirty(), "a marquee alone leaves the document saved");
|
||||
// Letting go takes the cut back exactly, on both layers.
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
run(&mut s, "element.pick", json!({"x": 900, "y": 900}));
|
||||
assert!(s.doc == saved, "the cut is healed on both layers");
|
||||
|
||||
// A move uses the cut: one step from before it, and the pieces merge back per layer.
|
||||
run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": 50, "x1": 310, "y1": 110}));
|
||||
let steps = s.history_len();
|
||||
s.begin_gesture("Move");
|
||||
run(&mut s, "element.translate", json!({"dx": 0, "dy": 40}));
|
||||
run(&mut s, "draw.drop", json!({}));
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), steps + 1, "the move and the drop are one step");
|
||||
for l in [top, bottom] {
|
||||
let total: f64 = s.elements_on(l).iter().map(|e| area(e)).sum();
|
||||
assert!((total - 10_000.0).abs() < 2.0, "both halves still there: {total}");
|
||||
let lowest = s.elements_on(l).iter().map(|e| s.element_bounds_on(l, e.id).max.y).fold(f32::MIN, f32::max);
|
||||
assert!((lowest - 140.0).abs() < 0.5, "the lower half moved down: {lowest}");
|
||||
}
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc == saved, "one undo goes straight back to the whole drawings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_marquee_with_shift_adds_across_layers_and_raw_merge_works_per_layer() {
|
||||
let (mut s, top, bottom) = raw_two_layers();
|
||||
run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": -10, "x1": 50, "y1": 110}));
|
||||
assert_eq!(s.selected_layers(), vec![top]);
|
||||
assert_eq!(s.layer, top);
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 250, "y0": -10, "x1": 310, "y1": 110, "add": true}));
|
||||
assert_eq!(s.selected_layers(), vec![top, bottom], "Shift keeps the first layer's parts");
|
||||
// Merging the selection again joins each layer's pieces on that layer only.
|
||||
run(&mut s, "element.set_fill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "raw.merge", json!({}));
|
||||
for l in [top, bottom] {
|
||||
assert!(s.elements_on(l).len() <= 2, "{} pieces", s.elements_on(l).len());
|
||||
let total: f64 = s.elements_on(l).iter().map(|e| area(e)).sum();
|
||||
assert!((total - 10_000.0).abs() < 2.0, "{total}");
|
||||
}
|
||||
// A marquee that starts over a layer with nothing makes the topmost hit layer active.
|
||||
run(&mut s, "layer.select", json!({"layer": top.0}));
|
||||
run(&mut s, "raw.select_rect", json!({"x0": 190, "y0": -10, "x1": 310, "y1": 110}));
|
||||
assert_eq!(s.layer, bottom);
|
||||
}
|
||||
|
||||
// ----- robustness ------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn every_command_survives_a_selection_on_two_layers() {
|
||||
let mut cmds = crate::commands();
|
||||
cmds.retain(|c| !c.id.starts_with("file."));
|
||||
for spec in cmds {
|
||||
for p in [json!({}), json!({"dx": 3, "dy": 4, "x": 50, "y": 50, "name": "x", "alpha": 0.5, "filters": [], "mode": "multiply", "loop": "loop", "kind": "movie_clip", "color": "#123456", "profile": "bulge", "text": "t"})] {
|
||||
let (mut s, ..) = two_layers();
|
||||
let _ = s.execute(spec.id, &p);
|
||||
// Undo and redo always work, and the selection stays on visible, unlocked layers.
|
||||
let _ = s.undo();
|
||||
let _ = s.redo();
|
||||
for (l, _) in s.selection.iter() {
|
||||
assert!(s.selectable(l), "{}: selection on an unselectable layer", spec.id);
|
||||
}
|
||||
let _ = anicraft_render::render_frame(&s.doc, 0, 0.25);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Timings across layers (ADR 0044's table; run with
|
||||
/// `cargo test -p anicraft-engine selection_timings -- --ignored --nocapture`).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn selection_timings() {
|
||||
let mut s = Session::default();
|
||||
s.style.object_drawing = false;
|
||||
// 8 layers, each with 6 × 6 outlined raw squares: 288 fills and their outlines.
|
||||
for l in 0..8 {
|
||||
if l > 0 {
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
}
|
||||
for i in 0..6 {
|
||||
for j in 0..6 {
|
||||
run(&mut s, "draw.rect", json!({"x": i * 50 + l * 3, "y": j * 50 + l * 3, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
}
|
||||
}
|
||||
}
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let layers = s.doc.timeline(0).layers.len();
|
||||
let shapes: usize = s.doc.timeline(0).layers.iter().map(|l| s.elements_on(l.id).len()).sum();
|
||||
eprintln!("{shapes} raw shapes on {layers} layers");
|
||||
let time = |s: &mut Session, label: &str, reps: u32, f: &dyn Fn(&mut Session)| {
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..reps {
|
||||
f(s);
|
||||
}
|
||||
eprintln!("{label}: {:.2} ms", t.elapsed().as_secs_f64() * 1000.0 / f64::from(reps));
|
||||
};
|
||||
time(&mut s, "select all", 20, &|s| {
|
||||
let _ = s.execute("edit.select_all", &json!({}));
|
||||
});
|
||||
time(&mut s, "fix_selection (after every command)", 20, &|s| s.fix_selection());
|
||||
s.begin_gesture("Move");
|
||||
time(&mut s, "move frame, every layer", 20, &|s| {
|
||||
let _ = s.execute("element.translate", &json!({"dx": 0.5, "dy": 0}));
|
||||
});
|
||||
time(&mut s, "snapping move frame, every layer", 20, &|s| {
|
||||
let _ = s.execute("element.translate", &json!({"dx": 0.5, "dy": 0, "snap": 10, "from": [0, 0]}));
|
||||
});
|
||||
s.end_gesture();
|
||||
s.undo().unwrap();
|
||||
time(&mut s, "marquee cut and heal, every layer", 10, &|s| {
|
||||
let _ = s.execute("raw.select_rect", &json!({"x0": 65, "y0": 65, "x1": 215, "y1": 215}));
|
||||
let _ = s.execute("edit.deselect", &json!({}));
|
||||
});
|
||||
let v = run(&mut s, "raw.select_rect", json!({"x0": 65, "y0": 65, "x1": 215, "y1": 215}));
|
||||
eprintln!("a marquee selects {} parts on {} layers ({} cut)", s.selection.len(), s.selected_layers().len(), v["cut"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_layer_name_selects_its_artwork() {
|
||||
let (mut s, top, bottom, a, b) = two_layers();
|
||||
// Another element on Bottom: the click takes both.
|
||||
run(&mut s, "layer.select", json!({"layer": bottom.0}));
|
||||
let c = el_id(&run(&mut s, "draw.rect", json!({"x": 400, "y": 400, "w": 20, "h": 20})));
|
||||
run(&mut s, "layer.select", json!({"layer": top.0}));
|
||||
assert!(s.selection.is_empty(), "without `select`, as before");
|
||||
let v = run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true}));
|
||||
assert_eq!(v["selected"], json!([b.0, c.0]));
|
||||
assert_eq!(s.layer, bottom);
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(bottom, b), (bottom, c)]);
|
||||
// Again on the same layer: still all of it. On a locked layer: active, nothing selected.
|
||||
run(&mut s, "element.select", json!({"ids": [a.0]}));
|
||||
run(&mut s, "layer.select", json!({"layer": top.0, "select": true}));
|
||||
assert_eq!(s.selection.iter().collect::<Vec<_>>(), vec![(top, a)]);
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": bottom.0}));
|
||||
run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true}));
|
||||
assert_eq!(s.layer, bottom);
|
||||
assert!(s.selection.is_empty());
|
||||
// At a frame where the layer is empty, nothing is selected.
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": bottom.0}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({"layer": top.0, "frame": 5}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 5}));
|
||||
run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true}));
|
||||
assert!(s.selection.is_empty());
|
||||
}
|
||||
@@ -215,16 +215,16 @@ fn undoable_bulk_deletions_ask_but_are_not_blocked() {
|
||||
fn copy_paste_cut_and_paste_in_place() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20}));
|
||||
let orig = s.selection[0];
|
||||
let orig = s.selection.ids().next().unwrap();
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
let els = s.visible_elements();
|
||||
assert_eq!(els.len(), 2);
|
||||
assert_ne!(s.selection[0], orig, "pasted elements get fresh ids");
|
||||
let pasted = els.iter().find(|e| e.id == s.selection[0]).unwrap();
|
||||
assert_ne!(s.selection.ids().next().unwrap(), orig, "pasted elements get fresh ids");
|
||||
let pasted = els.iter().find(|e| e.id == s.selection.ids().next().unwrap()).unwrap();
|
||||
assert_eq!(pasted.transform.translation(), Vec2::new(30.0, 30.0));
|
||||
run(&mut s, "edit.paste_in_place", json!({}));
|
||||
let last = s.visible_elements().into_iter().find(|e| e.id == s.selection[0]).unwrap();
|
||||
let last = s.visible_elements().into_iter().find(|e| e.id == s.selection.ids().next().unwrap()).unwrap();
|
||||
assert_eq!(last.transform.translation(), Vec2::new(20.0, 20.0));
|
||||
// paste centred on a point
|
||||
run(&mut s, "edit.paste", json!({"x": 500, "y": 400}));
|
||||
@@ -241,12 +241,17 @@ fn copy_paste_cut_and_paste_in_place() {
|
||||
fn clipboard_carries_symbols_into_another_document() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
run(&mut s, "layer.select", json!({"index": 0}));
|
||||
// Select All takes every unlocked layer's artwork (ADR 0044).
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let copied = run(&mut s, "edit.copy", json!({}));
|
||||
let used = s.doc.library.len();
|
||||
run(&mut s, "file.new", json!({"confirm": true}));
|
||||
assert!(s.doc.library.is_empty());
|
||||
run(&mut s, "edit.paste_in_place", json!({}));
|
||||
assert_eq!(s.doc.library.len(), 1, "the Ball symbol came along");
|
||||
assert!(s.doc.library.iter().any(|x| x.name == "Ball"), "the Ball symbol came along");
|
||||
assert_eq!(s.doc.library.len(), used);
|
||||
// Each copied layer lands on a layer of its own, made for it here.
|
||||
assert_eq!(s.doc.timeline(0).layers.len() as u64, copied["layers"].as_u64().unwrap());
|
||||
assert!(!anicraft_doc::evaluate(&s.doc, 0).items.is_empty(), "and it renders");
|
||||
let ids: Vec<u64> = s.doc.library.iter().map(|x| x.id.0).collect();
|
||||
assert!(s.doc.next_id > *ids.iter().max().unwrap());
|
||||
@@ -280,10 +285,10 @@ fn align_and_distribute() {
|
||||
}
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "align.left", json!({}));
|
||||
let lefts: Vec<f32> = s.selection.iter().map(|id| s.element_bounds(*id).min.x).collect();
|
||||
let lefts: Vec<f32> = s.selection.ids().map(|id| s.element_bounds(id).min.x).collect();
|
||||
assert!(lefts.iter().all(|x| (x - 10.0).abs() < 1e-3), "{lefts:?}");
|
||||
run(&mut s, "align.distribute_v", json!({}));
|
||||
let mut ys: Vec<f32> = s.selection.iter().map(|id| s.element_bounds(*id).center().y).collect();
|
||||
let mut ys: Vec<f32> = s.selection.ids().map(|id| s.element_bounds(id).center().y).collect();
|
||||
ys.sort_by(f32::total_cmp);
|
||||
assert!(((ys[1] - ys[0]) - (ys[2] - ys[1])).abs() < 1e-3, "{ys:?}");
|
||||
// a single element aligns to the stage
|
||||
@@ -481,13 +486,13 @@ fn commands_png(s: &Session) -> Vec<u8> {
|
||||
fn pick_selects_topmost() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100}));
|
||||
let a = s.selection[0];
|
||||
let a = s.selection.ids().next().unwrap();
|
||||
run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100}));
|
||||
let b = s.selection[0];
|
||||
let b = s.selection.ids().next().unwrap();
|
||||
run(&mut s, "element.pick", json!({"x": 75, "y": 75}));
|
||||
assert_eq!(s.selection, vec![b]);
|
||||
assert_eq!(s.selection.ids().collect::<Vec<_>>(), vec![b]);
|
||||
run(&mut s, "element.pick", json!({"x": 10, "y": 10}));
|
||||
assert_eq!(s.selection, vec![a]);
|
||||
assert_eq!(s.selection.ids().collect::<Vec<_>>(), vec![a]);
|
||||
run(&mut s, "element.pick", json!({"x": 500, "y": 500}));
|
||||
assert!(s.selection.is_empty());
|
||||
}
|
||||
@@ -547,6 +552,12 @@ fn panic_hunt_every_command() {
|
||||
json!({"id": 3, "profile": [[0, 1e30, -5], ["x"], [0.5, 16, 16]], "index": u64::MAX, "t": -0.5, "left": 1e9, "width": f64::MAX}),
|
||||
json!({"id": 3, "profile": "taper_both", "index": 0, "t": 1, "x": 1e30, "y": -1e30, "left": 0, "right": 16}),
|
||||
json!({"profile": (0..500).map(|i| json!([f64::from(i) / 500.0, 2, 2])).collect::<Vec<_>>()}),
|
||||
// Stroke styles (ADR 0046): junk, extremes and patterns that would be very fine.
|
||||
json!({"cap": "none", "join": "miter", "miter": 100, "dash": [0, 1e-30], "dash_offset": -1e4, "style": "dashed"}),
|
||||
json!({"cap": 7, "join": "mitre", "miter": f64::NAN, "dash": vec![1e4; 16], "dot_spacing": 0, "style": "dotted"}),
|
||||
json!({"style": "dotted", "dot_spacing": 0, "x0": 0, "y0": 0, "x1": 1e6, "y1": 1, "stroke_width": 1000}),
|
||||
json!({"dash": [0.001, 0.001], "x0": -1e6, "y0": 0, "x1": 1e6, "y1": 0, "x": 0, "y": 0}),
|
||||
json!({"dash": "x", "cap": "square", "style": "ragged", "dash_offset": 1e30}),
|
||||
json!({"sound": SOUND, "sync": "stream", "repeat": 9999, "loop": true, "extend": true, "frame": 99_999}),
|
||||
json!({"sound": SOUND, "sync": "nope", "repeat": 0, "loop": "x", "name": ""}),
|
||||
json!({"sound": SOUND, "frame": 3, "extend": true, "name": "renamed"}),
|
||||
@@ -580,10 +591,38 @@ fn panic_hunt_every_command() {
|
||||
json!({"points": [[0, 0], [40, 40], [90, 5]], "size": 30, "mode": "selected_fills", "x": 30, "y": 30, "slop": 0}),
|
||||
json!({"points": [[45, 45]], "size": 2000, "mode": "inside", "x": 45, "y": 45, "other": true, "fill": false, "stroke": true}),
|
||||
json!({"points": [[5, 5], [55, 55]], "size": 4, "mode": "lines", "shape": "square", "x": 1, "y": 1, "fill": "yes"}),
|
||||
// The Selection tool on raw shapes (ADR 0041): corners and edges of the raw rectangles,
|
||||
// stale and hostile point lists, huge snaps and marquees, segments that aren't there.
|
||||
json!({"x": 30, "y": 30, "to_x": 1e7, "to_y": -1e7, "snap": 1e9, "merge": false, "dx": 1e7, "dy": -1e7}),
|
||||
json!({"x": 60, "y": 45, "to_x": 30.1, "to_y": 30, "snap": 10, "points": [[1, 99_999], [u64::MAX, 0]], "cmd": 1, "t": 2}),
|
||||
json!({"x": 45, "y": 30, "dx": 5, "dy": 5, "cmd": u64::MAX, "t": f64::NAN, "id": 2, "slop": 1e9}),
|
||||
json!({"x0": 10, "y0": 10, "x1": 45, "y1": 75, "add": true, "from": [1, 2, 3], "snap": 3}),
|
||||
json!({"x0": -1e7, "y0": 1e7, "x1": 1e7, "y1": -1e7, "add": false, "from": [45, 45], "snap": 0.2}),
|
||||
json!({"x0": 30, "y0": 30, "x1": 30, "y1": 30, "point_slop": -5, "ids": [u64::MAX], "points": "x"}),
|
||||
// Subselection on raw shapes (ADR 0042): handles that aren't there or move too far,
|
||||
// anchors to move along that are hostile, connected sets of anything.
|
||||
json!({"id": 3, "cmd": 1, "slot": 2, "dx": 1e30, "dy": 0, "x": 30, "y": 30, "to_x": 31, "to_y": 30, "with": [[30, 30], [1e30, 0]]}),
|
||||
json!({"id": 5, "cmd": u64::MAX, "slot": 9, "dx": 1, "dy": 1, "with": "x", "x0": 0, "y0": 0, "x1": 1e9, "y1": 1e9}),
|
||||
json!({"id": 4, "cmd": 2, "slot": 1, "dx": -3, "dy": 2, "x": 60, "y": 60, "to_x": 61, "to_y": 61, "with": [[60, 60], [30, 90], [90, 30]], "merge": false}),
|
||||
// Kept scripts (ADR 0013 tier 1): odd text, unknown languages, class names that aren't.
|
||||
json!({"text": "\u{0}\r\n]]>\u{202e}stop();", "language": "other", "class": "a.b", "base": "c", "symbol": 1}),
|
||||
json!({"text": "x".repeat(1 << 20), "language": 3, "class": "not a class", "base": ""}),
|
||||
json!({"text": "", "language": "ActionScript3", "class": "", "base": "Orphan"}),
|
||||
// Bones (ADR 0043): the rigged session's bones are 100 and 102 (its armature layer 101),
|
||||
// its instances 10–12.
|
||||
json!({"bone": 102, "x": 1e30, "y": -1e30, "local": [1e9, "a"], "frame": 99_999}),
|
||||
json!({"bone": 102, "x": 0, "y": 0, "local": [f64::MAX, 0], "angle": 1e9, "rotate_by": -1e9, "dx": 1e7, "dy": -1e7}),
|
||||
json!({"bone": 100, "min": 400, "max": -400, "constrain": true, "pinned": "x"}),
|
||||
json!({"bone": 100, "min": 10, "max": 10, "constrain": "yes", "pinned": true, "x": 250, "y": 250}),
|
||||
json!({"from": 10, "to": 12, "head": [0, 0], "tail": [1e30, 0], "name": "x".repeat(300)}),
|
||||
json!({"from": 12, "to": 10, "head": [5], "tail": "x", "bone": u64::MAX}),
|
||||
json!({"from": 11, "to": 13, "head": [-1e6, 1e6], "layer": 101}),
|
||||
// Edit Multiple Frames (ADR 0047): ranges past the end or reversed, items that aren't
|
||||
// there or aren't triples, moves at the limits.
|
||||
json!({"first": 0, "last": 99_999, "dx": 1e7, "dy": -1e7, "items": [[0, 0, 1], "x", [u64::MAX, u64::MAX, u64::MAX]]}),
|
||||
json!({"first": u64::MAX, "last": 0, "dx": 5, "dy": 5, "items": []}),
|
||||
json!({"first": 40, "last": 0, "dx": 3, "dy": -2}),
|
||||
json!({"first": 0, "last": 100_001, "dx": f64::NAN, "dy": 0, "items": [[1, 2]]}),
|
||||
];
|
||||
// File commands are exercised separately (they touch the disk).
|
||||
let skip = |id: &str| id.starts_with("file.");
|
||||
@@ -617,7 +656,28 @@ fn panic_hunt_every_command() {
|
||||
for p in [json!({"x": 0, "y": 0, "w": 60, "h": 60}), json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"}), json!({"x": 1, "y": 1, "w": 10, "h": 10, "radius": 5})] {
|
||||
raw.execute("draw.rect", &p).unwrap();
|
||||
}
|
||||
for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw] {
|
||||
// An armature: two bones, posed at two frames with a limit and a pin (ADR 0043).
|
||||
let (mut rig, b1, b2) = crate::tests_bone::rigged();
|
||||
for (id, p) in [("bone.pose", json!({"bone": b1, "angle": 30, "frame": 8})), ("bone.set_limits", json!({"bone": b2, "min": -30, "max": 30})), ("bone.pin", json!({"bone": b1, "pinned": true}))] {
|
||||
rig.execute(id, &p).unwrap();
|
||||
}
|
||||
assert_eq!((b1, b2), (100, 102), "the hostile params name these bones");
|
||||
rig.set_frame(4);
|
||||
// Raw drawings and an object on two layers, selected on both through a marquee's cut that
|
||||
// is still provisional (ADR 0041, 0044).
|
||||
let mut layered = Session::default();
|
||||
layered.style.object_drawing = false;
|
||||
for (id, p) in [
|
||||
("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})),
|
||||
("layer.new", json!({})),
|
||||
("draw.rect", json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"})),
|
||||
("draw.rect", json!({"x": 200, "y": 0, "w": 20, "h": 20, "object": true})),
|
||||
("raw.select_rect", json!({"x0": 20, "y0": 20, "x1": 250, "y1": 50})),
|
||||
] {
|
||||
layered.execute(id, &p).unwrap();
|
||||
}
|
||||
assert_eq!(layered.selected_layers().len(), 2, "the fuzz starts with a selection on two layers");
|
||||
for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered] {
|
||||
let mut s = start;
|
||||
for spec in commands().iter().filter(|c| !skip(c.id)) {
|
||||
for p in &hostile {
|
||||
@@ -843,7 +903,7 @@ fn moving_an_anchor_brings_its_handles_and_is_one_undo_step_in_a_gesture() {
|
||||
fn moves_follow_the_element_transform() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100}));
|
||||
let id = s.selection[0].0;
|
||||
let id = s.selection.ids().next().unwrap().0;
|
||||
run(&mut s, "element.set_transform", json!({"sx": 2, "rotation": 90}));
|
||||
let a0 = stage_anchor(&s, id, 0);
|
||||
run(&mut s, "path.move_points", json!({"id": id, "points": [[0, 0]], "dx": 10, "dy": 0}));
|
||||
@@ -854,7 +914,7 @@ fn moves_follow_the_element_transform() {
|
||||
fn add_delete_and_convert_points() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100}));
|
||||
let id = s.selection[0].0;
|
||||
let id = s.selection.ids().next().unwrap().0;
|
||||
let area = |s: &Session| shape_path(s, id).flatten(&anicraft_geom::Affine::IDENTITY, 0.1)[0].points.len();
|
||||
let n0 = shape_path(&s, id).editable_anchors().len();
|
||||
// The closing edge (left side, x = 0) can take a point too.
|
||||
@@ -876,7 +936,7 @@ fn add_delete_and_convert_points() {
|
||||
assert!(s.execute("path.delete_points", &json!({"id": id, "cmds": [0]})).is_err());
|
||||
// Symbols are not point-editable.
|
||||
run(&mut s, "modify.convert_to_symbol", json!({}));
|
||||
let inst = s.selection[0].0;
|
||||
let inst = s.selection.ids().next().unwrap().0;
|
||||
assert!(s.execute("path.add_point", &json!({"id": inst, "x": 0, "y": 0})).is_err());
|
||||
}
|
||||
|
||||
@@ -1179,7 +1239,7 @@ fn opening_an_xfl_folder_imports_it_untitled() {
|
||||
let text = s.doc.timeline(s.scene).layers[0].keyframes[0].elements.iter().find(|e| matches!(e.kind, ElementKind::Text(_))).cloned().expect("a text element");
|
||||
assert_eq!(text.name, "title");
|
||||
assert!(dl.items.iter().any(|i| matches!(i.fill, Some(anicraft_doc::Paint::Solid(c)) if c == anicraft_doc::Rgba::hex(0x0000ff))), "the text renders");
|
||||
s.selection = vec![text.id];
|
||||
s.select_only([text.id]);
|
||||
run(&mut s, "text.edit", json!({"text": "Hello again"}));
|
||||
// Saved and opened again, it is the same text.
|
||||
let file = dir.join("imported.anicraft");
|
||||
@@ -1738,9 +1798,10 @@ fn images_import_as_bitmaps_render_save_and_export() {
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "edit.duplicate", json!({}));
|
||||
let svg = crate::cmds_file::frame_svg(&s.doc, 0);
|
||||
// Two images, three instances (the JPEG one was duplicated): each image is embedded once.
|
||||
// Two images, four instances (Select All took both layers, ADR 0044): each image is
|
||||
// embedded once.
|
||||
assert_eq!(svg.matches("data:image/png;base64,").count(), 2);
|
||||
assert_eq!(svg.matches("<pattern ").count(), 3);
|
||||
assert_eq!(svg.matches("<pattern ").count(), 4);
|
||||
// Undo takes an import back, bitmap and all.
|
||||
let n = s.doc.bitmaps.len();
|
||||
s.undo().unwrap();
|
||||
@@ -1765,7 +1826,7 @@ fn library_bitmaps_place_centred_on_the_stage() {
|
||||
// Placing it again from the Library adds a second picture, centred, on the current layer.
|
||||
let v = run(&mut s, "library.place", json!({"bitmap": bitmap, "x": 100, "y": 50}));
|
||||
let id = anicraft_doc::ElementId(v["element"].as_u64().unwrap());
|
||||
assert_eq!(s.selection, vec![id]);
|
||||
assert_eq!(s.selection.ids().collect::<Vec<_>>(), vec![id]);
|
||||
let el = s.active_layer().unwrap().keyframe_at(s.frame).unwrap().elements.iter().find(|e| e.id == id).unwrap().clone();
|
||||
assert_eq!(el.name, "dot.png");
|
||||
assert_eq!(el.transform.apply(anicraft_geom::Vec2::new(3.0, 2.0)), anicraft_geom::Vec2::new(100.0, 50.0), "centred on x/y");
|
||||
@@ -1853,7 +1914,7 @@ fn text_lays_out_renders_edits_saves_and_breaks_apart() {
|
||||
let mut s = Session::default();
|
||||
let v = run(&mut s, "text.create", json!({"text": "Hello", "x": 100, "y": 50, "size": 64, "color": "#cc2200"}));
|
||||
let id = ElementId(v["element"].as_u64().unwrap());
|
||||
assert_eq!(s.selection, vec![id]);
|
||||
assert_eq!(s.selection.ids().collect::<Vec<_>>(), vec![id]);
|
||||
assert!(v["width"].as_f64().unwrap() > 64.0);
|
||||
let text = |s: &Session| match &s.visible_elements().iter().find(|e| e.id == id).unwrap().kind {
|
||||
ElementKind::Text(t) => t.clone(),
|
||||
@@ -1907,7 +1968,7 @@ fn text_lays_out_renders_edits_saves_and_breaks_apart() {
|
||||
run(&mut s, "element.select", json!({"ids": [id.0]}));
|
||||
let before = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
run(&mut s, "modify.break_apart", json!({}));
|
||||
assert!(matches!(s.visible_elements().iter().find(|e| s.selection.contains(&e.id)).unwrap().kind, ElementKind::Shape(_)));
|
||||
assert!(matches!(s.visible_elements().iter().find(|e| s.selection.has_id(e.id)).unwrap().kind, ElementKind::Shape(_)));
|
||||
assert_eq!(anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().data, before.data, "a shape exactly like the text");
|
||||
let fonts = run(&mut s, "text.fonts", json!({}));
|
||||
assert!(fonts["families"].as_array().is_some_and(|f| !f.is_empty()));
|
||||
|
||||
@@ -16,7 +16,7 @@ fn with_instance(kind: &str) -> (Session, u64) {
|
||||
let id = s.execute("draw.rect", &json!({"x": 100, "y": 100, "w": 80, "h": 40})).unwrap()["element"].as_u64().unwrap();
|
||||
s.execute("element.select", &json!({"ids": [id]})).unwrap();
|
||||
let v = s.execute("modify.convert_to_symbol", &json!({"name": "Thing"})).unwrap();
|
||||
let inst = v["instance"].as_u64().or_else(|| s.selection.first().map(|e| e.0)).unwrap();
|
||||
let inst = v["instance"].as_u64().or_else(|| s.selection.first().map(|(_, e)| e.0)).unwrap();
|
||||
s.execute("symbol.set_kind", &json!({"kind": kind})).unwrap();
|
||||
(s, inst)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Bones and inverse kinematics end to end (ADR 0043): building an armature with the Bone
|
||||
//! tool's commands, posing by angle and by IK, pose tweens, limits and pins, removal, undo,
|
||||
//! the file format, refusals, analytic renders and plug-in policy.
|
||||
|
||||
use super::*;
|
||||
use anicraft_doc::{BlendMode, ColorEffect, Document, ElementKind, LoopMode, Paint, Rgba, Shape, Stage, Symbol, SymbolId, SymbolKind, Timeline};
|
||||
use anicraft_geom::{Affine, Path};
|
||||
use anicraft_render::render_frame;
|
||||
use serde_json::json;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const ROOT: u64 = 10;
|
||||
pub(crate) const ARM: u64 = 11;
|
||||
pub(crate) const HAND: u64 = 12;
|
||||
const SHAPE: u64 = 13;
|
||||
|
||||
/// A 500 × 300 stage, 20 frames, with three instances of a 100 × 10 black bar (registration at
|
||||
/// its left end) along y = 100 from x = 100, 200 and 300, and a plain shape below them.
|
||||
pub(crate) fn three_bars() -> Session {
|
||||
let mut d = Document { stage: Stage { width: 500, height: 300, ..Stage::default() }, ..Document::default() };
|
||||
let bar = SymbolId(1);
|
||||
let mut inner = Layer::new(LayerId(2), "bar");
|
||||
inner.keyframes[0] = Arc::new({
|
||||
let mut k = Keyframe::new(0, 1);
|
||||
k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) }));
|
||||
k
|
||||
});
|
||||
d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(inner)] } }));
|
||||
let inst = |id: u64, x: f32| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 100.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: bar, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } });
|
||||
let shape = Arc::new(Element { id: ElementId(SHAPE), name: String::new(), transform: Affine::translate(100.0, 250.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::BLACK))) });
|
||||
let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]);
|
||||
l.keyframes = vec![Arc::new({
|
||||
let mut k = Keyframe::new(0, 20);
|
||||
k.elements = vec![inst(ROOT, 100.0), inst(ARM, 200.0), inst(HAND, 300.0), shape];
|
||||
k
|
||||
})];
|
||||
d.next_id = 100;
|
||||
Session::new(d)
|
||||
}
|
||||
|
||||
/// [`three_bars`] rigged as a chain: shoulder (200, 100) → elbow (300, 100) → wrist (400, 100).
|
||||
pub(crate) fn rigged() -> (Session, u64, u64) {
|
||||
let mut s = three_bars();
|
||||
let b1 = run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM, "head": [200, 100], "tail": [300, 100]}))["bone"].as_u64().unwrap();
|
||||
let b2 = run(&mut s, "bone.add", json!({"from": ARM, "to": HAND, "tail": [400, 100]}))["bone"].as_u64().unwrap();
|
||||
(s, b1, b2)
|
||||
}
|
||||
|
||||
fn bone_at(s: &mut Session, frame: u32, bone: u64) -> Value {
|
||||
let v = run(s, "bone.info", json!({"frame": frame}));
|
||||
v["armatures"][0]["bones"].as_array().unwrap().iter().find(|b| b["id"] == bone).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn pt(v: &Value) -> Vec2 {
|
||||
Vec2::new(v[0].as_f64().unwrap() as f32, v[1].as_f64().unwrap() as f32)
|
||||
}
|
||||
|
||||
fn transform_of(s: &Session, frame: u32, id: u64) -> Affine {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
tl.layers.iter().find_map(|l| evaluate_layer_elements(l, frame).and_then(|(_, e)| e.iter().find(|e| e.id.0 == id).map(|e| e.transform))).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bone_tool_moves_instances_onto_an_armature_layer() {
|
||||
let (mut s, b1, b2) = rigged();
|
||||
let tl = s.doc.timeline(0);
|
||||
assert_eq!(tl.layers.len(), 2);
|
||||
let arm = &tl.layers[0];
|
||||
assert_eq!(arm.kind, LayerKind::Armature);
|
||||
assert_eq!(arm.name, "Armature_1");
|
||||
assert_eq!(s.layer, arm.id, "the armature layer is active");
|
||||
let ids: Vec<u64> = arm.keyframes[0].elements.iter().map(|e| e.id.0).collect();
|
||||
assert_eq!(ids, vec![ROOT, ARM, HAND]);
|
||||
assert_eq!((arm.keyframes[0].start, arm.keyframes[0].duration), (0, 20), "the pose spans the timeline");
|
||||
let rest: Vec<u64> = tl.layers[1].keyframes[0].elements.iter().map(|e| e.id.0).collect();
|
||||
assert_eq!(rest, vec![SHAPE], "the instances left their layer; the shape stayed");
|
||||
// Nothing moved on the stage.
|
||||
assert_eq!(transform_of(&s, 0, HAND), Affine::translate(300.0, 100.0));
|
||||
let b = bone_at(&mut s, 0, b2);
|
||||
assert!(pt(&b["head"]).distance(Vec2::new(300.0, 100.0)) < 1e-3, "the second bone starts where the first ends");
|
||||
assert!(pt(&b["tail"]).distance(Vec2::new(400.0, 100.0)) < 1e-3);
|
||||
assert_eq!(b["parent_bone"], b1);
|
||||
assert_eq!(bone_at(&mut s, 0, b1)["parent_bone"], Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bone_add_refuses_what_cant_be_joined() {
|
||||
let mut s = three_bars();
|
||||
let bad = |s: &mut Session, p: Value| s.execute("bone.add", &p).unwrap_err().to_string();
|
||||
assert!(bad(&mut s, json!({"from": ROOT, "to": ROOT})).contains("two different"));
|
||||
assert!(bad(&mut s, json!({"from": ROOT, "to": SHAPE})).contains("symbol"));
|
||||
assert!(bad(&mut s, json!({"from": ROOT, "to": 999})).contains("no instance"));
|
||||
assert!(bad(&mut s, json!({"from": ROOT})).contains("required"));
|
||||
assert!(bad(&mut s, json!({"from": ROOT, "to": ARM, "head": [1, "x"]})).contains("[x, y]"));
|
||||
run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM}));
|
||||
assert!(bad(&mut s, json!({"from": HAND, "to": ARM})).contains("armature"), "start on the armature");
|
||||
assert!(bad(&mut s, json!({"from": ARM, "to": ROOT})).contains("root"));
|
||||
run(&mut s, "bone.add", json!({"from": ROOT, "to": HAND}));
|
||||
assert!(bad(&mut s, json!({"from": ARM, "to": HAND})).contains("already"));
|
||||
assert_eq!(s.history_len(), 2, "refusals leave no undo steps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ik_drags_reach_and_one_drag_is_one_undo_step() {
|
||||
let (mut s, b1, b2) = rigged();
|
||||
let steps = s.history_len();
|
||||
s.begin_gesture("Drag Bone");
|
||||
let mut last = Value::Null;
|
||||
for i in 0..=20 {
|
||||
let t = i as f32 / 20.0;
|
||||
last = run(&mut s, "bone.solve", json!({"bone": b2, "x": 400.0 - 100.0 * t, "y": 100.0 + 80.0 * t}));
|
||||
}
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), steps + 1, "one drag, one undo step");
|
||||
assert_eq!(last["reached"], true, "{last}");
|
||||
let end = pt(&bone_at(&mut s, 0, b2)["tail"]);
|
||||
assert!(end.distance(Vec2::new(300.0, 180.0)) < 0.5, "{end:?}");
|
||||
// The root stays where it was; the shoulder and elbow turned.
|
||||
assert_eq!(transform_of(&s, 0, ROOT), Affine::translate(100.0, 100.0));
|
||||
assert!(bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap().abs() > 1.0);
|
||||
// An unreachable target: the chain points straight at it, the root still put.
|
||||
let v = run(&mut s, "bone.solve", json!({"bone": b2, "x": 200, "y": 320}));
|
||||
assert_eq!(v["reached"], false);
|
||||
assert!(bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap().abs() < 0.1, "straight");
|
||||
let tail = pt(&bone_at(&mut s, 0, b2)["tail"]);
|
||||
assert!(tail.distance(Vec2::new(200.0, 300.0)) < 0.05, "{tail:?}");
|
||||
assert_eq!(transform_of(&s, 0, ROOT), Affine::translate(100.0, 100.0));
|
||||
s.undo().unwrap();
|
||||
s.undo().unwrap();
|
||||
assert_eq!(transform_of(&s, 0, HAND), Affine::translate(300.0, 100.0), "undo puts the pose back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_and_pins_hold_in_every_pose() {
|
||||
let (mut s, b1, b2) = rigged();
|
||||
run(&mut s, "bone.pose", json!({"bone": b2, "angle": 60}));
|
||||
let v = run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -20, "max": 20}));
|
||||
assert_eq!(v["constrain"], true);
|
||||
assert!((bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap() - 20.0).abs() < 1e-3, "the pose came inside the new limits");
|
||||
run(&mut s, "bone.solve", json!({"bone": b2, "x": 230, "y": 160}));
|
||||
let a = bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap();
|
||||
assert!((-20.0 - 1e-3..=20.0 + 1e-3).contains(&a), "{a}");
|
||||
assert!(s.execute("bone.set_limits", &json!({"bone": b2, "min": 30, "max": 10})).is_err());
|
||||
assert!(s.execute("bone.set_limits", &json!({"bone": b2, "min": -400})).is_err());
|
||||
run(&mut s, "bone.set_limits", json!({"bone": b2, "constrain": false}));
|
||||
assert_eq!(bone_at(&mut s, 0, b2)["min"], Value::Null);
|
||||
// Pinned: the shoulder keeps its angle while the elbow follows the drag.
|
||||
let before = bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap();
|
||||
run(&mut s, "bone.pin", json!({"bone": b1, "pinned": true}));
|
||||
run(&mut s, "bone.solve", json!({"bone": b2, "x": 350, "y": 60}));
|
||||
assert_eq!(bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap(), before);
|
||||
assert!(s.execute("bone.solve", &json!({"bone": b1, "x": 0, "y": 0})).unwrap_err().to_string().contains("pinned"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poses_key_frames_and_tween_with_easing() {
|
||||
let (mut s, b1, _) = rigged();
|
||||
run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90, "frame": 10}));
|
||||
let l = s.doc.timeline(0).layers[0].clone();
|
||||
assert_eq!(l.keyframes.iter().map(|k| k.start).collect::<Vec<_>>(), vec![0, 10], "a pose keyed at frame 10");
|
||||
let a = |s: &mut Session, f| bone_at(s, f, b1)["angle"].as_f64().unwrap();
|
||||
assert_eq!(a(&mut s, 0), 0.0, "exact at the first key");
|
||||
assert!((a(&mut s, 10) - 90.0).abs() < 1e-4, "exact at the second key");
|
||||
assert!((a(&mut s, 5) - 45.0).abs() < 1e-3, "half way");
|
||||
// The hand rides the shoulder: at frame 10 it hangs straight down from it.
|
||||
assert!(transform_of(&s, 10, HAND).translation().distance(Vec2::new(200.0, 200.0)) < 1e-3);
|
||||
// The span's easing shapes the pose tween.
|
||||
run(&mut s, "timeline.set_easing", json!({"frame": 0, "easing": "QuadIn"}));
|
||||
assert!((a(&mut s, 5) - 22.5).abs() < 1e-3, "{}", a(&mut s, 5));
|
||||
// Posing inside the tween keys that frame with the pose it showed.
|
||||
run(&mut s, "bone.pose", json!({"bone": b1, "rotate_by": 10, "frame": 5}));
|
||||
assert!((a(&mut s, 5) - 32.5).abs() < 1e-3);
|
||||
assert_eq!(s.doc.timeline(0).layers[0].keyframes.len(), 3);
|
||||
// Moving the root moves the whole armature, in that pose.
|
||||
run(&mut s, "bone.pose", json!({"dx": 10, "dy": 5, "frame": 10}));
|
||||
assert!(transform_of(&s, 10, HAND).translation().distance(Vec2::new(210.0, 205.0)) < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artwork_edits_are_refused_on_the_armature_layer() {
|
||||
let (mut s, _, _) = rigged();
|
||||
s.select_only([ElementId(HAND)]);
|
||||
for (id, p) in [("draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})), ("element.translate", json!({"dx": 5, "dy": 0})), ("edit.delete", json!({})), ("timeline.create_motion_tween", json!({}))] {
|
||||
let e = s.execute(id, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("armature"), "{id}: {e}");
|
||||
}
|
||||
assert!(s.execute("layer.set_type", &json!({"type": "normal"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_bones_frees_the_instances_where_they_are() {
|
||||
let (mut s, b1, b2) = rigged();
|
||||
run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90}));
|
||||
run(&mut s, "bone.pose", json!({"bone": b1, "angle": 0, "frame": 10}));
|
||||
// Two poses: removing asks first (undoable tier).
|
||||
let c = s.confirmation("bone.remove", &json!({"bone": b2})).unwrap();
|
||||
assert!(!c.irreversible && c.message.contains("2 keyframes"), "{}", c.message);
|
||||
let hand = transform_of(&s, 0, HAND);
|
||||
let v = run(&mut s, "bone.remove", json!({"bone": b2}));
|
||||
assert_eq!(v["armature_removed"], false);
|
||||
let tl = s.doc.timeline(0);
|
||||
assert_eq!(tl.layers.len(), 3);
|
||||
assert_eq!(tl.layers[1].keyframes[0].elements[0].id.0, HAND, "the hand is on a layer of its own");
|
||||
assert!(tl.layers[0].keyframes.iter().all(|k| k.pose.0.iter().all(|j| j.bone.0 != b2)));
|
||||
assert_eq!(transform_of(&s, 0, HAND), hand, "where it was");
|
||||
// The last bone takes the armature with it; the instances stay as they look.
|
||||
let arm = transform_of(&s, 0, ARM);
|
||||
let v = run(&mut s, "bone.remove", json!({"bone": b1}));
|
||||
assert_eq!(v["armature_removed"], true);
|
||||
assert!(s.doc.timeline(0).layers.iter().all(|l| l.kind != LayerKind::Armature));
|
||||
assert_eq!(transform_of(&s, 0, ARM), arm);
|
||||
s.undo().unwrap();
|
||||
s.undo().unwrap();
|
||||
assert_eq!(s.doc.timeline(0).layers[0].armature.as_ref().unwrap().bones.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn armatures_survive_a_file_round_trip_and_render_the_pose() {
|
||||
let (mut s, b1, b2) = rigged();
|
||||
run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -45, "max": 45}));
|
||||
run(&mut s, "bone.pin", json!({"bone": b1, "pinned": true}));
|
||||
run(&mut s, "bone.pin", json!({"bone": b1, "pinned": false}));
|
||||
run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90, "frame": 10}));
|
||||
let text = crate::format::to_json(&s.doc).unwrap();
|
||||
let back = crate::format::from_json(&text).unwrap();
|
||||
assert_eq!(back, s.doc);
|
||||
for f in [0, 5, 10] {
|
||||
assert_eq!(render_frame(&back, f, 1.0).unwrap().data, render_frame(&s.doc, f, 1.0).unwrap().data);
|
||||
}
|
||||
// At frame 10 the arm hangs from the shoulder: the bar covers (200, 150), not (250, 100).
|
||||
let pm = render_frame(&s.doc, 10, 1.0).unwrap();
|
||||
assert!(pm.pixel(200, 150).unwrap()[0] < 0.1, "the arm points down");
|
||||
assert!(pm.pixel(250, 100).unwrap()[0] > 0.9, "and is no longer along the line");
|
||||
// Older files (no armature) load as before; a file's armature on another kind of layer is
|
||||
// dropped.
|
||||
let old = crate::format::from_json(&crate::format::to_json(&Document::default()).unwrap()).unwrap();
|
||||
assert!(old.timeline(0).layers.iter().all(|l| l.armature.is_none()));
|
||||
let mut odd = s.doc.clone();
|
||||
Arc::make_mut(&mut odd.timeline_mut(0).layers[0]).kind = LayerKind::Normal;
|
||||
let odd = crate::format::from_json(&crate::format::to_json(&odd).unwrap()).unwrap();
|
||||
assert!(odd.timeline(0).layers[0].armature.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plug_ins_may_pose_armatures() {
|
||||
for id in ["bone.add", "bone.remove", "bone.set_limits", "bone.pin", "bone.pose", "bone.solve", "bone.info"] {
|
||||
assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}");
|
||||
}
|
||||
}
|
||||
@@ -132,21 +132,53 @@ fn kept_scripts_survive_the_file_and_hostile_ones_are_dropped_whole() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_runs_a_kept_script() {
|
||||
fn scripts_in_the_subset_run_and_the_rest_are_kept_and_said_so() {
|
||||
let mut s = Session::new(sample::interactive());
|
||||
let layer = s.doc.timeline(0).layers[0].id.0;
|
||||
// A script that would stop the movie and trace, on the show keyframe instead of its actions.
|
||||
s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "trace(\"xyzzy-kept\"); stop();"})).unwrap();
|
||||
// A script that stops the movie and traces, on the show keyframe instead of its actions.
|
||||
let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "trace(\"xyzzy-\" + 1); stop();"})).unwrap();
|
||||
assert_eq!((v["runs"].as_bool(), v["problems"].as_array().map(Vec::len)), (Some(true), Some(0)), "{v}");
|
||||
let v = s.execute("control.test_movie", &json!({"frames": 20, "events": [{"tick": 2, "type": "click", "x": 640, "y": 400}]})).unwrap();
|
||||
let lines: Vec<&str> = v["output"].as_array().unwrap().iter().filter_map(|l| l["line"].as_str()).collect();
|
||||
assert!(lines.is_empty(), "{lines:?}");
|
||||
assert_eq!(lines.first().copied(), Some("Frame script runs: Scene 1 › Actions, frame 2"), "{lines:?}");
|
||||
assert!(lines.contains(&"xyzzy-1"), "{lines:?}");
|
||||
assert!(v["state"]["frame"].as_u64().unwrap() < 10 && v["state"]["playing"] == false, "it stopped: {}", v["state"]);
|
||||
// The HTML export runs it too, as the same actions.
|
||||
let out = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap();
|
||||
assert!(out.html.contains("xyzzy-1") && !out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report);
|
||||
// One outside the subset doesn't run at all, and Test Movie says where and why.
|
||||
let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "stop();
|
||||
var n:int = 1;"})).unwrap();
|
||||
assert_eq!(v["runs"], false);
|
||||
assert_eq!(v["problems"][0], json!({"line": 2, "column": 1, "message": "variables (`var`) aren't supported yet"}));
|
||||
let v = s.execute("control.test_movie", &json!({"frames": 20, "events": [{"tick": 2, "type": "click", "x": 640, "y": 400}]})).unwrap();
|
||||
assert_eq!(v["output"][0]["line"], "Frame script not run: Scene 1 › Actions, frame 2: line 2, column 1: variables (`var`) aren't supported yet");
|
||||
assert!(v["state"]["frame"].as_u64().unwrap() > 10, "it played on: {}", v["state"]);
|
||||
// The HTML export draws the movie and says the script isn't in it.
|
||||
let out = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap();
|
||||
assert!(out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report);
|
||||
assert!(!out.html.contains("xyzzy-kept"), "the script's text isn't exported");
|
||||
assert!(!out.html.contains("var n:int"), "a kept script's text isn't exported");
|
||||
let list = s.execute("script.list", &json!({"text": false})).unwrap();
|
||||
assert_eq!((list["frames"][0]["runs"].as_bool(), list["frames"][0]["problems"][0]["line"].as_u64()), (Some(false), Some(2)));
|
||||
// Plug-ins may read and write kept scripts, as they may actions.
|
||||
for id in ["script.set", "script.clear", "script.list", "script.set_class"] {
|
||||
for id in ["script.set", "script.clear", "script.list", "script.set_class", "script.check"] {
|
||||
assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_check_says_what_a_text_would_do_and_changes_nothing() {
|
||||
let mut s = Session::new(sample::interactive());
|
||||
let before = s.doc.clone();
|
||||
let v = s.execute("script.check", &json!({"text": "stop();
|
||||
btn.addEventListener(MouseEvent.CLICK, go);
|
||||
function go(e:MouseEvent):void { gotoAndPlay(\"run\"); }
|
||||
navigateToURL(new URLRequest(\"x\"));"})).unwrap();
|
||||
assert_eq!(v["runs"], true);
|
||||
assert_eq!(v["describe"], json!(["Stop", "On click (btn): Go to “run” and play"]));
|
||||
assert_eq!(v["steps"][1]["listen"]["target"], "btn");
|
||||
assert_eq!(v["notes"][0]["line"], 4);
|
||||
let v = s.execute("script.check", &json!({"text": "stop();", "language": "actionscript1or2"})).unwrap();
|
||||
assert_eq!((v["runs"].as_bool(), v["problems"][0]["line"].as_u64()), (Some(false), Some(0)));
|
||||
assert!(s.execute("script.check", &json!({})).is_err());
|
||||
assert!(s.doc == before && s.undo_label().is_none());
|
||||
}
|
||||
@@ -62,8 +62,9 @@ pub fn check(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], to
|
||||
compare(golden, name, width, height, rgba, tol)
|
||||
}
|
||||
|
||||
/// The comparison [`check`] makes when it isn't updating.
|
||||
fn compare(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], tol: Tolerance) -> Result<(), String> {
|
||||
/// The comparison [`check`] makes when it isn't updating (a test whose renders must match
|
||||
/// another test's goldens compares only, never writing them).
|
||||
pub fn compare(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], tol: Tolerance) -> Result<(), String> {
|
||||
assert_eq!(rgba.len(), (width * height * 4) as usize);
|
||||
let keep = |why: String| -> String {
|
||||
let actual = out_dir().join(format!("{name}.actual.png"));
|
||||
|
||||
@@ -47,7 +47,7 @@ fn the_stage_renders_without_a_thread() {
|
||||
let svc = RenderService::new(64 << 20, None);
|
||||
let view = anicraft_engine::render::View::stage(&s.doc, 0.5);
|
||||
// No worker thread can start, so a request renders right away.
|
||||
let img = svc.request(svc.job(s.state, &s.doc, 3, view, false)).expect("rendered on this thread");
|
||||
let img = svc.request(svc.job(s.state, &s.doc, 3, view, None)).expect("rendered on this thread");
|
||||
assert!(img.error.is_none() && img.width > 0 && img.rgba_premul.iter().any(|&b| b != 0));
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ const FRAMES: &[(&str, &[u32])] = &[
|
||||
("filters", &[0]),
|
||||
("gradients", &[0]),
|
||||
("guides", &[0, 6, 12]),
|
||||
("interactive", &[0, 9]),
|
||||
("masks", &[0]),
|
||||
("primitives", &[0]),
|
||||
("scenes", &[0, 3, 7, 8, 10]),
|
||||
@@ -42,6 +43,9 @@ const SCALE: f32 = 0.5;
|
||||
|
||||
/// What a frame must show at a stage point: (package, frame, x, y, colour).
|
||||
const PROBES: &[(&str, u32, f32, f32, u32)] = &[
|
||||
// The door movie clip and the button, on the authored timeline (scripts never change it).
|
||||
("interactive", 0, 90.0, 90.0, 0x8D5524),
|
||||
("interactive", 9, 240.0, 90.0, 0x2A9D8F),
|
||||
// Both sides of a shared edge, the hole, the hex-coordinate triangle.
|
||||
("shapes", 0, 45.0, 50.0, 0xD9452B),
|
||||
("shapes", 0, 80.0, 30.0, 0x2B6CD9),
|
||||
@@ -172,3 +176,31 @@ fn every_package_opens_with_file_open_and_round_trips_through_the_file_format()
|
||||
assert!(s.doc == t.doc, "{case}: the saved document opens differently");
|
||||
}
|
||||
}
|
||||
|
||||
/// Animate's raw shapes open as raw shapes, each keyframe's merged into one drawing (ADR 0042),
|
||||
/// and look as they did: the goldens still match. A raw outline is one stroke per side (ADR
|
||||
/// 0031), so at a corner two round caps overlap where one round join was and their antialiased
|
||||
/// edges add up: a few corner pixels may be darker (47 of the shapes frame's 14,400).
|
||||
#[test]
|
||||
fn raw_shapes_open_raw_merged_and_unchanged_to_the_eye() {
|
||||
let mut failures = Vec::new();
|
||||
let (mut raw_total, mut merged_total) = (0, 0);
|
||||
for (case, frames) in FRAMES.iter().filter(|(c, _)| !matches!(*c, "text")) {
|
||||
let mut s = Session::default();
|
||||
let info = s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}"));
|
||||
let raw = s.doc.scenes.iter().flat_map(|sc| sc.timeline.layers.iter()).chain(s.doc.library.iter().flat_map(|sym| sym.timeline.layers.iter())).flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()).filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).count();
|
||||
raw_total += raw;
|
||||
// (Keyframes a tween joins keep their shapes as they came.)
|
||||
merged_total += info["merged_keyframes"].as_u64().unwrap_or(0);
|
||||
for &f in *frames {
|
||||
let (w, h, rgba) = render(&s.doc, f);
|
||||
let golden = corpus().join(case).join("golden").join(format!("frame-{f:03}.png"));
|
||||
let corners = golden::Tolerance { pixels: 0.005, ..golden::DEFAULT };
|
||||
if let Err(e) = golden::compare(&golden, &format!("{case}-merged-frame-{f:03}"), w, h, &rgba, corners) {
|
||||
failures.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(raw_total > 0 && merged_total > 0, "the corpus has raw shapes, merged: {raw_total} shapes, {merged_total} keyframes");
|
||||
assert!(failures.is_empty(), "merged raw shapes look different:\n{}", failures.join("\n"));
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod clip;
|
||||
pub mod edit;
|
||||
pub mod morph;
|
||||
pub mod planar;
|
||||
pub mod raw;
|
||||
mod fit;
|
||||
mod path;
|
||||
pub mod svg;
|
||||
@@ -18,7 +19,7 @@ pub mod walk;
|
||||
|
||||
pub use affine::{Affine, Decomposed};
|
||||
pub use fit::fit_curve;
|
||||
pub use path::{FillRule, Path, PathCmd, Polyline};
|
||||
pub use path::{FillRule, Path, PathCmd, Polyline, segment_distance};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::{Add, Mul, Neg, Sub};
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//!
|
||||
//! The shapes, bottom to top, are cut into a planar map:
|
||||
//! - every segment is cut where it meets another (exact sub-curves by de Casteljau);
|
||||
//! - points closer than [`SNAP`] become one vertex, and pieces that run along each other become
|
||||
//! one edge;
|
||||
//! - points closer than [`SNAP`] become one vertex (anchors meet at their midpoint; a point that
|
||||
//! lands on a line goes onto it, and the line stays), and pieces that run along each other
|
||||
//! become one edge;
|
||||
//! - each face of the map takes the fill of the topmost shape covering it (winding at a point
|
||||
//! inside the face).
|
||||
//!
|
||||
@@ -52,6 +53,8 @@ pub struct Piece {
|
||||
pub style: u32,
|
||||
pub path: Path,
|
||||
pub item: usize,
|
||||
/// Inside the cutter ([`merge_cut`]); always false from [`merge`].
|
||||
pub inside: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -62,7 +65,28 @@ pub struct Merged {
|
||||
|
||||
/// Merges `items` (bottom to top). `None` when there is too much to merge at once.
|
||||
pub fn merge(items: &[Item]) -> Option<Merged> {
|
||||
let segs = collect(items)?;
|
||||
merge_with(items, None)
|
||||
}
|
||||
|
||||
/// [`merge`], also cutting everything along `cutter` (a closed outline that only cuts, such as
|
||||
/// the Selection tool's marquee, ADR 0041): fills are split at its edges and stroke runs end
|
||||
/// there, nothing of the cutter itself comes out, and each piece says whether it lies inside it.
|
||||
pub fn merge_cut(items: &[Item], cutter: &Path) -> Option<Merged> {
|
||||
merge_with(items, Some(cutter))
|
||||
}
|
||||
|
||||
/// The item number the cutter's segments carry.
|
||||
const CUTTER: usize = usize::MAX;
|
||||
|
||||
fn merge_with(items: &[Item], cutter: Option<&Path>) -> Option<Merged> {
|
||||
let mut segs = collect(items)?;
|
||||
if let Some(path) = cutter {
|
||||
let edge = Item { path, fill: None, fill_rule: FillRule::EvenOdd, stroke: Some(0) };
|
||||
segs.extend(collect(&[edge])?.into_iter().map(|s| Seg { item: CUTTER, ..s }));
|
||||
if segs.len() > MAX_SEGMENTS {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let splits = cut(&segs)?;
|
||||
let map = Map::build(&segs, &splits);
|
||||
Some(map.output(items, &segs))
|
||||
@@ -448,12 +472,44 @@ struct Map {
|
||||
slot: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Greedy clustering: a point joins the first vertex within [`TOL`], so none moves farther.
|
||||
/// Greedy clustering: a point joins the nearest vertex whose first point is within [`TOL`].
|
||||
struct Verts {
|
||||
pts: Vec<P>,
|
||||
grid: HashMap<(i64, i64), Vec<usize>>,
|
||||
}
|
||||
|
||||
/// What fell into one vertex, to decide where it goes (issue #42: anchor points closer than
|
||||
/// [`SNAP`] meet at their midpoint; a point that lands on a line goes onto it, and the line stays).
|
||||
#[derive(Default)]
|
||||
struct Cluster {
|
||||
/// A point inside a segment, away from its ends (where an end lies on a line, or lines
|
||||
/// cross): the vertex stays there.
|
||||
on_line: Option<P>,
|
||||
/// Segment ends, each position once.
|
||||
ends: Vec<P>,
|
||||
}
|
||||
|
||||
impl Cluster {
|
||||
fn add(&mut self, p: P, end: bool, on_line: bool) {
|
||||
if on_line {
|
||||
self.on_line.get_or_insert(p);
|
||||
} else if end && !self.ends.iter().any(|q| q.dist(p) < 1e-9) && self.ends.len() < 64 {
|
||||
self.ends.push(p);
|
||||
}
|
||||
}
|
||||
fn place(&self, seed: P) -> P {
|
||||
if let Some(p) = self.on_line {
|
||||
return p;
|
||||
}
|
||||
if self.ends.is_empty() {
|
||||
return seed;
|
||||
}
|
||||
let n = self.ends.len() as f64;
|
||||
let sum = self.ends.iter().fold(P::default(), |s, p| s.add(*p));
|
||||
sum.mul(1.0 / n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Verts {
|
||||
fn cell(p: P) -> (i64, i64) {
|
||||
((p.x / TOL).floor() as i64, (p.y / TOL).floor() as i64)
|
||||
@@ -491,13 +547,35 @@ fn pinned(c: &Cubic, line: bool, a: P, b: P) -> Cubic {
|
||||
impl Map {
|
||||
fn build(segs: &[Seg], splits: &[Vec<f64>]) -> Map {
|
||||
let mut vs = Verts { pts: Vec::new(), grid: HashMap::new() };
|
||||
// Every cut point into a vertex first, then each vertex placed (see `Cluster`), so the
|
||||
// pieces are pinned to where their vertices end up.
|
||||
let mut clusters: Vec<Cluster> = Vec::new();
|
||||
let mut ids: Vec<Vec<usize>> = Vec::with_capacity(segs.len());
|
||||
for (s, ts) in segs.iter().zip(splits) {
|
||||
let mut row = Vec::with_capacity(ts.len());
|
||||
for &t in ts {
|
||||
let end = t <= 0.0 || t >= 1.0;
|
||||
let p = if t <= 0.0 { s.c[0] } else if t >= 1.0 { s.c[3] } else { eval(&s.c, t) };
|
||||
let v = vs.at(p);
|
||||
if clusters.len() <= v {
|
||||
clusters.resize_with(v + 1, Cluster::default);
|
||||
}
|
||||
let on_line = !end && p.dist(s.c[0]) >= TOL && p.dist(s.c[3]) >= TOL;
|
||||
clusters[v].add(p, end, on_line);
|
||||
row.push(v);
|
||||
}
|
||||
ids.push(row);
|
||||
}
|
||||
for (p, c) in vs.pts.iter_mut().zip(&clusters) {
|
||||
*p = c.place(*p);
|
||||
}
|
||||
let mut edges: Vec<Edge> = Vec::new();
|
||||
let mut by_ends: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
|
||||
for (si, (s, ts)) in segs.iter().zip(splits).enumerate() {
|
||||
for w in ts.windows(2) {
|
||||
for (si, ((s, ts), row)) in segs.iter().zip(splits).zip(&ids).enumerate() {
|
||||
for (w, v) in ts.windows(2).zip(row.windows(2)) {
|
||||
let (t0, t1) = (w[0], w[1]);
|
||||
let c = sub(&s.c, t0, t1);
|
||||
let (a, b) = (vs.at(c[0]), vs.at(c[3]));
|
||||
let (a, b) = (v[0], v[1]);
|
||||
if a == b {
|
||||
continue; // shorter than SNAP (longer loops were halved when collected)
|
||||
}
|
||||
@@ -655,16 +733,19 @@ impl Map {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(e, edge)| {
|
||||
let z = edge.strokes.iter().copied().max()?;
|
||||
let z = edge.strokes.iter().copied().filter(|&i| i < items.len()).max()?;
|
||||
let (l, r) = (face(2 * e), face(2 * e + 1));
|
||||
let hidden = l.zip(r).is_some_and(|(l, r)| covers[l].iter().any(|&i| i > z && covers[r].contains(&i)));
|
||||
(!hidden).then_some(z)
|
||||
})
|
||||
.collect();
|
||||
// The cutter's edges divide like a stroke that never shows.
|
||||
let cut_edge: Vec<bool> = self.edges.iter().map(|e| e.strokes.contains(&CUTTER)).collect();
|
||||
let cutter = Region::new(segs, CUTTER, cut_edge.contains(&true));
|
||||
// Faces of one fill with no stroke between them are one region.
|
||||
let mut group = Dsu::new(samples.len());
|
||||
for (e, stroke) in stroke_of.iter().enumerate() {
|
||||
if let (None, Some(l), Some(r)) = (stroke, face(2 * e), face(2 * e + 1))
|
||||
if let (None, false, Some(l), Some(r)) = (stroke, cut_edge[e], face(2 * e), face(2 * e + 1))
|
||||
&& l != r
|
||||
&& fill_of(l).map(|f| f.0) == fill_of(r).map(|f| f.0)
|
||||
&& fill_of(l).is_some()
|
||||
@@ -674,11 +755,13 @@ impl Map {
|
||||
}
|
||||
let roots = group.roots();
|
||||
let gid = |f: Option<usize>| f.filter(|&f| fill_of(f).is_some()).and_then(|f| roots.get(f).copied());
|
||||
// Each region's style and topmost item.
|
||||
let mut top: HashMap<usize, (u32, usize)> = HashMap::new();
|
||||
for f in 0..samples.len() {
|
||||
// Each region's style and topmost item, and whether it is inside the cutter (the
|
||||
// cutter's edges bound every region, so one sample tells).
|
||||
let mut top: HashMap<usize, (u32, usize, bool)> = HashMap::new();
|
||||
for (f, sample) in samples.iter().enumerate() {
|
||||
if let (Some(g), Some((style, item))) = (gid(Some(f)), fill_of(f)) {
|
||||
let t = top.entry(g).or_insert((style, item));
|
||||
let inside = sample.is_some_and(|p| cutter.covers(p, FillRule::EvenOdd));
|
||||
let t = top.entry(g).or_insert((style, item, inside));
|
||||
t.1 = t.1.max(item);
|
||||
}
|
||||
}
|
||||
@@ -708,25 +791,27 @@ impl Map {
|
||||
match piece_of.get(&g) {
|
||||
Some(&i) => out.fills[i].path.cmds.extend(path.cmds),
|
||||
None => {
|
||||
let (style, item) = top.get(&g).copied().unwrap_or((0, 0));
|
||||
let (style, item, inside) = top.get(&g).copied().unwrap_or((0, 0, false));
|
||||
piece_of.insert(g, out.fills.len());
|
||||
out.fills.push(Piece { style, path, item });
|
||||
out.fills.push(Piece { style, path, item, inside });
|
||||
}
|
||||
}
|
||||
}
|
||||
self.strokes(items, &stroke_of, segs, &mut out);
|
||||
self.strokes(items, &stroke_of, &cut_edge, &cutter, segs, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Visible strokes, chained through vertices where exactly two of one style meet smoothly.
|
||||
fn strokes(&self, items: &[Item], stroke_of: &[Option<usize>], segs: &[Seg], out: &mut Merged) {
|
||||
/// Visible strokes, chained through vertices where exactly two of one style meet smoothly
|
||||
/// (and never across the cutter).
|
||||
fn strokes(&self, items: &[Item], stroke_of: &[Option<usize>], cut_edge: &[bool], cutter: &Region, segs: &[Seg], out: &mut Merged) {
|
||||
let style = |e: usize| stroke_of[e].and_then(|z| items[z].stroke);
|
||||
let shown: Vec<Vec<Half>> = self.around.iter().map(|l| l.iter().copied().filter(|&h| style(h / 2).is_some()).collect()).collect();
|
||||
let on_cut: Vec<bool> = self.around.iter().map(|l| l.iter().any(|&h| cut_edge[h / 2])).collect();
|
||||
// The half that carries on from `h` at its end, if the run goes on.
|
||||
let carry = |h: Half| -> Option<Half> {
|
||||
let v = self.dest(h);
|
||||
let list = &shown[v];
|
||||
if list.len() != 2 {
|
||||
if list.len() != 2 || on_cut[v] {
|
||||
return None;
|
||||
}
|
||||
let n = list.iter().copied().find(|&o| o != (h ^ 1))?;
|
||||
@@ -763,7 +848,9 @@ impl Map {
|
||||
h = n;
|
||||
}
|
||||
let item = halves.iter().filter_map(|&h| stroke_of[h / 2]).max().unwrap_or(0);
|
||||
out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item });
|
||||
// A run along the cutter's edge counts as inside it.
|
||||
let inside = halves.iter().any(|&h| cut_edge[h / 2]) || halves.get(halves.len() / 2).is_some_and(|&h| cutter.covers(eval(&self.curve(h), 0.5), FillRule::EvenOdd));
|
||||
out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item, inside });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -256,3 +256,77 @@ fn a_search_that_runs_out_of_steps_declines_the_merge() {
|
||||
let (a, b) = (arc(100.0), arc(100.3));
|
||||
assert_eq!(merge(&[stroked(&a, None, 1), stroked(&b, None, 1)]).map(|m| m.strokes.len()), Some(2));
|
||||
}
|
||||
|
||||
// ----- snapping within SNAP and cutting (ADR 0041) -----------------------------------------------
|
||||
|
||||
fn ends(p: &Path) -> Vec<Vec2> {
|
||||
p.anchors().into_iter().map(|(_, v)| v).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_within_snap_meet_at_their_midpoint() {
|
||||
// Issue #42 §4: two ends 0.1 apart (a keyboard nudge's reach) become one point halfway.
|
||||
let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(50.0, 0.0));
|
||||
let b = Path::line(Vec2::new(50.1, 0.1), Vec2::new(50.1, 50.0));
|
||||
let m = run(&[stroked(&a, None, 1), stroked(&b, None, 1)]);
|
||||
assert_eq!(m.strokes.len(), 2, "{m:?}");
|
||||
let mid = Vec2::new(50.05, 0.05);
|
||||
for s in &m.strokes {
|
||||
assert!(ends(&s.path).iter().any(|p| p.distance(mid) < 1e-4), "{:?}", s.path);
|
||||
}
|
||||
// A fill corner and a line end too: the corner moves halfway, so the outline stays closed.
|
||||
let r = rect(0.0, 0.0, 10.0, 10.0);
|
||||
let l = Path::line(Vec2::new(10.12, 10.0), Vec2::new(30.0, 30.0));
|
||||
let m = run(&[fill(&r, 1), stroked(&l, None, 2)]);
|
||||
let corner = Vec2::new(10.06, 10.0);
|
||||
assert!(m.fills.iter().any(|f| ends(&f.path).iter().any(|p| p.distance(corner) < 1e-4)), "{m:?}");
|
||||
assert!(m.strokes.iter().any(|s| ends(&s.path).iter().any(|p| p.distance(corner) < 1e-4)), "{m:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_near_a_line_goes_onto_it_and_the_line_stays_straight() {
|
||||
// Issue #42 §4: "an anchor point snaps to a line without modifying it".
|
||||
let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0));
|
||||
let b = Path::line(Vec2::new(40.0, 0.15), Vec2::new(40.0, 60.0));
|
||||
let m = run(&[stroked(&a, None, 1), stroked(&b, None, 1)]);
|
||||
// The long line is cut where the other meets it (a T), and every piece stays on y = 0.
|
||||
let flat: Vec<&Piece> = m.strokes.iter().filter(|s| ends(&s.path).iter().all(|p| p.y.abs() < 1e-4)).collect();
|
||||
assert_eq!(flat.len(), 2, "{m:?}");
|
||||
assert!(m.strokes.iter().any(|s| ends(&s.path).iter().any(|p| p.distance(Vec2::new(40.0, 0.0)) < 1e-4) && ends(&s.path).iter().any(|p| p.y > 59.0)), "the end moved onto the line: {m:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cutter_splits_fills_and_strokes_and_the_parts_add_up() {
|
||||
let r = rect(0.0, 0.0, 100.0, 80.0);
|
||||
let marquee = rect(60.0, -10.0, 100.0, 50.0);
|
||||
let m = merge_cut(&[stroked(&r, Some(1), 2)], &marquee).unwrap_or_default();
|
||||
// The fill in two: 40 × 40 inside (the marquee is x 60–160, y −10–40), the rest outside,
|
||||
// adding up to the whole.
|
||||
let inside: f32 = m.fills.iter().filter(|p| p.inside).map(|p| area(&p.path)).sum();
|
||||
let outside: f32 = m.fills.iter().filter(|p| !p.inside).map(|p| area(&p.path)).sum();
|
||||
assert!(near(inside, 40.0 * 40.0, 0.5), "{inside}");
|
||||
assert!(near(inside + outside, 8000.0, 0.5), "{}", inside + outside);
|
||||
assert!(m.fills.iter().all(|p| p.style == 1));
|
||||
// Nothing of the marquee comes out: only the rectangle's own sides, cut where it crosses
|
||||
// them (the top and the right side are cut there).
|
||||
let len = |p: &Path| p.flatten(&crate::Affine::IDENTITY, 0.01).iter().map(|pl| pl.points.windows(2).map(|w| w[0].distance(w[1])).sum::<f32>()).sum::<f32>();
|
||||
let total: f32 = m.strokes.iter().map(|s| len(&s.path)).sum();
|
||||
assert!(near(total, 360.0, 0.05), "{total}");
|
||||
let inner: f32 = m.strokes.iter().filter(|s| s.inside).map(|s| len(&s.path)).sum();
|
||||
assert!(near(inner, 40.0 + 40.0, 0.05), "the top's right 40 and the right side's upper 40: {inner}");
|
||||
assert!(m.strokes.iter().all(|s| s.style == 2));
|
||||
// Without a cutter nothing is inside.
|
||||
assert!(run(&[stroked(&r, Some(1), 2)]).fills.iter().all(|p| !p.inside));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cutter_over_a_curve_cuts_exact_pieces() {
|
||||
let c = Path::ellipse(0.0, 0.0, 50.0, 50.0);
|
||||
let marquee = rect(-100.0, -100.0, 100.0, 100.0);
|
||||
let m = merge_cut(&[fill(&c, 1)], &marquee).unwrap_or_default();
|
||||
let inside: f32 = m.fills.iter().filter(|p| p.inside).map(|p| area(&p.path)).sum();
|
||||
let all: f32 = m.fills.iter().map(|p| area(&p.path)).sum();
|
||||
// A quarter of the disc, to within the ellipse's Bézier approximation.
|
||||
assert!(near(inside * 4.0, all, 1.0), "{inside} of {all}");
|
||||
assert_eq!(m.fills.len(), 2);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Editing raw shapes that share edges and points (ADR 0041). A layer's merged drawing is one
|
||||
//! element per fill region and per stroke run (ADR 0031), so a corner or an edge they share is
|
||||
//! stored once in each of them. Bending an edge or moving a point with the Selection tool has to
|
||||
//! change every copy the same way, so the drawing stays joined. These are the pure parts: finding
|
||||
//! the copies of an edge in a path and replacing them, making sure a path has an anchor where
|
||||
//! another shape ends, and the nearest point on a curve (for snapping).
|
||||
|
||||
use crate::walk::cubic_point;
|
||||
use crate::{Affine, Path, PathCmd, Vec2};
|
||||
|
||||
/// A cubic Bézier segment: start, two control points, end.
|
||||
pub type Cubic = [Vec2; 4];
|
||||
|
||||
/// Most commands one pass looks at (keeps an edit's cost bounded).
|
||||
const MAX_CMDS: usize = 100_000;
|
||||
|
||||
/// Segment `cmd` of `path` as a cubic from where it starts (lines and quadratics raised exactly).
|
||||
/// `None` for anything that is not a segment.
|
||||
pub fn segment_cubic(path: &Path, cmd: usize) -> Option<Cubic> {
|
||||
let s = path.segment_start(cmd)?;
|
||||
Some(match *path.cmds.get(cmd)? {
|
||||
PathCmd::LineTo(p) => [s, s.lerp(p, 1.0 / 3.0), s.lerp(p, 2.0 / 3.0), p],
|
||||
PathCmd::QuadTo(c, p) => [s, s.lerp(c, 2.0 / 3.0), p.lerp(c, 2.0 / 3.0), p],
|
||||
PathCmd::CubicTo(a, b, p) => [s, a, b, p],
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `c` mapped by `m` (an affine map takes control points to control points exactly).
|
||||
pub fn transform(c: &Cubic, m: &Affine) -> Cubic {
|
||||
c.map(|p| m.apply(p))
|
||||
}
|
||||
|
||||
/// `c` with its point at `t` moved by `d` and its ends kept: the smallest moves of the two
|
||||
/// control points that carry that point exactly, as [`Path::bend_segment`] does.
|
||||
pub fn bend(c: &Cubic, t: f32, d: Vec2) -> Option<Cubic> {
|
||||
let mut p = Path::new();
|
||||
p.move_to(c[0]).cubic_to(c[1], c[2], c[3]);
|
||||
if !p.bend_segment(1, t, d) {
|
||||
return None;
|
||||
}
|
||||
segment_cubic(&p, 1).filter(|b| b.iter().all(|q| q.is_finite()))
|
||||
}
|
||||
|
||||
fn split(c: &Cubic, t: f32) -> (Cubic, Cubic) {
|
||||
let (a, b, d) = (c[0].lerp(c[1], t), c[1].lerp(c[2], t), c[2].lerp(c[3], t));
|
||||
let (e, f) = (a.lerp(b, t), b.lerp(d, t));
|
||||
let m = e.lerp(f, t);
|
||||
([c[0], a, e, m], [m, f, d, c[3]])
|
||||
}
|
||||
|
||||
/// The part of `c` from `t0` to `t1` (reversed when `t1 < t0`).
|
||||
pub fn sub(c: &Cubic, t0: f32, t1: f32) -> Cubic {
|
||||
if t1 < t0 {
|
||||
let r = sub(c, t1, t0);
|
||||
return [r[3], r[2], r[1], r[0]];
|
||||
}
|
||||
let left = if t1 >= 1.0 { *c } else { split(c, t1.max(0.0)).0 };
|
||||
if t0 <= 0.0 || t1 <= 0.0 {
|
||||
return left;
|
||||
}
|
||||
split(&left, (t0 / t1).clamp(0.0, 1.0)).1
|
||||
}
|
||||
|
||||
/// The parameter on `c` nearest `p`, and the distance.
|
||||
pub fn nearest(c: &Cubic, p: Vec2) -> (f32, f32) {
|
||||
const N: usize = 32;
|
||||
let mut best = (0.0f32, f32::INFINITY);
|
||||
for i in 0..=N {
|
||||
let t = i as f32 / N as f32;
|
||||
let d = cubic_point(c, t).distance(p);
|
||||
if d < best.1 {
|
||||
best = (t, d);
|
||||
}
|
||||
}
|
||||
// Golden-section search around the best sample.
|
||||
let (mut lo, mut hi) = ((best.0 - 1.0 / N as f32).max(0.0), (best.0 + 1.0 / N as f32).min(1.0));
|
||||
const G: f32 = 0.618_034;
|
||||
for _ in 0..30 {
|
||||
let (m1, m2) = (hi - (hi - lo) * G, lo + (hi - lo) * G);
|
||||
if cubic_point(c, m1).distance(p) < cubic_point(c, m2).distance(p) {
|
||||
hi = m2;
|
||||
} else {
|
||||
lo = m1;
|
||||
}
|
||||
}
|
||||
let t = 0.5 * (lo + hi);
|
||||
let d = cubic_point(c, t).distance(p);
|
||||
if d < best.1 { (t, d) } else { best }
|
||||
}
|
||||
|
||||
fn bounds_meet(a: &Cubic, b: &Cubic, pad: f32) -> bool {
|
||||
let lo = |c: &Cubic| c.iter().fold(Vec2::new(f32::INFINITY, f32::INFINITY), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y)));
|
||||
let hi = |c: &Cubic| c.iter().fold(Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY), |m, p| Vec2::new(m.x.max(p.x), m.y.max(p.y)));
|
||||
let (al, ah, bl, bh) = (lo(a), hi(a), lo(b), hi(b));
|
||||
al.x <= bh.x + pad && bl.x <= ah.x + pad && al.y <= bh.y + pad && bl.y <= ah.y + pad
|
||||
}
|
||||
|
||||
/// Where `c` runs along `of`: the parameters on `of` of its two ends, when both ends and three
|
||||
/// points between lie within `tol` of it and it is not a single point there.
|
||||
fn along(c: &Cubic, of: &Cubic, tol: f32) -> Option<(f32, f32)> {
|
||||
let (u0, d0) = nearest(of, c[0]);
|
||||
let (u1, d1) = nearest(of, c[3]);
|
||||
if d0 > tol || d1 > tol || (u1 - u0).abs() < 1e-4 {
|
||||
return None;
|
||||
}
|
||||
[0.25, 0.5, 0.75].iter().all(|&t| nearest(of, cubic_point(c, t)).1 <= tol).then_some((u0, u1))
|
||||
}
|
||||
|
||||
/// `piece` with its ends moved onto `a` and `b`, the handles moving with them (the anchors of a
|
||||
/// path stay exactly where they were, so it stays joined to its neighbours).
|
||||
fn pinned(piece: &Cubic, a: Vec2, b: Vec2) -> PathCmd {
|
||||
PathCmd::CubicTo(piece[1] + (a - piece[0]), piece[2] + (b - piece[3]), b)
|
||||
}
|
||||
|
||||
/// Replaces every stretch of `path` that runs along `old` with the same stretch of `new` (the
|
||||
/// edge `old` bent into `new`; their ends are the same). A segment lying along part of `old`
|
||||
/// takes that part of `new`; a segment that `old` lies along part of is split at `old`'s ends
|
||||
/// first. Returns how many segments changed.
|
||||
pub fn follow(path: &mut Path, old: &Cubic, new: &Cubic, tol: f32) -> usize {
|
||||
if !(tol.is_finite() && tol > 0.0) || !old.iter().chain(new).all(|p| p.is_finite()) {
|
||||
return 0;
|
||||
}
|
||||
let mut changed = 0;
|
||||
let mut k = 0;
|
||||
while k < path.cmds.len().min(MAX_CMDS) {
|
||||
let Some(s) = segment_cubic(path, k) else {
|
||||
k += 1;
|
||||
continue;
|
||||
};
|
||||
if !bounds_meet(&s, old, tol) {
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some((u0, u1)) = along(&s, old, tol) {
|
||||
// All of this segment is a stretch of the edge.
|
||||
if let Some(c) = path.cmds.get_mut(k) {
|
||||
*c = pinned(&sub(new, u0, u1), s[0], s[3]);
|
||||
changed += 1;
|
||||
}
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((s0, s1)) = along(old, &s, tol) else {
|
||||
k += 1;
|
||||
continue;
|
||||
};
|
||||
// The edge is a stretch of this (longer) segment: cut it out and replace it.
|
||||
let (lo, hi) = (s0.min(s1), s0.max(s1));
|
||||
const END: f32 = 1e-4;
|
||||
if hi < 1.0 - END && !path.split_segment(k, hi) {
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
let mid = if lo > END && path.split_segment(k, lo / hi.max(END)) { k + 1 } else { k };
|
||||
if let (Some(m), Some(start)) = (segment_cubic(path, mid), path.segment_start(mid)) {
|
||||
let piece = if s0 <= s1 { *new } else { [new[3], new[2], new[1], new[0]] };
|
||||
if let Some(c) = path.cmds.get_mut(mid) {
|
||||
*c = pinned(&piece, start, m[3]);
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
k = mid + 1;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The anchors of `path` at `p` (within `tol`), as the commands that name them. When none is
|
||||
/// there but a segment passes within `tol` (another shape ends on this one's edge), the segment
|
||||
/// is split there first, so the point can move with the shapes that end on it.
|
||||
pub fn anchors_at(path: &mut Path, p: Vec2, tol: f32) -> Vec<usize> {
|
||||
let near = |path: &Path| path.editable_anchors().into_iter().filter(|(_, q)| q.distance(p) <= tol).map(|(i, _)| i).collect::<Vec<_>>();
|
||||
let found = near(path);
|
||||
if !found.is_empty() || path.cmds.len() >= MAX_CMDS {
|
||||
return found;
|
||||
}
|
||||
match path.nearest_segment(p, &Affine::IDENTITY) {
|
||||
Some((cmd, t, d)) if d <= tol && t > 0.0 && t < 1.0 && path.split_segment(cmd, t) => vec![cmd],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn line(a: (f32, f32), b: (f32, f32)) -> Cubic {
|
||||
let (a, b) = (Vec2::new(a.0, a.1), Vec2::new(b.0, b.1));
|
||||
[a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bent_edge_passes_through_the_dragged_point_and_keeps_its_ends() {
|
||||
let c = line((0.0, 0.0), (90.0, 0.0));
|
||||
let Some(b) = bend(&c, 0.5, Vec2::new(0.0, 30.0)) else { panic!("no bend") };
|
||||
assert_eq!((b[0], b[3]), (c[0], c[3]));
|
||||
assert!(cubic_point(&b, 0.5).distance(Vec2::new(45.0, 30.0)) < 1e-3, "{:?}", cubic_point(&b, 0.5));
|
||||
// Off centre too: the grabbed point goes exactly where the pointer took it.
|
||||
let Some(b) = bend(&c, 0.2, Vec2::new(5.0, -12.0)) else { panic!("no bend") };
|
||||
assert!(cubic_point(&b, 0.2).distance(Vec2::new(23.0, -12.0)) < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_copy_of_an_edge_follows_a_bend() {
|
||||
// A fill's outline (a rectangle) shares its top edge with a stroke drawn the other way.
|
||||
let mut fill = Path::rect(0.0, 0.0, 90.0, 60.0);
|
||||
fill.close_explicitly();
|
||||
let old = line((90.0, 0.0), (0.0, 0.0));
|
||||
let Some(new) = bend(&old, 0.5, Vec2::new(0.0, -20.0)) else { panic!("no bend") };
|
||||
assert_eq!(follow(&mut fill, &old, &new, 0.2), 1);
|
||||
// The top now bulges up through (45, −20); the other sides are untouched.
|
||||
let top = fill.cmds.iter().position(|c| matches!(c, PathCmd::CubicTo(..))).and_then(|k| segment_cubic(&fill, k));
|
||||
let Some(top) = top else { panic!("no curve: {:?}", fill.cmds) };
|
||||
assert!(cubic_point(&top, 0.5).distance(Vec2::new(45.0, -20.0)) < 1e-3);
|
||||
assert_eq!(fill.cmds.iter().filter(|c| matches!(c, PathCmd::LineTo(_))).count(), 3);
|
||||
// A longer segment that the edge is part of is cut at the edge's ends.
|
||||
let mut long = Path::line(Vec2::new(-30.0, 0.0), Vec2::new(120.0, 0.0));
|
||||
assert_eq!(follow(&mut long, &old, &new, 0.2), 1);
|
||||
assert_eq!(long.cmds.len(), 4, "{:?}", long.cmds);
|
||||
let a = long.anchors().into_iter().map(|(_, p)| p).collect::<Vec<_>>();
|
||||
assert!(a.iter().any(|p| p.distance(Vec2::ZERO) < 1e-3) && a.iter().any(|p| p.distance(Vec2::new(90.0, 0.0)) < 1e-3), "{a:?}");
|
||||
let Some(mid) = segment_cubic(&long, 2) else { panic!() };
|
||||
assert!(cubic_point(&mid, 0.5).distance(Vec2::new(45.0, -20.0)) < 1e-2, "{:?}", cubic_point(&mid, 0.5));
|
||||
// Something merely nearby is left alone.
|
||||
let mut other = Path::line(Vec2::new(0.0, 5.0), Vec2::new(90.0, 5.0));
|
||||
assert_eq!(follow(&mut other, &old, &new, 0.2), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_gets_an_anchor_where_another_ends_on_it() {
|
||||
let mut p = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0));
|
||||
assert_eq!(anchors_at(&mut p, Vec2::new(100.05, 0.0), 0.2), vec![1], "an end that is there");
|
||||
assert_eq!(anchors_at(&mut p, Vec2::new(40.0, 0.1), 0.2), vec![1], "split there");
|
||||
assert_eq!(p.cmds.len(), 3);
|
||||
assert!(anchors_at(&mut p, Vec2::new(40.0, 5.0), 0.2).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_finds_the_closest_point_on_a_curve() {
|
||||
let c = [Vec2::new(0.0, 0.0), Vec2::new(0.0, 50.0), Vec2::new(100.0, 50.0), Vec2::new(100.0, 0.0)];
|
||||
let (t, d) = nearest(&c, Vec2::new(50.0, 60.0));
|
||||
assert!((t - 0.5).abs() < 1e-3 && (d - 22.5).abs() < 1e-2, "{t} {d}");
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,19 @@ impl CurveWalk {
|
||||
(b.seg as usize, ta + (b.t - ta) * f)
|
||||
}
|
||||
|
||||
/// The distance along the path to the anchor that ends path command `cmd`, or 0 for the
|
||||
/// start (a command before the first segment). `None` when `cmd` ends no segment the walk
|
||||
/// measured.
|
||||
pub fn anchor_distance(&self, cmd: usize) -> Option<f32> {
|
||||
if self.segs.first().is_some_and(|(c, _)| cmd < *c) {
|
||||
return Some(0.0);
|
||||
}
|
||||
let k = self.segs.binary_search_by_key(&cmd, |(c, _)| *c).ok()?;
|
||||
// Segment k's samples end with its anchor (t = 1).
|
||||
let j = self.samples.partition_point(|x| x.seg as usize <= k);
|
||||
self.samples.get(j.checked_sub(1)?).map(|x| x.s)
|
||||
}
|
||||
|
||||
/// The path command and curve parameter at distance `s`: where to split or bend the path.
|
||||
pub fn locate(&self, s: f32) -> (usize, f32) {
|
||||
let (k, t) = self.find(s);
|
||||
@@ -298,6 +311,12 @@ mod tests {
|
||||
assert!(w.at(125.0).distance(Vec2::new(110.0, 45.0)) < 1e-3);
|
||||
assert!(w.tangent(125.0).distance(Vec2::new(0.0, 1.0)) < 1e-5);
|
||||
assert_eq!(w.locate(125.0).0, 2, "the second line is command 2");
|
||||
// Anchors by distance: the start, the corner, the end; the walk lands on them exactly.
|
||||
assert_eq!(w.anchor_distance(0), Some(0.0));
|
||||
let corner = w.anchor_distance(1).unwrap();
|
||||
assert!((corner - 100.0).abs() < 1e-3 && w.at(corner) == Vec2::new(110.0, 20.0), "{corner}");
|
||||
assert_eq!(w.anchor_distance(2), Some(w.length()));
|
||||
assert_eq!(w.anchor_distance(3), None);
|
||||
assert!((w.project(Vec2::new(130.0, 60.0)) - 140.0).abs() < 1e-2);
|
||||
let tail = w.tail(50.0).unwrap();
|
||||
let tw = CurveWalk::new(&tail).unwrap();
|
||||
|
||||
@@ -95,9 +95,9 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
// Strokes: wide, thin (sub-pixel, faded), on open and closed paths.
|
||||
let mut wide = item(Path::line(Vec2::new(10.0, 20.0), Vec2::new(150.0, 70.0)), Paint::Solid(red));
|
||||
wide.fill = None;
|
||||
wide.stroke = Some(Stroke { color: Rgba::BLACK, width: 9.0, profile: None });
|
||||
wide.stroke = Some(Stroke::new(Rgba::BLACK, 9.0));
|
||||
let mut thin = item(Path::ellipse(80.0, 50.0, 60.0, 30.0), Paint::Solid(Rgba::new(1.0, 0.9, 0.2, 1.0)));
|
||||
thin.stroke = Some(Stroke { color: Rgba::new(0.1, 0.1, 0.4, 1.0), width: 0.4, profile: None });
|
||||
thin.stroke = Some(Stroke::new(Rgba::new(0.1, 0.1, 0.4, 1.0), 0.4));
|
||||
out.push(("strokes", list(vec![thin, wide]), view(160, 100, Some(Rgba::WHITE))));
|
||||
// Variable-width strokes (ADR 0018) come prepared by the oracle, so the GPU draws them alike.
|
||||
let mut taper = item(Path::line(Vec2::new(10.0, 80.0), Vec2::new(150.0, 15.0)), Paint::Solid(red));
|
||||
@@ -106,6 +106,22 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let mut bulge = item(Path::ellipse(80.0, 50.0, 55.0, 28.0), Paint::Solid(Rgba::new(0.3, 0.8, 0.5, 1.0)));
|
||||
bulge.stroke = Some(Stroke::new(Rgba::new(0.1, 0.1, 0.4, 1.0), 8.0).with_profile(anicraft_doc::ProfilePreset::Bulge.profile()));
|
||||
out.push(("variable-width strokes", list(vec![bulge, taper]), view(160, 100, Some(Rgba::WHITE))));
|
||||
// Caps, joins and dashes (ADR 0046) also come prepared by the oracle.
|
||||
use anicraft_doc::{Cap, Dash, Join, StrokeStyle};
|
||||
let mut zag = Path::new();
|
||||
zag.move_to(Vec2::new(12.0, 80.0));
|
||||
for p in [Vec2::new(45.0, 20.0), Vec2::new(78.0, 80.0), Vec2::new(111.0, 20.0)] {
|
||||
zag.line_to(p);
|
||||
}
|
||||
let mut zig = item(zag, Paint::Solid(red));
|
||||
zig.fill = None;
|
||||
zig.stroke = Some(Stroke::new(Rgba::BLACK, 10.0).with_style(StrokeStyle { cap: Cap::Square, join: Join::Miter, miter_limit: 4.0, dash: None }));
|
||||
let mut dashed = item(Path::ellipse(90.0, 50.0, 55.0, 30.0), Paint::Solid(Rgba::new(1.0, 0.9, 0.2, 1.0)));
|
||||
dashed.stroke = Some(Stroke::new(Rgba::new(0.1, 0.1, 0.4, 1.0), 4.0).with_style(StrokeStyle { cap: Cap::Butt, join: Join::Bevel, dash: Dash::dashed(9.0, 5.0), ..StrokeStyle::default() }));
|
||||
let mut dots = item(Path::line(Vec2::new(10.0, 92.0), Vec2::new(150.0, 92.0)), Paint::Solid(red));
|
||||
dots.fill = None;
|
||||
dots.stroke = Some(Stroke::new(red, 5.0).with_profile(anicraft_doc::ProfilePreset::TaperEnd.profile()).with_style(StrokeStyle { dash: Dash::dotted(3.0), ..StrokeStyle::default() }));
|
||||
out.push(("styled strokes", list(vec![dashed, zig, dots]), view(160, 100, Some(Rgba::WHITE))));
|
||||
// Larger than the surface on every side; colour effects (onion-skin style tint and alpha).
|
||||
let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red));
|
||||
huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 };
|
||||
|
||||
@@ -14,10 +14,13 @@
|
||||
//! frames are stored once, so a still keyframe over many frames costs one entry.
|
||||
//!
|
||||
//! What doesn't carry across is counted in the report: filters, Subtract and Invert blending,
|
||||
//! tints on bitmaps, and plug-in frame scripts (they need the plug-in host).
|
||||
//! tints on bitmaps, plug-in frame scripts (they need the plug-in host) and kept scripts
|
||||
//! outside the ActionScript subset. Scripts in the subset (ADR 0013 tier 2) come across as the
|
||||
//! same actions and listeners the Rust player runs.
|
||||
|
||||
use crate::stroke::variable_outline;
|
||||
use anicraft_doc::actions::{Action, FrameRef, Seg};
|
||||
use crate::stroke::stroke_outline;
|
||||
use anicraft_doc::actions::as3::ScriptOp;
|
||||
use anicraft_doc::actions::{Action, FrameRef, Seg, Target};
|
||||
use anicraft_doc::{BlendMode, ColorEffect, Document, Element, ElementKind, FrameScript, Layer, LayerKind, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start};
|
||||
use anicraft_geom::{Affine, FillRule, Path, PathCmd};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -90,7 +93,8 @@ const BLENDS: &str = "Subtract and Invert blending (drawn normally)";
|
||||
const BITMAP_TINT: &str = "tints on bitmap fills (drawn untinted)";
|
||||
const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)";
|
||||
const BUTTON_SOUNDS: &str = "sounds on button frames (not played yet)";
|
||||
const KEPT_SCRIPTS: &str = "kept frame scripts (not run; kept in the document only)";
|
||||
const KEPT_SCRIPTS: &str = "kept frame scripts outside the ActionScript subset (not run; kept in the document only)";
|
||||
const OUTSIDE_CALLS: &str = "script calls that reach outside the movie (ignored)";
|
||||
|
||||
/// A number rounded to `1/scale`, written as an integer when it is one.
|
||||
fn num(v: f32, scale: f64) -> Value {
|
||||
@@ -104,6 +108,20 @@ fn num(v: f32, scale: f64) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's style for the page (ADR 0046): `c` cap, `j` join, `ml` miter limit, and for a
|
||||
/// broken line `d` its on/off lengths and `o` the offset into them (local units, scaled by
|
||||
/// the page like the width; dots are zero-length round-capped dashes).
|
||||
fn line_style(st: &anicraft_doc::Stroke) -> Value {
|
||||
let style = &st.style;
|
||||
let mut k = json!({"c": style.effective_cap().key(), "j": style.join.key(), "ml": num(style.miter_limit, 1e3)});
|
||||
if let Some(d) = &style.dash {
|
||||
let (lengths, offset) = d.pattern(st.width);
|
||||
k["d"] = Value::Array(lengths.into_iter().map(|l| num(l, 1e3)).collect());
|
||||
k["o"] = num(offset, 1e3);
|
||||
}
|
||||
k
|
||||
}
|
||||
|
||||
fn coord(v: f32) -> Value {
|
||||
num(v, 1000.0)
|
||||
}
|
||||
@@ -176,13 +194,10 @@ fn path_data(p: &Path) -> String {
|
||||
if finite { s } else { String::new() }
|
||||
}
|
||||
|
||||
/// An action as the player reads it: `op`, the target as steps (`^` the main timeline, `..` up
|
||||
/// a level, else an instance name; `e` when it isn't a valid path), and `d`, its description
|
||||
/// (for messages).
|
||||
fn action(a: &Action) -> Value {
|
||||
let mut o = Map::new();
|
||||
o.insert("op".into(), json!(a.op()));
|
||||
if let Some(t) = a.target() {
|
||||
/// A target as the player reads it: `t`, its steps (`^` the main timeline, `..` up a level,
|
||||
/// else an instance name), or `e` when it isn't a valid path.
|
||||
fn target(o: &mut Map<String, Value>, t: &Target) {
|
||||
{
|
||||
match t.segments() {
|
||||
Ok(segs) => {
|
||||
if !segs.is_empty() {
|
||||
@@ -202,6 +217,16 @@ fn action(a: &Action) -> Value {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An action as the player reads it: `op`, its target (see [`target`]), and `d`, its
|
||||
/// description (for messages).
|
||||
fn action(a: &Action) -> Value {
|
||||
let mut o = Map::new();
|
||||
o.insert("op".into(), json!(a.op()));
|
||||
if let Some(t) = a.target() {
|
||||
target(&mut o, t);
|
||||
}
|
||||
match a {
|
||||
Action::Trace { message } => {
|
||||
o.insert("msg".into(), json!(message));
|
||||
@@ -232,6 +257,28 @@ fn actions(list: &[Action]) -> Value {
|
||||
Value::Array(list.iter().map(action).collect())
|
||||
}
|
||||
|
||||
/// A compiled script's steps (ADR 0013 tier 2): actions, and `listen` steps with the target,
|
||||
/// the event `ev`, the function `k` and the actions `h` it runs.
|
||||
fn script_ops(ops: &[ScriptOp]) -> Value {
|
||||
Value::Array(
|
||||
ops.iter()
|
||||
.map(|op| match op {
|
||||
ScriptOp::Action(a) => action(a),
|
||||
ScriptOp::Listen(l) => {
|
||||
let mut o = Map::new();
|
||||
o.insert("op".into(), json!("listen"));
|
||||
target(&mut o, &l.target);
|
||||
o.insert("ev".into(), json!(l.event.key()));
|
||||
o.insert("k".into(), json!(l.function));
|
||||
o.insert("h".into(), actions(&l.actions));
|
||||
o.insert("d".into(), json!(format!("Listen for {} ({})", l.event.key(), l.target)));
|
||||
Value::Object(o)
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether timeline layer `index` takes part in playback (what the player walks and draws):
|
||||
/// shown, not a folder or guide, not in a hidden folder.
|
||||
fn plays(tl: &Timeline, index: usize) -> bool {
|
||||
@@ -325,18 +372,22 @@ impl<'a> Bake<'a> {
|
||||
i
|
||||
}
|
||||
|
||||
/// A shape item: `p` path, `f` paint, `s` stroke `[r, g, b, a, width]`, `eo` even-odd,
|
||||
/// `m` transform, `c` colour effect.
|
||||
fn shape(&mut self, path: &Arc<Path>, m: &Affine, fx: &ColorEffect, fill: Option<(&Paint, &Element)>, stroke: Option<(Rgba, f32)>, rule: FillRule) -> Value {
|
||||
/// A shape item: `p` path, `f` paint, `s` stroke `[r, g, b, a, width]`, `k` its style when
|
||||
/// not round and solid (`c` cap, `j` join, `ml` miter limit, `d` dash lengths and `o` their
|
||||
/// offset, in local units like the width), `eo` even-odd, `m` transform, `c` colour effect.
|
||||
fn shape(&mut self, path: &Arc<Path>, m: &Affine, fx: &ColorEffect, fill: Option<(&Paint, &Element)>, stroke: Option<&anicraft_doc::Stroke>, rule: FillRule) -> Value {
|
||||
let mut o = Map::new();
|
||||
o.insert("p".into(), json!(self.path(path)));
|
||||
if let Some((p, el)) = fill {
|
||||
o.insert("f".into(), json!(self.paint(p, el)));
|
||||
}
|
||||
if let Some((c, w)) = stroke {
|
||||
let mut s = color(c);
|
||||
s.push(num(w, 1e3));
|
||||
if let Some(st) = stroke {
|
||||
let mut s = color(st.color);
|
||||
s.push(num(st.width, 1e3));
|
||||
o.insert("s".into(), Value::Array(s));
|
||||
if !st.style.is_default() {
|
||||
o.insert("k".into(), line_style(st));
|
||||
}
|
||||
}
|
||||
if rule == FillRule::EvenOdd {
|
||||
o.insert("eo".into(), json!(1));
|
||||
@@ -358,19 +409,20 @@ impl<'a> Bake<'a> {
|
||||
match &el.kind {
|
||||
ElementKind::Shape(s) => {
|
||||
let stroke = s.stroke.as_ref().filter(|st| st.width.is_finite() && st.width > 0.0);
|
||||
match stroke.and_then(|st| st.profile.as_ref().map(|p| (st, p))) {
|
||||
// A variable-width stroke is the filled outline the renderer fills.
|
||||
Some((st, profile)) => {
|
||||
match stroke.filter(|st| st.profile.is_some()) {
|
||||
// A variable-width stroke is the filled outline the renderer fills (its
|
||||
// caps, joins and dashes included).
|
||||
Some(st) => {
|
||||
if let Some(p) = &s.fill {
|
||||
out.push(self.shape(&s.path, &el.transform, &el.color, Some((p, el)), None, s.fill_rule));
|
||||
}
|
||||
let outline = variable_outline(&s.path, &el.transform, st.width, profile, crate::TOLERANCE);
|
||||
let outline = stroke_outline(&s.path, &el.transform, st, crate::TOLERANCE);
|
||||
if !outline.is_empty() {
|
||||
let fill = Paint::Solid(st.color);
|
||||
out.push(self.shape(&Arc::new(outline), &Affine::IDENTITY, &el.color, Some((&fill, el)), None, FillRule::NonZero));
|
||||
}
|
||||
}
|
||||
None => out.push(self.shape(&s.path, &el.transform, &el.color, s.fill.as_ref().map(|p| (p, el)), stroke.map(|st| (st.color, st.width)), s.fill_rule)),
|
||||
None => out.push(self.shape(&s.path, &el.transform, &el.color, s.fill.as_ref().map(|p| (p, el)), stroke, s.fill_rule)),
|
||||
}
|
||||
}
|
||||
// The camera is the view, not artwork (ADR 0027): it is baked into the layers.
|
||||
@@ -515,9 +567,21 @@ impl<'a> Bake<'a> {
|
||||
self.notes.entry(PLUGIN_SCRIPTS).or_default().insert(u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0));
|
||||
a.push(json!({"plugin": format!("{} · {}", p.id, p.entry)}));
|
||||
}
|
||||
// Kept scripts don't run anywhere yet (ADR 0013 tier 1).
|
||||
Some(FrameScript::Source(_)) => {
|
||||
self.notes.entry(KEPT_SCRIPTS).or_default().insert(u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0));
|
||||
// ActionScript in the subset runs as the player runs it; the rest is only
|
||||
// kept (ADR 0013).
|
||||
Some(FrameScript::Source(src)) => {
|
||||
let key = u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0);
|
||||
match src.compiled() {
|
||||
Ok(c) => {
|
||||
a.push(json!({"as": script_ops(&c.ops)}));
|
||||
if !c.notes.is_empty() {
|
||||
self.notes.entry(OUTSIDE_CALLS).or_default().insert(key);
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
self.notes.entry(KEPT_SCRIPTS).or_default().insert(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
@@ -158,14 +158,28 @@
|
||||
}
|
||||
}
|
||||
if (it.s) {
|
||||
const w = it.s[4] * AniCraft.meanScale(it.m) * k;
|
||||
const scale = AniCraft.meanScale(it.m);
|
||||
const w = it.s[4] * scale * k;
|
||||
if (w > 0 && Number.isFinite(w)) {
|
||||
g.setTransform(k, 0, 0, k, 0, 0);
|
||||
g.lineWidth = w / k;
|
||||
g.lineJoin = "round";
|
||||
g.lineCap = "round";
|
||||
// Caps, joins and dashes (stage units: local lengths × the mean scale, like the width).
|
||||
const st = it.k;
|
||||
g.lineJoin = st ? st.j : "round";
|
||||
g.lineCap = st ? st.c : "round";
|
||||
if (st) g.miterLimit = st.ml;
|
||||
const dashed = st && st.d && st.d.length > 0;
|
||||
if (dashed) {
|
||||
g.setLineDash(st.d.map((x) => x * scale));
|
||||
g.lineDashOffset = (st.o || 0) * scale;
|
||||
}
|
||||
g.strokeStyle = css(AniCraft.applyEffect(it.c, it.s));
|
||||
g.stroke(stagePath(path, it.m));
|
||||
if (dashed) {
|
||||
g.setLineDash([]);
|
||||
g.lineDashOffset = 0;
|
||||
}
|
||||
if (st) g.miterLimit = 10;
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -332,5 +346,5 @@
|
||||
report(player.start());
|
||||
resize();
|
||||
requestAnimationFrame(tick);
|
||||
});
|
||||
}).catch((e) => console.error("AniCraft: the movie couldn't start", e));
|
||||
})();
|
||||
@@ -1,7 +1,8 @@
|
||||
// AniCraft HTML canvas player: the core (ADR 0028). SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//
|
||||
// Plays a movie exported by File > Export > HTML Canvas: the instance tree, movie clip
|
||||
// playheads, frame actions and button events. It is a line-by-line port of the Rust player
|
||||
// playheads, frame actions, button events, and frame scripts in the ActionScript subset
|
||||
// (compiled by AniCraft to the same actions, with the mouse listeners they add). It is a line-by-line port of the Rust player
|
||||
// (crates/doc/src/player.rs, the reference) over the exported data, and the tests run it in a
|
||||
// JavaScript engine against that player. Nothing here touches the page: canvas.js draws and
|
||||
// listens to the pointer; this file only computes.
|
||||
@@ -20,6 +21,7 @@ var AniCraft = (function () {
|
||||
const MAX_EVENTS_PER_STEP = 256;
|
||||
const MAX_SOUNDS_PER_STEP = 256;
|
||||
const MAX_SYMBOL_DEPTH = 32;
|
||||
const MAX_LISTENERS_PER_INSTANCE = 16;
|
||||
const ROOT = 0, GRAPHIC = 1, CLIP = 2, BUTTON = 3;
|
||||
const KINDS = { graphic: GRAPHIC, movieclip: CLIP, button: BUTTON };
|
||||
const I = [1, 0, 0, 1, 0, 0];
|
||||
@@ -141,9 +143,10 @@ var AniCraft = (function () {
|
||||
// ----- the player state ------------------------------------------------------------------------
|
||||
|
||||
function newState() {
|
||||
return { scene: 0, root: { frame: 0, playing: true }, clips: new Dict(), props: new Dict(), pointer: null, down: false, hover: null, pressed: null, tick: 0 };
|
||||
return { scene: 0, root: { frame: 0, playing: true }, clips: new Dict(), props: new Dict(), listeners: new Dict(), pointer: null, down: false, hover: null, pressed: null, tick: 0 };
|
||||
}
|
||||
// Each clip entry: { path, frame, playing }; each props entry: { path, ...overrides }.
|
||||
// Each clip entry: { path, frame, playing }; each props entry: { path, ...overrides }; each
|
||||
// listeners entry: [{ ev, owner, k, h, path }] in the order added.
|
||||
function clipFrame(st, key, len) {
|
||||
const c = st.clips.get(key);
|
||||
return Math.min(c ? c.frame : 0, Math.max(len, 1) - 1);
|
||||
@@ -296,7 +299,7 @@ var AniCraft = (function () {
|
||||
}
|
||||
const xf = mul(cx.xf, m);
|
||||
if (e.y === undefined) {
|
||||
const it = { p: e.p, m: xf, f: e.f === undefined ? -1 : e.f, s: e.s || null, eo: !!e.eo, c: concat(cx.c, fx), clip: clip, masks: masks, group: cx.group };
|
||||
const it = { p: e.p, m: xf, f: e.f === undefined ? -1 : e.f, s: e.s || null, k: e.k || null, eo: !!e.eo, c: concat(cx.c, fx), clip: clip, masks: masks, group: cx.group };
|
||||
dl.items.push(it);
|
||||
if (v) v.item(it);
|
||||
return;
|
||||
@@ -331,7 +334,7 @@ var AniCraft = (function () {
|
||||
function hitIn(M, st, nodes, host, x, y) {
|
||||
for (let i = nodes.length - 1; i >= 0; i--) {
|
||||
const n = nodes[i];
|
||||
const interactive = n.kind === BUTTON || (n.kind === CLIP && n.events);
|
||||
const interactive = n.kind === BUTTON || (n.kind === CLIP && (n.events || st.listeners.has(n.key)));
|
||||
if (!n.hittable || !interactive) continue;
|
||||
const sym = M.symbols[n.sym];
|
||||
if (!sym) continue;
|
||||
@@ -408,7 +411,8 @@ var AniCraft = (function () {
|
||||
for (const k of Object.keys(p)) if (k !== "path") o[k] = p[k];
|
||||
return [p.path, o];
|
||||
});
|
||||
return { scene: st.scene, frame: st.root.frame, playing: st.root.playing, clips: clips, props: props, hover: st.hover, pressed: st.pressed, down: st.down };
|
||||
const listeners = Array.from(st.listeners.values()).filter((l) => l.length > 0).sort((a, b) => comparePaths(a[0].path, b[0].path)).map((l) => [l[0].path, l.map((x) => [x.ev, x.owner, x.k])]);
|
||||
return { scene: st.scene, frame: st.root.frame, playing: st.root.playing, clips: clips, props: props, listeners: listeners, hover: st.hover, pressed: st.pressed, down: st.down };
|
||||
};
|
||||
|
||||
function Run(player) {
|
||||
@@ -477,6 +481,12 @@ var AniCraft = (function () {
|
||||
this.queue(path);
|
||||
}
|
||||
for (const k of Array.from(st.props.keys())) if (!all.has(k)) st.props.delete(k);
|
||||
// A listener goes with its instance, and with the timeline whose script added it.
|
||||
for (const [k, list] of st.listeners.entries()) {
|
||||
const kept = list.filter((l) => all.has(keyOf(l.owner)));
|
||||
if (!all.has(k) || kept.length === 0) st.listeners.delete(k);
|
||||
else st.listeners.set(k, kept);
|
||||
}
|
||||
if (st.hover !== null && !all.has(keyOf(st.hover))) st.hover = null;
|
||||
if (st.pressed !== null && !all.has(keyOf(st.pressed))) st.pressed = null;
|
||||
};
|
||||
@@ -559,20 +569,57 @@ var AniCraft = (function () {
|
||||
const frame = this.nodes[i].frame;
|
||||
this.soundsAt(tl, frame, this.nodes[i].gain);
|
||||
for (const script of (tl.a && tl.a[frame]) || []) {
|
||||
if (Array.isArray(script)) this.runList(path, script);
|
||||
if (Array.isArray(script)) this.runList(path, script, false);
|
||||
else if (script.as) this.runOps(path, script.as);
|
||||
else this.out("Frame script " + script.plugin + " not run: frame scripts are not exported");
|
||||
}
|
||||
};
|
||||
Run.prototype.runList = function (owner, list) {
|
||||
for (const a of list) {
|
||||
if (this.halted) return;
|
||||
this.actions += 1;
|
||||
if (this.actions > MAX_ACTIONS_PER_STEP) {
|
||||
this.halt("more than " + MAX_ACTIONS_PER_STEP + " actions");
|
||||
return;
|
||||
}
|
||||
this.exec(owner, a);
|
||||
// Counts one action against the step's budget; false when nothing more may run.
|
||||
Run.prototype.budget = function () {
|
||||
if (this.halted) return false;
|
||||
this.actions += 1;
|
||||
if (this.actions > MAX_ACTIONS_PER_STEP) {
|
||||
this.halt("more than " + MAX_ACTIONS_PER_STEP + " actions");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
// `script`: the actions come from ActionScript.
|
||||
Run.prototype.runList = function (owner, list, script) {
|
||||
for (const a of list) {
|
||||
if (!this.budget()) return;
|
||||
this.exec(owner, a, script);
|
||||
}
|
||||
};
|
||||
// A compiled script's steps: actions, and `listen` (addEventListener).
|
||||
Run.prototype.runOps = function (owner, ops) {
|
||||
for (const a of ops) {
|
||||
if (!this.budget()) return;
|
||||
if (a.op === "listen") this.listen(owner, a);
|
||||
else this.exec(owner, a, true);
|
||||
}
|
||||
};
|
||||
// The instance the listener's target names gets it (once per function and event).
|
||||
Run.prototype.listen = function (owner, a) {
|
||||
this.refresh();
|
||||
const from = this.indexOf(owner);
|
||||
if (from < 0) return;
|
||||
const [i, err] = this.resolve(from, a);
|
||||
if (i < 0) return this.out(a.d + ": " + err);
|
||||
const node = this.nodes[i];
|
||||
if (!node) return;
|
||||
if (node.kind !== BUTTON && node.kind !== CLIP) {
|
||||
const why = node.kind === ROOT ? "the main timeline doesn't get pointer events here" : "“" + node.name + "” is a graphic; only buttons and movie clips get pointer events";
|
||||
return this.out(a.d + ": " + why);
|
||||
}
|
||||
let list = this.st.listeners.get(node.key);
|
||||
if (list && list.some((x) => x.ev === a.ev && samePath(x.owner, owner) && x.k === a.k)) return;
|
||||
if (list && list.length >= MAX_LISTENERS_PER_INSTANCE) return this.out(a.d + ": “" + node.name + "” already has " + MAX_LISTENERS_PER_INSTANCE + " listeners");
|
||||
if (!list) {
|
||||
list = [];
|
||||
this.st.listeners.set(node.key, list);
|
||||
}
|
||||
list.push({ ev: a.ev, owner: owner, k: a.k, h: a.h, path: node.path });
|
||||
};
|
||||
// The node `a`'s target names, seen from timeline node `from`: [index] or [-1, why].
|
||||
Run.prototype.resolve = function (from, a) {
|
||||
@@ -593,7 +640,7 @@ var AniCraft = (function () {
|
||||
}
|
||||
return [cur];
|
||||
};
|
||||
Run.prototype.exec = function (owner, a) {
|
||||
Run.prototype.exec = function (owner, a, script) {
|
||||
this.refresh();
|
||||
const from = this.indexOf(owner);
|
||||
if (from < 0) return;
|
||||
@@ -604,6 +651,8 @@ var AniCraft = (function () {
|
||||
return;
|
||||
case "next_scene":
|
||||
case "prev_scene": {
|
||||
// In ActionScript a movie clip's timeline has one scene.
|
||||
if (script && owner.length > 0) return this.out(a.d + ": a movie clip's timeline has one scene; call it in the main timeline's script");
|
||||
const s = a.op === "next_scene" ? st.scene + 1 : st.scene - 1;
|
||||
if (s >= 0 && s < this.M.scenes.length) this.gotoRoot(s, 0);
|
||||
return;
|
||||
@@ -757,17 +806,19 @@ var AniCraft = (function () {
|
||||
if (now !== null) this.fire(now, "over");
|
||||
}
|
||||
};
|
||||
// Runs an instance's handler for `event`, in the timeline the instance is on.
|
||||
// Runs an instance's handler for `event`, in the timeline the instance is on, then the
|
||||
// listeners scripts added for it (each in its script's timeline), in the order added.
|
||||
Run.prototype.fire = function (path, event) {
|
||||
this.refresh();
|
||||
const i = this.indexOf(path);
|
||||
if (i < 0) return;
|
||||
const n = this.nodes[i];
|
||||
const h = (n.events || []).find((x) => x[0] === event);
|
||||
if (!h) return;
|
||||
const ls = (this.st.listeners.get(n.key) || []).filter((l) => l.ev === event);
|
||||
if (!h && ls.length === 0) return;
|
||||
const owner = this.nodes[n.owner];
|
||||
if (!owner) return;
|
||||
this.runList(owner.path, h[1]);
|
||||
if (h && owner) this.runList(owner.path, h[1], false);
|
||||
for (const l of ls) this.runList(l.owner, l.h, true);
|
||||
this.settle();
|
||||
};
|
||||
Run.prototype.finish = function () {
|
||||
|
||||
@@ -200,6 +200,7 @@ fn snapshot(st: &PlayerState) -> Value {
|
||||
json!({
|
||||
"scene": st.scene, "frame": st.root.frame, "playing": st.root.playing,
|
||||
"clips": st.clips.iter().map(|(p, c)| json!([ids(p), c.frame, c.playing])).collect::<Vec<_>>(),
|
||||
"listeners": st.listeners.iter().filter(|(_, l)| !l.is_empty()).map(|(p, l)| json!([ids(p), l.iter().map(|x| json!([x.event.key(), ids(&x.owner), x.function])).collect::<Vec<_>>()])).collect::<Vec<_>>(),
|
||||
"hover": st.hover.as_deref().map(ids), "pressed": st.pressed.as_deref().map(ids), "down": st.down,
|
||||
})
|
||||
}
|
||||
@@ -464,6 +465,33 @@ fn variable_width_strokes_become_filled_outlines() {
|
||||
assert!(items[0]["m"].is_null(), "the outline is already in place");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_caps_joins_and_dashes_reach_the_page() {
|
||||
use anicraft_doc::{Cap, Dash, Join, Stroke, StrokeStyle};
|
||||
let mut doc = Document::default();
|
||||
let style = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 6.0, dash: Some(Dash::Dashed { lengths: vec![4.0, 1.5].into(), offset: 1.0 }) };
|
||||
let line = |y: f32, st: Stroke| Shape { path: Arc::new(Path::line(Vec2::new(10.0, y), Vec2::new(200.0, y))), fill: None, stroke: Some(st), fill_rule: FillRule::NonZero, merge: false };
|
||||
let shapes = [line(10.0, Stroke::new(Rgba::BLACK, 3.0)), line(30.0, Stroke::new(Rgba::BLACK, 3.0).with_style(style)), line(50.0, Stroke::new(Rgba::BLACK, 3.0).with_style(StrokeStyle { dash: Dash::dotted(2.0), ..StrokeStyle::default() }))];
|
||||
for (i, sh) in shapes.into_iter().enumerate() {
|
||||
let el = Element { id: ElementId(70 + i as u64), name: String::new(), transform: Affine::scale(2.0, 2.0), color: Default::default(), kind: ElementKind::Shape(sh) };
|
||||
Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements.push(Arc::new(el));
|
||||
}
|
||||
let m = movie(&doc, &HtmlOptions::default());
|
||||
let items = &m.json["contents"][0]["l"][0]["e"];
|
||||
// Round and solid: no style entry, as before.
|
||||
assert!(items[0]["s"].is_array() && items[0].get("k").is_none(), "{items}");
|
||||
// Lengths stay in local units; the page scales them like the width.
|
||||
assert_eq!(items[1]["k"], json!({"c": "butt", "j": "miter", "ml": 6, "d": [4, 1.5], "o": 1}));
|
||||
assert_eq!(items[2]["k"], json!({"c": "round", "j": "round", "ml": 3, "d": [0, 5], "o": 0}), "dots are round zero-length dashes");
|
||||
// The player hands the style to the page with each item.
|
||||
let mut js = Js::new(&m);
|
||||
js.eval("P.start()");
|
||||
let ours = js.eval("P.evaluate()");
|
||||
let theirs = ours["items"].as_array().unwrap();
|
||||
assert!(theirs[0]["k"].is_null());
|
||||
assert_eq!(theirs[1]["k"], items[1]["k"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_does_not_carry_across_is_reported() {
|
||||
let mut doc = fixture();
|
||||
@@ -585,3 +613,84 @@ fn hostile_documents_export_without_panicking() {
|
||||
let m = movie(&Document::default(), &HtmlOptions::default());
|
||||
assert_eq!(m.json["timelines"][0]["n"], 1);
|
||||
}
|
||||
|
||||
/// `k` with a kept ActionScript 3.0 script in place of its actions.
|
||||
fn as3(k: &mut Arc<Keyframe>, src: &str) {
|
||||
Arc::make_mut(k).script = Some(FrameScript::Source(Arc::new(anicraft_doc::actions::SourceScript::new(anicraft_doc::actions::Language::ActionScript3, src))));
|
||||
}
|
||||
|
||||
/// The fixture with its frame actions and the knob's handlers written as ActionScript: the
|
||||
/// main timeline's first frame adds the knob's listeners (named and inline functions,
|
||||
/// `currentTarget`), a listener makes the panel clip clickable, one names an instance that
|
||||
/// isn't there, the door's last frame calls `nextScene()` in its own script, and a script
|
||||
/// outside the subset stays kept and unrun.
|
||||
fn scripted() -> Document {
|
||||
let mut d = fixture();
|
||||
let main = "import flash.events.MouseEvent;\n\
|
||||
trace(\"start\");\n\
|
||||
knob.addEventListener(MouseEvent.CLICK, openDoor);\n\
|
||||
knob.addEventListener(MouseEvent.ROLL_OVER, function (e:MouseEvent):void { door.alpha = 0.5; });\n\
|
||||
knob.addEventListener(MouseEvent.ROLL_OUT, function (e:MouseEvent):void { door.alpha = 1; });\n\
|
||||
knob.addEventListener(MouseEvent.MOUSE_DOWN, pressed);\n\
|
||||
knob.addEventListener(MouseEvent.MOUSE_UP, released);\n\
|
||||
panel.addEventListener(MouseEvent.CLICK, function (e:MouseEvent):void { trace(\"panel \" + 1); MovieClip(e.currentTarget).gotoAndStop(1); e.currentTarget.alpha = 0.75; });\n\
|
||||
ghost.addEventListener(MouseEvent.CLICK, pressed);\n\
|
||||
navigateToURL(new URLRequest(\"https://example.com\"));\n\
|
||||
function openDoor(e:MouseEvent):void { door.gotoAndPlay(\"opening\"); panel.door.play(); }\n\
|
||||
function pressed(e:MouseEvent):void { trace(\"pressed\"); }\n\
|
||||
function released(e:MouseEvent):void { MovieClip(root).panel.gotoAndStop(100); }";
|
||||
let tl = d.timeline_mut(0);
|
||||
let l1 = Arc::make_mut(&mut tl.layers[0]);
|
||||
as3(&mut l1.keyframes[0], main);
|
||||
as3(&mut l1.keyframes[1], "ghost.stop()\npanel.stop()");
|
||||
as3(&mut l1.keyframes[2], "var n:int = 3; stop();");
|
||||
let l2 = Arc::make_mut(&mut tl.layers[1]);
|
||||
if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut Arc::make_mut(&mut l2.keyframes[0]).elements[0]).kind {
|
||||
events.clear();
|
||||
}
|
||||
let door = Arc::make_mut(&mut d.library[0]);
|
||||
let dl = Arc::make_mut(&mut door.timeline.layers[0]);
|
||||
as3(&mut dl.keyframes[2], "stop();\ntrace('door open');\nnextScene();");
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_js_player_runs_actionscript_like_the_rust_player() {
|
||||
let doc = scripted();
|
||||
let m = movie(&doc, &HtmlOptions::default());
|
||||
assert_eq!(m.report.get(KEPT_SCRIPTS), Some(&1), "{:?}", m.report);
|
||||
assert_eq!(m.report.get(OUTSIDE_CALLS), Some(&1), "{:?}", m.report);
|
||||
let none = || (vec![], vec![]);
|
||||
let mut script: Vec<(Vec<Event>, Vec<Event>)> = (0..2).map(|_| none()).collect();
|
||||
script.push((vec![Event::Move(at(100.0, 100.0))], vec![]));
|
||||
script.push((vec![Event::Down(at(101.0, 99.0))], vec![]));
|
||||
script.push((vec![], vec![Event::Up(at(102.0, 101.0))]));
|
||||
script.extend((0..6).map(|_| none()));
|
||||
// Click the panel (a movie clip that a listener made clickable).
|
||||
script.push((vec![Event::Move(at(380.0, 300.0))], vec![Event::Down(at(380.0, 300.0)), Event::Up(at(380.0, 300.0))]));
|
||||
script.push((vec![Event::Move(at(10.0, 10.0)), Event::Leave], vec![]));
|
||||
script.extend((0..30).map(|_| none()));
|
||||
let lines = compare(&doc, &script);
|
||||
for want in ["start", "pressed", "door open", "panel 1", "Listen for click (ghost): no instance named “ghost” here", "Stop (ghost): no instance named “ghost” here", "Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"] {
|
||||
assert!(lines.iter().any(|l| l == want), "the scripted fixture never wrote {want:?}: {lines:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actionscript_plays_the_movie_its_hand_made_actions_play() {
|
||||
// The scripted fixture and the fixture write the same lines and reach the same states, but
|
||||
// for the lines only scripts write and the listeners they hold.
|
||||
let (a, b) = (fixture(), scripted());
|
||||
let events = [vec![], vec![], vec![Event::Move(at(100.0, 100.0))], vec![Event::Down(at(101.0, 99.0))], vec![Event::Up(at(102.0, 101.0))], vec![], vec![], vec![], vec![Event::Move(at(10.0, 10.0))]];
|
||||
let (mut x, mut y) = (start(&a, &mut NoScripts), start(&b, &mut NoScripts));
|
||||
let only_scripts = |l: &String| l.starts_with("Listen for") || l.starts_with("Next scene:");
|
||||
for (i, ev) in events.iter().enumerate() {
|
||||
x = step(&a, &x.state, ev, &mut NoScripts);
|
||||
y = step(&b, &y.state, ev, &mut NoScripts);
|
||||
let ys: Vec<&String> = y.output.iter().filter(|l| !only_scripts(l)).collect();
|
||||
assert_eq!(x.output.iter().collect::<Vec<_>>(), ys, "step {}: output", i + 1);
|
||||
let mut st = y.state.clone();
|
||||
st.listeners.clear();
|
||||
assert_eq!(x.state, st, "step {}: state", i + 1);
|
||||
}
|
||||
}
|
||||
@@ -800,31 +800,11 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
|
||||
// The stroke is outlined from the flattened lines first, so the fill can then take them
|
||||
// without a copy; it is still drawn after the fill.
|
||||
let stroke = item.stroke.as_ref().and_then(|st| {
|
||||
let mut fx: ColorEffect = item.color;
|
||||
let mut pw = st.width * m.mean_scale();
|
||||
if !(pw.is_finite() && pw > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let shader = |fx: &ColorEffect| Shader::new(&Paint::Solid(st.color), &m, fx, None);
|
||||
if let Some(profile) = &st.profile {
|
||||
// Variable width (ADR 0018). Thin strokes fade by their widest part instead.
|
||||
let widest = pw * profile.max_factor();
|
||||
if !(widest.is_finite() && widest > 0.0) {
|
||||
return None;
|
||||
}
|
||||
if widest < 1.0 {
|
||||
fx.alpha *= widest;
|
||||
pw /= widest;
|
||||
}
|
||||
let polys = stroke::variable_polygons(&lines, pw * 0.5, profile, m.inverse().as_ref(), m.determinant() < 0.0);
|
||||
return Some((polys, shader(&fx)));
|
||||
}
|
||||
if pw < 1.0 {
|
||||
// Thin strokes: keep a 1 px footprint and fade by width (avoids dropouts).
|
||||
fx.alpha *= pw;
|
||||
pw = 1.0;
|
||||
}
|
||||
Some((stroke::stroke_polygons(&lines, pw * 0.5), shader(&fx)))
|
||||
// Caps, joins, dashes (ADR 0046) and width profiles (ADR 0018); thin strokes and
|
||||
// sub-pixel dash patterns fade instead of dropping out.
|
||||
let (polys, alpha) = stroke::stroke_geometry(&lines, st, &m, true)?;
|
||||
let fx = ColorEffect { alpha: item.color.alpha * alpha, ..item.color };
|
||||
Some((polys, Shader::new(&Paint::Solid(st.color), &m, &fx, None)))
|
||||
});
|
||||
if let Some(fill) = &item.fill {
|
||||
let polys: Vec<Vec<Vec2>> = lines.into_iter().map(|l| l.points).collect();
|
||||
@@ -995,7 +975,7 @@ mod tests {
|
||||
fn prepared_scenes_match_the_renderers_preparation_and_name_what_needs_more() {
|
||||
// A filled, stroked square and an off-screen circle: fill then stroke, one culled.
|
||||
let mut sq = item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
|
||||
sq.stroke = Some(anicraft_doc::Stroke { color: Rgba::WHITE, width: 2.0, profile: None });
|
||||
sq.stroke = Some(anicraft_doc::Stroke::new(Rgba::WHITE, 2.0));
|
||||
let off = item(Path::ellipse(500.0, 500.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK));
|
||||
let dl = list(vec![sq.clone(), off]);
|
||||
let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
@@ -1188,18 +1168,34 @@ mod tests {
|
||||
#[test]
|
||||
#[ignore = "measurement"]
|
||||
fn variable_stroke_cost() {
|
||||
let strokes = |profile: Option<anicraft_doc::WidthProfile>| {
|
||||
use anicraft_doc::{Cap, Dash, Join, StrokeStyle};
|
||||
let strokes = |profile: Option<anicraft_doc::WidthProfile>, style: StrokeStyle| {
|
||||
let items = (0..300)
|
||||
.map(|i| {
|
||||
let (x, y) = ((i % 20) as f32 * 64.0, (i / 20) as f32 * 48.0);
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(x, y + 40.0)).cubic_to(Vec2::new(x + 10.0, y - 20.0), Vec2::new(x + 50.0, y + 80.0), Vec2::new(x + 60.0, y + 10.0));
|
||||
stroked(p, 6.0, profile.clone())
|
||||
let mut it = stroked(p, 6.0, profile.clone());
|
||||
it.stroke = it.stroke.map(|st| st.with_style(style.clone()));
|
||||
it
|
||||
})
|
||||
.collect();
|
||||
list(items)
|
||||
};
|
||||
for (name, dl) in [("uniform", strokes(None)), ("taper_both", strokes(anicraft_doc::ProfilePreset::TaperBoth.profile())), ("bulge", strokes(anicraft_doc::ProfilePreset::Bulge.profile()))] {
|
||||
let round = StrokeStyle::default();
|
||||
let miter = StrokeStyle { cap: Cap::Square, join: Join::Miter, ..StrokeStyle::default() };
|
||||
let dashed = StrokeStyle { cap: Cap::Butt, dash: Dash::dashed(8.0, 4.0), ..StrokeStyle::default() };
|
||||
let dotted = StrokeStyle { dash: Dash::dotted(4.0), ..StrokeStyle::default() };
|
||||
let taper = || anicraft_doc::ProfilePreset::TaperBoth.profile();
|
||||
for (name, dl) in [
|
||||
("uniform", strokes(None, round.clone())),
|
||||
("taper_both", strokes(taper(), round)),
|
||||
("bulge", strokes(anicraft_doc::ProfilePreset::Bulge.profile(), StrokeStyle::default())),
|
||||
("square + miter", strokes(None, miter)),
|
||||
("dashed 8/4", strokes(None, dashed.clone())),
|
||||
("dotted 4", strokes(None, dotted)),
|
||||
("taper_both dashed", strokes(taper(), dashed)),
|
||||
] {
|
||||
let mut ms: Vec<f64> = (0..9)
|
||||
.map(|_| {
|
||||
let t = std::time::Instant::now();
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
//! that persists from frame to frame (same layer, element and path structure) becomes one
|
||||
//! shape layer, its outline baked into stage space. Whatever changes (outline, colours,
|
||||
//! gradient points, stroke width, opacity, masks) is written as hold keyframes at the frames
|
||||
//! where it changes, so any Lottie player shows exactly AniCraft's frames. Strokes use round
|
||||
//! joins and caps, like the renderer; variable-width strokes are filled outlines (the
|
||||
//! polygons the renderer fills).
|
||||
//! where it changes, so any Lottie player shows exactly AniCraft's frames. Strokes keep their
|
||||
//! caps, joins, miter limit and dashes (dash lengths scaled like the width, dots as zero-length
|
||||
//! round dashes; ADR 0046); variable-width strokes are filled outlines (the polygons the
|
||||
//! renderer fills, dashes included).
|
||||
//!
|
||||
//! Not carried across (counted in the report): bitmap fills; nested masks keep only the
|
||||
//! innermost mask; a symbol fading as one group is faded shape by shape; stretched radial
|
||||
@@ -135,13 +136,54 @@ enum Fill {
|
||||
struct Sample {
|
||||
paths: Vec<Bez>,
|
||||
fill: Option<Fill>,
|
||||
stroke: Option<(Rgba, f32)>,
|
||||
stroke: Option<Line>,
|
||||
/// Group opacity (a fading symbol), applied to the shape as a whole.
|
||||
opacity: f32,
|
||||
/// Mask outlines this artwork shows through (their union).
|
||||
masks: Vec<Bez>,
|
||||
}
|
||||
|
||||
/// A stroke in one frame, in stage space.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct Line {
|
||||
color: Rgba,
|
||||
width: f32,
|
||||
/// Lottie's line cap and join numbers (1 butt / miter, 2 round, 3 square / bevel).
|
||||
cap: u8,
|
||||
join: u8,
|
||||
miter: f32,
|
||||
/// On and off lengths (stage units), and the offset into them.
|
||||
dash: Vec<f32>,
|
||||
offset: f32,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
/// A round, solid line (outline mode's hairline).
|
||||
fn round(color: Rgba, width: f32) -> Line {
|
||||
Line { color, width, cap: 2, join: 2, miter: 4.0, dash: Vec::new(), offset: 0.0 }
|
||||
}
|
||||
|
||||
fn of(st: &anicraft_doc::Stroke, color: Rgba, k: f32) -> Line {
|
||||
use anicraft_doc::{Cap, Join};
|
||||
let style = &st.style;
|
||||
let cap = match style.effective_cap() {
|
||||
Cap::Butt => 1,
|
||||
Cap::Round => 2,
|
||||
Cap::Square => 3,
|
||||
};
|
||||
let join = match style.join {
|
||||
Join::Miter => 1,
|
||||
Join::Round => 2,
|
||||
Join::Bevel => 3,
|
||||
};
|
||||
let (dash, offset) = style.dash.as_ref().map_or((Vec::new(), 0.0), |d| {
|
||||
let (l, o) = d.pattern(st.width);
|
||||
(l.into_iter().map(|x| x * k).collect(), o * k)
|
||||
});
|
||||
Line { color, width: st.width * k, cap, join, miter: style.miter_limit, dash, offset }
|
||||
}
|
||||
}
|
||||
|
||||
/// Subpaths as (closed, vertex count): what must match for values to be keyframed.
|
||||
type Structure = Vec<(bool, usize)>;
|
||||
|
||||
@@ -155,7 +197,8 @@ struct Key {
|
||||
shape: Structure,
|
||||
fill: u8,
|
||||
stops: usize,
|
||||
stroke: bool,
|
||||
/// The stroke's cap, join and dash entry count (its lengths may change from frame to frame).
|
||||
stroke: Option<(u8, u8, usize)>,
|
||||
masks: Structure,
|
||||
/// Lottie layer blend mode (`bm`).
|
||||
blend: u8,
|
||||
@@ -222,7 +265,7 @@ fn sample(item: &DisplayItem, opacity: f32, masks: Vec<Bez>, report: &mut HashSe
|
||||
let fx = &item.color;
|
||||
let (fill, stroke) = if let Some(c) = item.outline {
|
||||
// Outline mode: a 1 px hairline in the layer colour, as on the stage.
|
||||
(None, Some((c, 1.0)))
|
||||
(None, Some(Line::round(c, 1.0)))
|
||||
} else {
|
||||
let fill = match &item.fill {
|
||||
Some(Paint::Solid(c)) => Some(Fill::Solid { color: fx.apply(*c), rule: item.fill_rule }),
|
||||
@@ -247,7 +290,7 @@ fn sample(item: &DisplayItem, opacity: f32, masks: Vec<Bez>, report: &mut HashSe
|
||||
};
|
||||
let stroke = item.stroke.as_ref().and_then(|s| {
|
||||
let w = s.width * m.mean_scale();
|
||||
(w.is_finite() && w > 0.0).then(|| (fx.apply(s.color), w))
|
||||
(w.is_finite() && w > 0.0).then(|| Line::of(s, fx.apply(s.color), m.mean_scale()))
|
||||
});
|
||||
(fill, stroke)
|
||||
};
|
||||
@@ -354,7 +397,7 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo
|
||||
Some(Fill::Gradient { stops, .. }) => stops.len(),
|
||||
_ => 0,
|
||||
},
|
||||
stroke: s.stroke.is_some(),
|
||||
stroke: s.stroke.as_ref().map(|l| (l.cap, l.join, l.dash.len())),
|
||||
masks: s.masks.iter().map(|b| (b.closed, b.v.len())).collect(),
|
||||
blend,
|
||||
};
|
||||
@@ -485,11 +528,28 @@ fn layer(tr: &Track, ind: usize) -> Value {
|
||||
let values: Vec<(u32, Value)> = f.iter().filter_map(|(t, s)| s.paths.get(k).map(|b| (*t, b.to_value()))).collect();
|
||||
items.push(json!({"ty": "sh", "nm": format!("Path {}", k + 1), "ks": shape_prop(&values)}));
|
||||
}
|
||||
if tr.key.stroke {
|
||||
let color: Vec<(u32, Value)> = f.iter().filter_map(|(t, s)| s.stroke.map(|(c, _)| (*t, rgb(c)))).collect();
|
||||
let opacity: Vec<(u32, Value)> = f.iter().filter_map(|(t, s)| s.stroke.map(|(c, _)| (*t, n(c.sanitized().a * 100.0)))).collect();
|
||||
let width: Vec<(u32, Value)> = f.iter().filter_map(|(t, s)| s.stroke.map(|(_, w)| (*t, n(w)))).collect();
|
||||
items.push(json!({"ty": "st", "nm": "Stroke", "c": prop(&color), "o": prop(&opacity), "w": prop(&width), "lc": 2, "lj": 2, "ml": 4}));
|
||||
if let Some((cap, join, dashes)) = tr.key.stroke {
|
||||
let lines: Vec<(u32, &Line)> = f.iter().filter_map(|(t, s)| s.stroke.as_ref().map(|l| (*t, l))).collect();
|
||||
let values = |g: &dyn Fn(&Line) -> Value| lines.iter().map(|(t, l)| (*t, g(l))).collect::<Vec<(u32, Value)>>();
|
||||
let color = values(&|l| rgb(l.color));
|
||||
let opacity = values(&|l| n(l.color.sanitized().a * 100.0));
|
||||
let width = values(&|l| n(l.width));
|
||||
// The miter limit is a plain number in Lottie: the first frame's.
|
||||
// (Round and bevel joins don't use it: Lottie's usual 4, as before styles.)
|
||||
let miter = if join == 1 { lines.first().map_or(json!(4), |(_, l)| n(l.miter)) } else { json!(4) };
|
||||
let mut st = json!({"ty": "st", "nm": "Stroke", "c": prop(&color), "o": prop(&opacity), "w": prop(&width), "lc": cap, "lj": join, "ml": miter});
|
||||
if dashes > 0 {
|
||||
// Dash, gap, dash, gap…, then the offset; each animates like any value.
|
||||
let mut d: Vec<Value> = (0..dashes)
|
||||
.map(|k| {
|
||||
let (code, name) = if k % 2 == 0 { ("d", "dash") } else { ("g", "gap") };
|
||||
json!({"n": code, "nm": name, "v": prop(&values(&|l| n(l.dash.get(k).copied().unwrap_or(0.0))))})
|
||||
})
|
||||
.collect();
|
||||
d.push(json!({"n": "o", "nm": "offset", "v": prop(&values(&|l| n(l.offset)))}));
|
||||
st["d"] = Value::Array(d);
|
||||
}
|
||||
items.push(st);
|
||||
}
|
||||
match f.first().and_then(|(_, s)| s.fill.as_ref()) {
|
||||
Some(Fill::Solid { rule: r, .. }) => {
|
||||
@@ -629,4 +689,32 @@ mod tests {
|
||||
assert!(!it.iter().any(|i| i["ty"] == "st"), "no Lottie stroke");
|
||||
assert!(e.report.is_empty(), "nothing lost: {:?}", e.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_caps_joins_and_dashes_carry_across() {
|
||||
use anicraft_doc::{Cap, Dash, Document, Element, ElementId, ElementKind, Join, Shape, Stroke, StrokeStyle};
|
||||
let export = |st: Stroke| {
|
||||
let mut doc = Document::default();
|
||||
let shape = Shape { path: std::sync::Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(st), fill_rule: FillRule::NonZero, merge: false };
|
||||
let el = Element { id: ElementId(77), name: String::new(), transform: Affine::scale(2.0, 2.0), color: Default::default(), kind: ElementKind::Shape(shape) };
|
||||
let layer = std::sync::Arc::make_mut(&mut doc.timeline_mut(0).layers[0]);
|
||||
layer.keyframe_mut(0).unwrap().elements.push(std::sync::Arc::new(el));
|
||||
let v = parse(&to_lottie(&doc, "s", 0, 0, false));
|
||||
v["layers"][0]["shapes"][0]["it"].as_array().unwrap().iter().find(|i| i["ty"] == "st").cloned().unwrap()
|
||||
};
|
||||
// Round and solid as before.
|
||||
let st = export(Stroke::new(Rgba::BLACK, 3.0));
|
||||
assert_eq!((st["lc"].clone(), st["lj"].clone(), st["ml"].clone(), st.get("d").is_none()), (json!(2), json!(2), json!(4), true));
|
||||
// Butt caps, miter joins with their limit, dashes scaled like the width.
|
||||
let style = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 6.0, dash: Some(Dash::Dashed { lengths: vec![4.0, 1.5].into(), offset: 1.0 }) };
|
||||
let st = export(Stroke::new(Rgba::BLACK, 3.0).with_style(style));
|
||||
assert_eq!((st["lc"].clone(), st["lj"].clone(), st["ml"].clone(), st["w"]["k"].clone()), (json!(1), json!(1), json!(6.0), json!(6.0)));
|
||||
let d = st["d"].as_array().unwrap();
|
||||
let got: Vec<(&str, f64)> = d.iter().map(|e| (e["n"].as_str().unwrap(), e["v"]["k"].as_f64().unwrap())).collect();
|
||||
assert_eq!(got, [("d", 8.0), ("g", 3.0), ("o", 2.0)]);
|
||||
// Dots: zero-length dashes with round caps, whatever the cap.
|
||||
let st = export(Stroke::new(Rgba::BLACK, 3.0).with_style(StrokeStyle { cap: Cap::Square, join: Join::Bevel, dash: Dash::dotted(2.0), ..StrokeStyle::default() }));
|
||||
assert_eq!((st["lc"].clone(), st["lj"].clone()), (json!(2), json!(3)));
|
||||
assert_eq!((st["d"][0]["v"]["k"].as_f64(), st["d"][1]["v"]["k"].as_f64()), (Some(0.0), Some(10.0)));
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
//! non-zero rule gives a seamless union without computing an outline offset.
|
||||
|
||||
use anicraft_doc::width::left_normal;
|
||||
use anicraft_doc::{DisplayItem, DisplayList, WidthProfile};
|
||||
use anicraft_doc::{Cap, DisplayItem, DisplayList, Join, Stroke, WidthProfile};
|
||||
use anicraft_geom::{Affine, Path, Polyline, Vec2};
|
||||
|
||||
fn signed_area(p: &[Vec2]) -> f32 {
|
||||
@@ -211,6 +211,324 @@ pub fn variable_polygons(lines: &[Polyline], hw: f32, profile: &WidthProfile, to
|
||||
out
|
||||
}
|
||||
|
||||
/// How a stroke's outline is shaped, in output units (the stroker's view of a
|
||||
/// [`anicraft_doc::StrokeStyle`]).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Outline<'a> {
|
||||
pub cap: Cap,
|
||||
pub join: Join,
|
||||
pub miter_limit: f32,
|
||||
/// On/off lengths along each subpath (output units, starting with a dash) and how far into
|
||||
/// them each subpath starts; `None`: solid.
|
||||
pub dash: Option<(&'a [f32], f32)>,
|
||||
}
|
||||
|
||||
impl Outline<'_> {
|
||||
/// Round caps and joins, solid: the stroke every shape had before styles.
|
||||
pub const ROUND: Outline<'static> = Outline { cap: Cap::Round, join: Join::Round, miter_limit: anicraft_doc::stroke_style::DEFAULT_MITER_LIMIT, dash: None };
|
||||
|
||||
fn is_round(&self) -> bool {
|
||||
self.cap == Cap::Round && self.join == Join::Round && self.dash.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Most dashes one stroke is cut into; past that, the rest of each subpath draws solid (only
|
||||
/// reached by very long, very finely dashed lines zoomed far in).
|
||||
const MAX_DASHES: usize = 200_000;
|
||||
|
||||
/// Polygons covering a stroke with any caps, joins and dashes, uniform (`profile` `None`) or
|
||||
/// variable, all positively wound like [`stroke_polygons`] so non-zero filling gives their
|
||||
/// union. Round, solid strokes take [`stroke_polygons`] and [`variable_polygons`] exactly.
|
||||
///
|
||||
/// `hw`, `profile`, `to_local` and `flip` are as in [`variable_polygons`]. Dashes are measured
|
||||
/// along the flattened lines in output units and restart at every subpath, as in SVG; each
|
||||
/// dash is an open piece with the stroke's caps, its widths those of its place on the whole
|
||||
/// subpath. A zero-length dash is a dot: its caps alone.
|
||||
pub fn styled_polygons(lines: &[Polyline], hw: f32, outline: &Outline, profile: Option<&WidthProfile>, to_local: Option<&Affine>, flip: bool) -> Vec<Vec<Vec2>> {
|
||||
if outline.is_round() {
|
||||
return match profile {
|
||||
Some(pr) => variable_polygons(lines, hw, pr, to_local, flip),
|
||||
None => stroke_polygons(lines, hw),
|
||||
};
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if !(hw.is_finite() && hw > 0.0) {
|
||||
return out;
|
||||
}
|
||||
let dash = outline.dash.filter(|(l, _)| l.len() >= 2 && l.iter().all(|x| x.is_finite() && *x >= 0.0) && l.iter().sum::<f32>() > 1e-6);
|
||||
let mut budget = MAX_DASHES;
|
||||
for pl in lines {
|
||||
let pts = if profile.is_some() { resample(pl) } else { cleaned(pl) };
|
||||
let n = pts.len();
|
||||
if n < 2 {
|
||||
continue;
|
||||
}
|
||||
let closed = pl.closed && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.distance(*b) < 1e-4);
|
||||
// Arc length along the output lines (dashes), and in the shape's space (the profile).
|
||||
let cum = cumulative(&pts);
|
||||
let widths: Vec<(f32, f32)> = match profile {
|
||||
Some(pr) => {
|
||||
let local: Vec<Vec2> = match to_local {
|
||||
Some(m) => pts.iter().map(|p| m.apply(*p)).collect(),
|
||||
None => pts.clone(),
|
||||
};
|
||||
let lc = cumulative(&local);
|
||||
let total = lc.last().copied().filter(|d| d.is_finite() && *d > 0.0).unwrap_or(1.0);
|
||||
lc.iter().map(|c| side_widths(pr, c / total, hw, flip)).collect()
|
||||
}
|
||||
None => vec![(hw, hw); n],
|
||||
};
|
||||
let Some((pattern, offset)) = dash else {
|
||||
stroke_piece(&pts, &widths, closed, outline, &mut out);
|
||||
continue;
|
||||
};
|
||||
let total = cum.last().copied().unwrap_or(0.0);
|
||||
let mut cut = Cutter { pts: &pts, cum: &cum, widths: &widths, seg: 0 };
|
||||
for (a, b) in dash_intervals(pattern, offset, total, &mut budget) {
|
||||
if b - a <= 1e-6 {
|
||||
// A dot: the caps of a piece with no length.
|
||||
let (p, d, w) = cut.at(a);
|
||||
out.extend(cap(p, -d, left_normal(d), w, outline.cap, false));
|
||||
out.extend(cap(p, d, left_normal(d), w, outline.cap, true));
|
||||
continue;
|
||||
}
|
||||
let (piece, pw) = cut.piece(a, b);
|
||||
stroke_piece(&piece, &pw, false, outline, &mut out);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The half-widths on each side at `t` of the way along, in output units.
|
||||
fn side_widths(pr: &WidthProfile, t: f32, hw: f32, flip: bool) -> (f32, f32) {
|
||||
let (l, r) = pr.at(t);
|
||||
if flip { (r * hw, l * hw) } else { (l * hw, r * hw) }
|
||||
}
|
||||
|
||||
fn cumulative(pts: &[Vec2]) -> Vec<f32> {
|
||||
let mut cum = Vec::with_capacity(pts.len());
|
||||
let mut d = 0.0f32;
|
||||
cum.push(0.0);
|
||||
for w in pts.windows(2) {
|
||||
d += w[0].distance(w[1]);
|
||||
cum.push(d);
|
||||
}
|
||||
cum
|
||||
}
|
||||
|
||||
/// The on stretches `[a, b]` of a dash pattern along a subpath `total` long, in order (a dot
|
||||
/// is a stretch with `a == b`). Uses up `budget`; when it runs out, the rest of the subpath is
|
||||
/// one stretch.
|
||||
fn dash_intervals(pattern: &[f32], offset: f32, total: f32, budget: &mut usize) -> Vec<(f32, f32)> {
|
||||
let mut out = Vec::new();
|
||||
let period: f32 = pattern.iter().sum();
|
||||
if !(total.is_finite() && total > 0.0 && period.is_finite() && period > 0.0) {
|
||||
return out;
|
||||
}
|
||||
// Entry `i` of period `k` starts at `base + k · period + starts[i]`: the subpath begins the
|
||||
// offset into the pattern. (Positions are computed, not summed, so they don't drift.)
|
||||
let base = -(if offset.is_finite() { offset.rem_euclid(period) } else { 0.0 });
|
||||
let mut starts = Vec::with_capacity(pattern.len());
|
||||
let mut acc = 0.0f32;
|
||||
for &len in pattern {
|
||||
starts.push(acc);
|
||||
acc += len;
|
||||
}
|
||||
// Every period holds a dash (entry 0), so the budget bounds the walk.
|
||||
'periods: for k in 0u32.. {
|
||||
let p0 = base + k as f32 * period;
|
||||
for (i, (&len, &st)) in pattern.iter().zip(&starts).enumerate() {
|
||||
let s = p0 + st;
|
||||
if s > total {
|
||||
break 'periods;
|
||||
}
|
||||
let e = s + len;
|
||||
if i % 2 == 0 && (if len > 0.0 { e > 0.0 && s < total } else { s >= 0.0 }) {
|
||||
if *budget == 0 {
|
||||
out.push((s.max(0.0), total));
|
||||
break 'periods;
|
||||
}
|
||||
*budget -= 1;
|
||||
out.push((s.max(0.0), e.min(total)));
|
||||
}
|
||||
}
|
||||
if k == u32::MAX {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Cuts pieces out of a subpath by arc length, walking forwards.
|
||||
struct Cutter<'a> {
|
||||
pts: &'a [Vec2],
|
||||
cum: &'a [f32],
|
||||
widths: &'a [(f32, f32)],
|
||||
/// The segment the last cut was in.
|
||||
seg: usize,
|
||||
}
|
||||
|
||||
impl Cutter<'_> {
|
||||
/// The segment index holding arc length `s` (moving forwards from the last one).
|
||||
fn find(&mut self, s: f32) -> usize {
|
||||
let last = self.pts.len().saturating_sub(2);
|
||||
while self.seg < last && self.cum.get(self.seg + 1).is_some_and(|&c| c < s) {
|
||||
self.seg += 1;
|
||||
}
|
||||
self.seg
|
||||
}
|
||||
|
||||
/// The point, direction and widths at arc length `s`.
|
||||
fn at(&mut self, s: f32) -> (Vec2, Vec2, (f32, f32)) {
|
||||
let i = self.find(s);
|
||||
let (a, b) = (self.pts.get(i).copied().unwrap_or(Vec2::ZERO), self.pts.get(i + 1).copied().unwrap_or(Vec2::ZERO));
|
||||
let (c0, c1) = (self.cum.get(i).copied().unwrap_or(0.0), self.cum.get(i + 1).copied().unwrap_or(0.0));
|
||||
let k = if c1 > c0 { ((s - c0) / (c1 - c0)).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let (w0, w1) = (self.widths.get(i).copied().unwrap_or((0.0, 0.0)), self.widths.get(i + 1).copied().unwrap_or((0.0, 0.0)));
|
||||
let w = (w0.0 + (w1.0 - w0.0) * k, w0.1 + (w1.1 - w0.1) * k);
|
||||
(a.lerp(b, k), (b - a).normalized(), w)
|
||||
}
|
||||
|
||||
/// The points and widths from arc length `a` to `b` (no repeated points).
|
||||
fn piece(&mut self, a: f32, b: f32) -> (Vec<Vec2>, Vec<(f32, f32)>) {
|
||||
let (p0, _, w0) = self.at(a);
|
||||
let mut pts = vec![p0];
|
||||
let mut ws = vec![w0];
|
||||
let mut push = |p: Vec2, w: (f32, f32)| {
|
||||
if pts.last().is_none_or(|q| q.distance(p) > 1e-6) {
|
||||
pts.push(p);
|
||||
ws.push(w);
|
||||
}
|
||||
};
|
||||
let mut j = self.seg + 1;
|
||||
while let (Some(&c), Some(&p)) = (self.cum.get(j), self.pts.get(j)) {
|
||||
if c >= b {
|
||||
break;
|
||||
}
|
||||
if c > a {
|
||||
push(p, self.widths.get(j).copied().unwrap_or((0.0, 0.0)));
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
let (p1, _, w1) = self.at(b);
|
||||
push(p1, w1);
|
||||
(pts, ws)
|
||||
}
|
||||
}
|
||||
|
||||
/// One open or closed run of points with its half-widths per point: a trapezoid per segment,
|
||||
/// a join at every bend and caps at open ends.
|
||||
fn stroke_piece(pts: &[Vec2], widths: &[(f32, f32)], closed: bool, outline: &Outline, out: &mut Vec<Vec<Vec2>>) {
|
||||
let n = pts.len();
|
||||
if n < 2 {
|
||||
return;
|
||||
}
|
||||
let w = |i: usize| widths.get(i).copied().unwrap_or((0.0, 0.0));
|
||||
let p = |i: usize| pts.get(i).copied().unwrap_or(Vec2::ZERO);
|
||||
let dir = |i: usize| (p(i + 1) - p(i)).normalized();
|
||||
for i in 0..n - 1 {
|
||||
let (a, b) = (p(i), p(i + 1));
|
||||
if a.distance(b) < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let ((la, ra), (lb, rb)) = (w(i), w(i + 1));
|
||||
if la.max(ra).max(lb).max(rb) <= NO_WIDTH {
|
||||
continue;
|
||||
}
|
||||
let nrm = left_normal(dir(i));
|
||||
out.push(oriented(vec![a + nrm * la, b + nrm * lb, b - nrm * rb, a - nrm * ra]));
|
||||
}
|
||||
let joints = (1..n - 1).map(|i| (i, i - 1, i)).chain(closed.then_some((0, n - 2, 0)));
|
||||
for (at, before, after) in joints {
|
||||
out.extend(join(p(at), dir(before), dir(after), w(at), outline));
|
||||
}
|
||||
if !closed {
|
||||
let (d0, d1) = (dir(0), dir(n - 2));
|
||||
out.extend(cap(p(0), -d0, left_normal(d0), w(0), outline.cap, false));
|
||||
out.extend(cap(p(n - 1), d1, left_normal(d1), w(n - 1), outline.cap, true));
|
||||
}
|
||||
}
|
||||
|
||||
/// What fills the outer side of a bend at `p` from direction `u` to `v` (unit vectors), with
|
||||
/// half-widths `(left, right)` there; `None` on (nearly) straight runs, where the segments'
|
||||
/// trapezoids already meet.
|
||||
fn join(p: Vec2, u: Vec2, v: Vec2, (l, r): (f32, f32), outline: &Outline) -> Option<Vec<Vec2>> {
|
||||
if u.dot(v) > 0.0 && u.cross(v).abs() * l.max(r) < 0.05 {
|
||||
return None;
|
||||
}
|
||||
// The gap opens on the outside of the bend, around the direction u − v.
|
||||
let mid = (u - v).normalized();
|
||||
let (n0, n1) = (left_normal(u), left_normal(v));
|
||||
let (s, radius) = if mid.dot(n0) >= 0.0 { (1.0, l) } else { (-1.0, r) };
|
||||
if radius <= NO_WIDTH {
|
||||
return None;
|
||||
}
|
||||
let (o0, o1) = (n0 * s, n1 * s);
|
||||
let (a, b) = (p + o0 * radius, p + o1 * radius);
|
||||
match outline.join {
|
||||
Join::Round => {
|
||||
let (a0, a1, am) = (angle(o0), angle(o1), angle(mid));
|
||||
let wrap = |x: f32| (x + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI;
|
||||
let mut sweep = wrap(a1 - a0);
|
||||
let to_mid = wrap(am - a0);
|
||||
if to_mid * sweep < 0.0 || to_mid.abs() > sweep.abs() {
|
||||
sweep -= std::f32::consts::TAU.copysign(sweep);
|
||||
}
|
||||
fan(p, a0, sweep, radius, radius)
|
||||
}
|
||||
Join::Miter | Join::Bevel => {
|
||||
// The outer edges meet at p + (o0 + o1) / (1 + o0·o1) · radius, 1 / cos(θ/2) half-
|
||||
// widths out (θ the turn); SVG's miter ratio is that over the half-width.
|
||||
let c = 1.0 + o0.dot(o1);
|
||||
let limit = outline.miter_limit.clamp(1.0, anicraft_doc::stroke_style::MAX_MITER_LIMIT);
|
||||
if outline.join == Join::Miter && c > 1e-6 && c * limit * limit >= 2.0 {
|
||||
let tip = p + (o0 + o1) * (radius / c);
|
||||
Some(oriented(vec![p, a, tip, b]))
|
||||
} else {
|
||||
Some(oriented(vec![p, a, b]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The cap at end `at` of a piece, facing `out` (unit, away from the piece), across the cross-
|
||||
/// section with left normal `nrm` and half-widths `(left, right)`. `end`: the piece's last
|
||||
/// point (so the half disc turns the other way).
|
||||
fn cap(at: Vec2, out: Vec2, nrm: Vec2, (l, r): (f32, f32), kind: Cap, end: bool) -> Option<Vec<Vec2>> {
|
||||
let half = (l + r) * 0.5;
|
||||
if half <= NO_WIDTH || !out.is_finite() {
|
||||
return None;
|
||||
}
|
||||
match kind {
|
||||
Cap::Butt => None,
|
||||
// Half a disc across the cross-section (so a one-sided width stays on its side).
|
||||
Cap::Round => fan(at + nrm * ((l - r) * 0.5), angle(nrm), if end { std::f32::consts::PI } else { -std::f32::consts::PI }, half, half),
|
||||
// The cross-section carried half its thickness past the end.
|
||||
Cap::Square => {
|
||||
let (pl, pr) = (at + nrm * l, at - nrm * r);
|
||||
Some(oriented(vec![pl, pl + out * half, pr + out * half, pr]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A polyline's finite points with repeats dropped and the start repeated at the end when it
|
||||
/// is closed (no subdivision: one width needs none).
|
||||
fn cleaned(pl: &Polyline) -> Vec<Vec2> {
|
||||
let mut out: Vec<Vec2> = Vec::with_capacity(pl.points.len() + 1);
|
||||
for &p in pl.points.iter().filter(|p| p.is_finite()) {
|
||||
if out.last().is_none_or(|q| q.distance(p) > 1e-6) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
if pl.closed
|
||||
&& let (Some(&first), Some(&last)) = (out.first(), out.last())
|
||||
&& first.distance(last) > 1e-6
|
||||
{
|
||||
out.push(first);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A polyline's points with long segments subdivided (so widths can follow a profile), the
|
||||
/// start repeated at the end when it is closed, and repeated points dropped.
|
||||
fn resample(pl: &Polyline) -> Vec<Vec2> {
|
||||
@@ -243,14 +561,65 @@ fn resample(pl: &Polyline) -> Vec<Vec2> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A variable-width stroke as a filled outline in `m`'s output space, for vector exports: the
|
||||
/// same polygons the renderer fills, as closed subpaths (fill them non-zero).
|
||||
pub fn variable_outline(path: &Path, m: &Affine, width: f32, profile: &WidthProfile, tolerance: f32) -> Path {
|
||||
/// The polygons stroke `st` fills along `lines` (its path flattened through `m`), and how much
|
||||
/// to fade them; `None` when it draws nothing.
|
||||
///
|
||||
/// `raster` is what the renderer does for strokes too fine for pixels: a stroke thinner than
|
||||
/// one output unit keeps that footprint and fades by its width instead (no dropouts), and a
|
||||
/// dash pattern repeating in less than one output unit draws solid, faded by how much of it is
|
||||
/// on. Vector outlines leave it off and get the exact geometry. Dash lengths are measured along
|
||||
/// the output lines, scaled like the width (by the mean scale of `m`), so vector exports, which
|
||||
/// write `stroke-dasharray` the same way, draw the same dashes.
|
||||
pub fn stroke_geometry(lines: &[Polyline], st: &Stroke, m: &Affine, raster: bool) -> Option<(Vec<Vec<Vec2>>, f32)> {
|
||||
let scale = m.mean_scale();
|
||||
let mut pw = st.width * scale;
|
||||
if !(pw.is_finite() && pw > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let mut alpha = 1.0f32;
|
||||
let widest = pw * st.profile.as_ref().map_or(1.0, WidthProfile::max_factor);
|
||||
if !(widest.is_finite() && widest > 0.0) {
|
||||
return None;
|
||||
}
|
||||
if raster && widest < 1.0 {
|
||||
alpha *= widest;
|
||||
pw /= widest;
|
||||
}
|
||||
let style = &st.style;
|
||||
let cap = style.effective_cap();
|
||||
let pattern = style.dash.as_ref().map(|d| {
|
||||
let (l, o) = d.pattern(st.width);
|
||||
(l.into_iter().map(|x| x * scale).collect::<Vec<f32>>(), o * scale)
|
||||
});
|
||||
let mut dash = pattern.as_ref().map(|(l, o)| (l.as_slice(), *o));
|
||||
if let Some((l, _)) = dash {
|
||||
let period: f32 = l.iter().sum();
|
||||
if !(period.is_finite() && period > 0.0) {
|
||||
dash = None;
|
||||
} else if raster && period < 1.0 {
|
||||
// Finer than a pixel: solid, as light as the pattern's ink.
|
||||
let dashes = l.len().div_ceil(2) as f32;
|
||||
let on: f32 = l.iter().step_by(2).sum::<f32>() + if cap == Cap::Butt { 0.0 } else { dashes * pw };
|
||||
alpha *= (on / period).clamp(0.0, 1.0);
|
||||
dash = None;
|
||||
}
|
||||
}
|
||||
let outline = Outline { cap, join: style.join, miter_limit: style.miter_limit, dash };
|
||||
let (to_local, flip) = match &st.profile {
|
||||
Some(_) => (m.inverse(), m.determinant() < 0.0),
|
||||
None => (None, false),
|
||||
};
|
||||
let polys = styled_polygons(lines, pw * 0.5, &outline, st.profile.as_ref(), to_local.as_ref(), flip);
|
||||
Some((polys, alpha))
|
||||
}
|
||||
|
||||
/// A stroke as a filled outline in `m`'s output space, for vector exports: the same polygons
|
||||
/// the renderer fills, as closed subpaths (fill them non-zero).
|
||||
pub fn stroke_outline(path: &Path, m: &Affine, st: &Stroke, tolerance: f32) -> Path {
|
||||
let lines = path.flatten(m, tolerance);
|
||||
let to_local = m.inverse();
|
||||
let flip = m.determinant() < 0.0;
|
||||
let mut out = Path::new();
|
||||
for poly in variable_polygons(&lines, width * 0.5 * m.mean_scale(), profile, to_local.as_ref(), flip) {
|
||||
let Some((polys, _)) = stroke_geometry(&lines, st, m, false) else { return out };
|
||||
for poly in polys {
|
||||
let mut it = poly.into_iter();
|
||||
let Some(first) = it.next() else { continue };
|
||||
out.move_to(first);
|
||||
@@ -272,7 +641,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa
|
||||
}
|
||||
let mut items = Vec::with_capacity(dl.items.len() + 8);
|
||||
for it in &dl.items {
|
||||
let Some((st, profile)) = it.stroke.as_ref().and_then(|s| s.profile.as_ref().map(|p| (s, p))).filter(|_| varies(it)) else {
|
||||
let Some(st) = it.stroke.as_ref().filter(|_| varies(it)) else {
|
||||
items.push(it.clone());
|
||||
continue;
|
||||
};
|
||||
@@ -282,7 +651,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa
|
||||
if !it.transform.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let outline = variable_outline(&it.path, &it.transform, st.width, profile, crate::TOLERANCE);
|
||||
let outline = stroke_outline(&it.path, &it.transform, st, crate::TOLERANCE);
|
||||
if !outline.is_empty() {
|
||||
items.push(DisplayItem { path: std::sync::Arc::new(outline), transform: Affine::IDENTITY, fill: Some(anicraft_doc::Paint::Solid(st.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, image: None, ..it.clone() });
|
||||
}
|
||||
@@ -290,6 +659,10 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa
|
||||
std::borrow::Cow::Owned(DisplayList { items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "stroke_style_tests.rs"]
|
||||
mod style_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Analytic tests of caps, joins, the miter limit and dashes (ADR 0046).
|
||||
|
||||
use super::*;
|
||||
|
||||
fn area(polys: &[Vec<Vec2>]) -> f32 {
|
||||
polys.iter().map(|p| signed_area(p)).sum()
|
||||
}
|
||||
|
||||
fn styled(points: &[(f32, f32)], closed: bool, hw: f32, o: &Outline) -> Vec<Vec<Vec2>> {
|
||||
let pl = Polyline { points: points.iter().map(|&(x, y)| Vec2::new(x, y)).collect(), closed };
|
||||
let polys = styled_polygons(&[pl], hw, o, None, None, false);
|
||||
assert!(polys.iter().all(|p| signed_area(p) >= 0.0 && p.iter().all(|q| q.is_finite())), "positive and finite");
|
||||
polys
|
||||
}
|
||||
|
||||
fn outline(cap: Cap, join: Join) -> Outline<'static> {
|
||||
Outline { cap, join, ..Outline::ROUND }
|
||||
}
|
||||
|
||||
/// Whether `q` is inside the union (non-zero winding over every polygon).
|
||||
fn covered(polys: &[Vec<Vec2>], q: Vec2) -> bool {
|
||||
let mut wn = 0i32;
|
||||
for p in polys {
|
||||
for (i, &a) in p.iter().enumerate() {
|
||||
let b = p[(i + 1) % p.len()];
|
||||
let side = (b - a).cross(q - a);
|
||||
if a.y <= q.y && b.y > q.y && side > 0.0 {
|
||||
wn += 1;
|
||||
} else if a.y > q.y && b.y <= q.y && side < 0.0 {
|
||||
wn -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
wn != 0
|
||||
}
|
||||
|
||||
/// The union's area by sampling a grid `step` apart over `[x0, x1] × [y0, y1]`.
|
||||
fn union_area(polys: &[Vec<Vec2>], (x0, y0, x1, y1): (f32, f32, f32, f32), step: f32) -> f32 {
|
||||
let mut n = 0usize;
|
||||
let (nx, ny) = (((x1 - x0) / step) as usize, ((y1 - y0) / step) as usize);
|
||||
for j in 0..ny {
|
||||
for i in 0..nx {
|
||||
if covered(polys, Vec2::new(x0 + (i as f32 + 0.5) * step, y0 + (j as f32 + 0.5) * step)) {
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
n as f32 * step * step
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn butt_square_and_round_caps_differ_by_their_ends() {
|
||||
let line = [(0.0, 0.0), (100.0, 0.0)];
|
||||
// A butt-capped line is exactly its rectangle; square caps add half a width at each end.
|
||||
let butt = styled(&line, false, 5.0, &outline(Cap::Butt, Join::Miter));
|
||||
assert_eq!(butt.len(), 1);
|
||||
assert!((area(&butt) - 1000.0).abs() < 1e-3, "{}", area(&butt));
|
||||
let square = styled(&line, false, 5.0, &outline(Cap::Square, Join::Miter));
|
||||
assert!((area(&square) - 1100.0).abs() < 1e-3, "{}", area(&square));
|
||||
let xs = |p: &[Vec<Vec2>]| p.iter().flatten().fold((f32::MAX, f32::MIN), |(lo, hi), q| (lo.min(q.x), hi.max(q.x)));
|
||||
assert_eq!(xs(&butt), (0.0, 100.0));
|
||||
assert_eq!(xs(&square), (-5.0, 105.0));
|
||||
// Round: the rectangle plus a disc (half at each end), within the arc tolerance.
|
||||
let round = styled(&line, false, 5.0, &outline(Cap::Round, Join::Bevel));
|
||||
let want = 1000.0 + std::f32::consts::PI * 25.0;
|
||||
assert!((area(&round) - want).abs() < 0.01 * want, "{} vs {want}", area(&round));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn miter_bevel_and_round_corners() {
|
||||
// Right 50 then down 50 (y-down): the outer corner is up and to the right of (50, 0).
|
||||
let l = [(0.0, 0.0), (50.0, 0.0), (50.0, 50.0)];
|
||||
let corner = |join| {
|
||||
let polys = styled(&l, false, 5.0, &outline(Cap::Butt, join));
|
||||
// The corner piece alone: everything but the two segment rectangles.
|
||||
area(&polys) - 2.0 * 500.0
|
||||
};
|
||||
assert!((corner(Join::Miter) - 25.0).abs() < 1e-3, "a 5 × 5 square: {}", corner(Join::Miter));
|
||||
assert!((corner(Join::Bevel) - 12.5).abs() < 1e-3, "half of it: {}", corner(Join::Bevel));
|
||||
let round = corner(Join::Round);
|
||||
assert!((round - std::f32::consts::PI * 25.0 / 4.0).abs() < 0.6, "a quarter disc, within the arc tolerance: {round}");
|
||||
// The miter reaches the corner (55, -5); the bevel stops at the diagonal.
|
||||
let miter = styled(&l, false, 5.0, &outline(Cap::Butt, Join::Miter));
|
||||
let bevel = styled(&l, false, 5.0, &outline(Cap::Butt, Join::Bevel));
|
||||
assert!(covered(&miter, Vec2::new(54.5, -4.5)) && !covered(&bevel, Vec2::new(54.5, -4.5)));
|
||||
assert!(covered(&bevel, Vec2::new(52.0, -2.0)));
|
||||
// A closed square with miters is a full frame: the outer square less the inner one.
|
||||
let sq = styled(&[(0.0, 0.0), (40.0, 0.0), (40.0, 40.0), (0.0, 40.0)], true, 2.0, &outline(Cap::Round, Join::Miter));
|
||||
let a = union_area(&sq, (-4.0, -4.0, 44.0, 44.0), 0.25);
|
||||
assert!((a - (44.0 * 44.0 - 36.0 * 36.0)).abs() < 4.0, "{a}");
|
||||
assert!(covered(&sq, Vec2::new(-1.9, -1.9)), "sharp outer corner, also where the path closes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_miter_limit_bevels_sharp_corners() {
|
||||
// A 160° turn (a 20° corner): the miter is 1 / sin(10°) ≈ 5.76 half-widths long.
|
||||
let back = 20f32.to_radians();
|
||||
let l = [(0.0, 0.0), (50.0, 0.0), (50.0 - 30.0 * back.cos(), 30.0 * back.sin())];
|
||||
let ratio = 1.0 / 10f32.to_radians().sin();
|
||||
let reach = |limit: f32| {
|
||||
let o = Outline { miter_limit: limit, ..outline(Cap::Butt, Join::Miter) };
|
||||
styled(&l, false, 2.0, &o).iter().flatten().map(|q| q.distance(Vec2::new(50.0, 0.0))).filter(|d| *d < 20.0).fold(0.0f32, f32::max)
|
||||
};
|
||||
assert!((reach(6.0) - ratio * 2.0).abs() < 1e-3, "under the limit: a point {} px out", reach(6.0));
|
||||
assert!(reach(5.5) < 2.0 + 1e-3, "over the limit: bevelled, {} px out", reach(5.5));
|
||||
// Animate's default (3) and SVG's (4) both bevel it.
|
||||
assert!(reach(3.0) < 2.0 + 1e-3 && reach(4.0) < 2.0 + 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashes_follow_curves_by_arc_length() {
|
||||
// A circle of radius 50 flattened finely, dashed 10 on, 10 off from its start.
|
||||
let r = 50.0f32;
|
||||
let ring: Vec<(f32, f32)> = (0..720)
|
||||
.map(|i| {
|
||||
let a = i as f32 / 720.0 * std::f32::consts::TAU;
|
||||
(r * a.cos(), r * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let pattern = [10.0, 10.0];
|
||||
let o = Outline { dash: Some((&pattern, 0.0)), ..outline(Cap::Butt, Join::Round) };
|
||||
let polys = styled(&ring, true, 1.5, &o);
|
||||
let on_ring = |s: f32| Vec2::new(r * (s / r).cos(), r * (s / r).sin());
|
||||
for k in 0..15 {
|
||||
let s = k as f32 * 20.0;
|
||||
assert!(covered(&polys, on_ring(s + 5.0)), "dash {k} is drawn at arc length {}", s + 5.0);
|
||||
assert!(!covered(&polys, on_ring(s + 15.0)), "gap {k} is empty at arc length {}", s + 15.0);
|
||||
assert!(covered(&polys, on_ring(s + 0.3)) && !covered(&polys, on_ring(s + 10.3)), "dash {k} runs from {s} to {}", s + 10.0);
|
||||
}
|
||||
// The offset moves the pattern along: 5 in, the first dash is half gone.
|
||||
let o = Outline { dash: Some((&pattern, 5.0)), ..o };
|
||||
let shifted = styled(&ring, true, 1.5, &o);
|
||||
assert!(covered(&shifted, on_ring(2.0)) && !covered(&shifted, on_ring(7.0)) && covered(&shifted, on_ring(17.0)));
|
||||
// Butt-capped dashes: about the on share of the ring's area (π((r+w)² − (r−w)²)).
|
||||
let ring_area = std::f32::consts::PI * ((r + 1.5).powi(2) - (r - 1.5).powi(2));
|
||||
assert!((area(&polys) - ring_area * 0.5).abs() < 0.03 * ring_area, "{} vs {}", area(&polys), ring_area * 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_intervals_walk_the_pattern() {
|
||||
let mut budget = 100;
|
||||
assert_eq!(dash_intervals(&[3.0, 2.0], 0.0, 12.0, &mut budget), vec![(0.0, 3.0), (5.0, 8.0), (10.0, 12.0)]);
|
||||
assert_eq!(dash_intervals(&[3.0, 2.0], 4.0, 6.0, &mut budget), vec![(1.0, 4.0)]);
|
||||
assert_eq!(dash_intervals(&[3.0, 2.0], -1.0, 6.0, &mut budget), vec![(1.0, 4.0)], "a negative offset counts back from the end of the period");
|
||||
// Dots: zero-length dashes, the last one on the very end.
|
||||
assert_eq!(dash_intervals(&[0.0, 5.0], 0.0, 10.0, &mut budget), vec![(0.0, 0.0), (5.0, 5.0), (10.0, 10.0)]);
|
||||
// The budget bounds the walk; the rest is one stretch.
|
||||
let mut small = 2;
|
||||
assert_eq!(dash_intervals(&[1.0, 1.0], 0.0, 1e9, &mut small), vec![(0.0, 1.0), (2.0, 3.0), (4.0, 1e9)]);
|
||||
assert!(dash_intervals(&[1.0, 1.0], f32::NAN, f32::INFINITY, &mut budget).is_empty());
|
||||
assert!(dash_intervals(&[0.0, 0.0], 0.0, 5.0, &mut budget).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashes_keep_the_width_profile_of_their_place() {
|
||||
let line = Polyline { points: vec![Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)], closed: false };
|
||||
let taper = anicraft_doc::ProfilePreset::TaperBoth.profile().unwrap();
|
||||
let pattern = [10.0, 10.0];
|
||||
let o = Outline { dash: Some((&pattern, 0.0)), ..outline(Cap::Butt, Join::Round) };
|
||||
let polys = styled_polygons(std::slice::from_ref(&line), 5.0, &o, Some(&taper), None, false);
|
||||
assert!(polys.iter().all(|p| signed_area(p) >= 0.0));
|
||||
// In the dash from 40 to 50 the half-width is the profile's there; 50..60 is a gap.
|
||||
for x in [42.0f32, 45.0, 48.0] {
|
||||
let want = taper.at(x / 100.0).0 * 5.0;
|
||||
assert!(covered(&polys, Vec2::new(x, -(want - 0.1))) && !covered(&polys, Vec2::new(x, -(want + 0.1))), "half-width {want} at {x}");
|
||||
}
|
||||
assert!(!covered(&polys, Vec2::new(55.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dots_are_discs_one_width_across() {
|
||||
let pattern = [0.0, 10.0];
|
||||
let o = Outline { dash: Some((&pattern, 0.0)), ..outline(Cap::Round, Join::Round) };
|
||||
let line = [(0.0, 0.0), (100.0, 0.0)];
|
||||
let polys = styled(&line, false, 2.0, &o);
|
||||
// Eleven dots (0, 10, … 100), each two half discs of radius 2.
|
||||
assert_eq!(polys.len(), 22);
|
||||
let want = 11.0 * std::f32::consts::PI * 4.0;
|
||||
assert!((area(&polys) - want).abs() < 0.08 * want, "within the arc tolerance: {} vs {want}", area(&polys));
|
||||
assert!(covered(&polys, Vec2::new(30.0, 1.5)) && !covered(&polys, Vec2::new(35.0, 0.0)));
|
||||
// Butt-capped dots draw nothing; square ones are squares.
|
||||
let o = Outline { cap: Cap::Butt, ..o };
|
||||
assert!(styled(&line, false, 2.0, &o).is_empty());
|
||||
let o = Outline { cap: Cap::Square, ..o };
|
||||
assert!((area(&styled(&line, false, 2.0, &o)) - 11.0 * 16.0).abs() < 1e-2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_solid_strokes_take_the_old_paths_exactly() {
|
||||
let pl = Polyline { points: vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0)], closed: false };
|
||||
assert_eq!(styled_polygons(std::slice::from_ref(&pl), 2.0, &Outline::ROUND, None, None, false), stroke_polygons(std::slice::from_ref(&pl), 2.0));
|
||||
let taper = anicraft_doc::ProfilePreset::TaperEnd.profile().unwrap();
|
||||
assert_eq!(styled_polygons(std::slice::from_ref(&pl), 2.0, &Outline::ROUND, Some(&taper), None, false), variable_polygons(&[pl], 2.0, &taper, None, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styled_degenerate_inputs_are_safe() {
|
||||
let pattern = [1.0, 1.0];
|
||||
for o in [outline(Cap::Square, Join::Miter), Outline { dash: Some((&pattern, 0.0)), ..outline(Cap::Butt, Join::Bevel) }] {
|
||||
assert!(styled_polygons(&[], 1.0, &o, None, None, false).is_empty());
|
||||
for pts in [vec![Vec2::ZERO; 3], vec![Vec2::ZERO, Vec2::new(f32::NAN, 1.0), Vec2::new(5.0, 0.0), Vec2::new(5.0, 0.0), Vec2::ZERO], vec![Vec2::ZERO, Vec2::new(1e30, 0.0), Vec2::new(-1e30, 0.0)]] {
|
||||
for closed in [false, true] {
|
||||
let polys = styled_polygons(&[Polyline { points: pts.clone(), closed }], 1.0, &o, None, None, false);
|
||||
assert!(polys.iter().flatten().all(|q| q.is_finite()));
|
||||
}
|
||||
}
|
||||
assert!(styled_polygons(&[Polyline { points: vec![Vec2::ZERO, Vec2::new(5.0, 0.0)], closed: false }], f32::NAN, &o, None, None, false).is_empty());
|
||||
}
|
||||
// A U-turn with a miter join: bevelled, never a point at infinity.
|
||||
let polys = styled(&[(0.0, 0.0), (10.0, 0.0), (0.0, 0.0)], false, 1.0, &outline(Cap::Butt, Join::Miter));
|
||||
assert!(polys.iter().flatten().all(|q| q.length() < 20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fine_patterns_draw_solid_and_lighter_on_raster() {
|
||||
// A 0.2-unit pattern at 1:1 is finer than a pixel: solid, at the share that is on.
|
||||
let st = anicraft_doc::Stroke::new(anicraft_doc::Rgba::BLACK, 4.0).with_style(anicraft_doc::StrokeStyle { cap: Cap::Butt, dash: anicraft_doc::Dash::dashed(0.05, 0.15), ..Default::default() });
|
||||
let lines = [Polyline { points: vec![Vec2::ZERO, Vec2::new(50.0, 0.0)], closed: false }];
|
||||
let (polys, alpha) = stroke_geometry(&lines, &st, &Affine::IDENTITY, true).unwrap();
|
||||
assert_eq!(polys.len(), 1);
|
||||
assert!((alpha - 0.25).abs() < 1e-4, "{alpha}");
|
||||
// Vector outlines keep every dash.
|
||||
let (exact, a) = stroke_geometry(&lines, &st, &Affine::IDENTITY, false).unwrap();
|
||||
assert_eq!((exact.len(), a), (250, 1.0));
|
||||
// Zoomed in 10×, the pattern is two pixels: real dashes, and their lengths scale.
|
||||
let (zoomed, a) = stroke_geometry(&[Polyline { points: vec![Vec2::ZERO, Vec2::new(500.0, 0.0)], closed: false }], &st, &Affine::scale(10.0, 10.0), true).unwrap();
|
||||
assert_eq!((zoomed.len(), a), (250, 1.0));
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
//!
|
||||
//! It draws what the CPU renderer draws, from the same evaluated frame:
|
||||
//! * paths are written in stage space, and strokes get the same stage-space width
|
||||
//! (`width × mean scale`, round joins and caps);
|
||||
//! (`width × mean scale`) with their caps, joins and miter limit, and dashes scaled the same
|
||||
//! way (`stroke-dasharray`, `stroke-dashoffset`; dots are zero-length round-capped dashes),
|
||||
//! as the renderer measures them (ADR 0046);
|
||||
//! * gradients keep their local geometry under a `gradientTransform`, padded at the ends;
|
||||
//! * colour effects (alpha, tint) are baked into every colour and stop;
|
||||
//! * masks become `clipPath`s (fill areas only, nested through `clip-path` on the clip), and an
|
||||
@@ -90,9 +92,10 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String {
|
||||
let c = item.color.apply(st.color);
|
||||
let _ = write!(
|
||||
body,
|
||||
"<path d=\"{d}\" fill=\"none\"{} stroke-width=\"{}\" stroke-linejoin=\"round\" stroke-linecap=\"round\"{clip}/>",
|
||||
"<path d=\"{d}\" fill=\"none\"{} stroke-width=\"{}\"{}{clip}/>",
|
||||
color_attrs("stroke", c),
|
||||
num(width)
|
||||
num(width),
|
||||
style_attrs(st, item.transform.mean_scale())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -142,6 +145,25 @@ fn num(v: f32) -> String {
|
||||
if r == 0.0 { "0".into() } else { format!("{r}") }
|
||||
}
|
||||
|
||||
/// A stroke's join, cap, miter limit and dashes as SVG attributes (dash lengths scaled by `k`,
|
||||
/// like the width). The default style writes `stroke-linejoin="round" stroke-linecap="round"`.
|
||||
fn style_attrs(st: &anicraft_doc::Stroke, k: f32) -> String {
|
||||
let style = &st.style;
|
||||
let mut out = format!(" stroke-linejoin=\"{}\" stroke-linecap=\"{}\"", style.join.key(), style.effective_cap().key());
|
||||
if style.join == anicraft_doc::Join::Miter {
|
||||
let _ = write!(out, " stroke-miterlimit=\"{}\"", num(style.miter_limit));
|
||||
}
|
||||
if let Some(dash) = &style.dash {
|
||||
let (lengths, offset) = dash.pattern(st.width);
|
||||
let list: Vec<String> = lengths.iter().map(|l| num(l * k)).collect();
|
||||
let _ = write!(out, " stroke-dasharray=\"{}\"", list.join(" "));
|
||||
if num(offset * k) != "0" {
|
||||
let _ = write!(out, " stroke-dashoffset=\"{}\"", num(offset * k));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn hex(c: Rgba) -> String {
|
||||
c.sanitized().to_hex()
|
||||
}
|
||||
@@ -435,6 +457,29 @@ mod tests {
|
||||
assert!(svg.trim_end().ends_with("</svg>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_caps_joins_and_dashes_are_written_scaled() {
|
||||
use anicraft_doc::{Cap, Dash, Join, StrokeStyle};
|
||||
let svg_of = |st: Stroke| {
|
||||
let mut a = item(Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), None);
|
||||
a.transform = Affine::scale(2.0, 2.0);
|
||||
a.stroke = Some(st);
|
||||
to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage())
|
||||
};
|
||||
// The default style is written as before: round, no dashes.
|
||||
let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0));
|
||||
assert!(svg.contains("stroke-width=\"6\" stroke-linejoin=\"round\" stroke-linecap=\"round\"/>"), "{svg}");
|
||||
assert!(!svg.contains("dasharray") && !svg.contains("miterlimit"));
|
||||
// Dashes, offset and the miter limit; lengths scale with the shape, like the width.
|
||||
let dashed = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 6.0, dash: Some(Dash::Dashed { lengths: vec![4.0, 1.5].into(), offset: 1.0 }) };
|
||||
let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0).with_style(dashed));
|
||||
assert!(svg.contains("stroke-linejoin=\"miter\" stroke-linecap=\"butt\" stroke-miterlimit=\"6\" stroke-dasharray=\"8 3\" stroke-dashoffset=\"2\"/>"), "{svg}");
|
||||
// Dots: zero-length round dashes one width plus the spacing apart.
|
||||
let dotted = StrokeStyle { cap: Cap::Square, join: Join::Bevel, dash: Dash::dotted(2.0), ..StrokeStyle::default() };
|
||||
let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0).with_style(dotted));
|
||||
assert!(svg.contains("stroke-linejoin=\"bevel\" stroke-linecap=\"round\" stroke-dasharray=\"0 10\"/>"), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_width_strokes_are_written_as_filled_outlines() {
|
||||
let mut a = item(Path::line(Vec2::new(0.0, 10.0), Vec2::new(80.0, 10.0)), Some(Paint::Solid(Rgba::hex(0xff0000))));
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
//! * consecutive items with the same mask share one masked layer under one mask layer.
|
||||
|
||||
use crate::{Builder, ImportedElement, ImportedLayer, ImportedMask, Item, PaintSpec, Report, Style, declarations, get, hidden, length, local, name_of, paint_spec, transform};
|
||||
use anicraft_doc::{ElementKind, Paint, Rgba, Shape};
|
||||
use anicraft_doc::{ElementKind, Paint, Rgba, Shape, Stroke};
|
||||
use anicraft_geom::clip::{clip_convex, convex_polygon};
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
|
||||
use anicraft_xml::Element as X;
|
||||
@@ -40,7 +40,7 @@ pub(crate) struct Region {
|
||||
/// Conservative drawing-space bounds of an element's artwork.
|
||||
fn element_bounds(e: &ImportedElement) -> Rect {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(s) => s.path.bounds().inflate(s.stroke.as_ref().map_or(0.0, |st| st.width * 0.5)).transformed(&e.transform),
|
||||
ElementKind::Shape(s) => s.path.bounds().inflate(s.stroke.as_ref().map_or(0.0, Stroke::reach)).transformed(&e.transform),
|
||||
ElementKind::Text(t) => t.outline.bounds().union(&Rect::new(0.0, 0.0, t.box_width.max(0.0), t.box_height.max(0.0))).transformed(&e.transform),
|
||||
ElementKind::Symbol { .. } | ElementKind::Camera => Rect::EMPTY,
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
//! and `polygon`, read in document order. Styling comes from presentation attributes and
|
||||
//! `style=""` declarations, with inheritance. Colours can be hex, `rgb()`/`rgba()`, CSS names,
|
||||
//! `none`, `transparent` or `currentColor`. Also supported: `opacity`, `fill-opacity` and
|
||||
//! `stroke-opacity`, `fill-rule`, `stroke-width` with units, the transform list (`matrix`,
|
||||
//! `stroke-opacity`, `fill-rule`, `stroke-width` with units, `stroke-linecap`,
|
||||
//! `stroke-linejoin`, `stroke-miterlimit`, `stroke-dasharray` and `stroke-dashoffset` (ADR 0046;
|
||||
//! SVG's defaults: butt caps, miter joins, limit 4), the transform list (`matrix`,
|
||||
//! `translate`, `scale`, `rotate`, `skewX`, `skewY`), `viewBox` with `preserveAspectRatio`, and
|
||||
//! linear and radial gradients (both unit systems, `gradientTransform`, stops inherited through
|
||||
//! `href`).
|
||||
@@ -20,11 +22,11 @@
|
||||
//! (ADR 0014).
|
||||
//!
|
||||
//! What AniCraft cannot represent yet is reported, never guessed silently: images, filters,
|
||||
//! soft masks, patterns, dashes, style sheets, text on a path, reflected/repeated gradients and
|
||||
//! soft masks, patterns, style sheets, text on a path, reflected/repeated gradients and
|
||||
//! skewed gradient transforms (approximated).
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use anicraft_doc::{ElementKind, GradientStop, Paint, Rgba, Shape, Stroke};
|
||||
use anicraft_doc::{Cap, Dash, ElementKind, GradientStop, Join, Paint, Rgba, Shape, Stroke, StrokeStyle};
|
||||
use anicraft_geom::svg::parse_path_data;
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
|
||||
use anicraft_text::{FaceMatch, Fonts};
|
||||
@@ -467,6 +469,12 @@ struct Style {
|
||||
stroke: PaintSpec,
|
||||
stroke_opacity: f32,
|
||||
stroke_width: f32,
|
||||
cap: Cap,
|
||||
join: Join,
|
||||
miter_limit: f32,
|
||||
/// `stroke-dasharray` lengths (user units); `None`: solid.
|
||||
dash: Option<Vec<f32>>,
|
||||
dash_offset: f32,
|
||||
current: Rgba,
|
||||
/// The CSS `font-family` list, as written.
|
||||
font_family: String,
|
||||
@@ -489,6 +497,12 @@ impl Default for Style {
|
||||
stroke: PaintSpec::None,
|
||||
stroke_opacity: 1.0,
|
||||
stroke_width: 1.0,
|
||||
// SVG's initial values, not AniCraft's (round) defaults.
|
||||
cap: Cap::Butt,
|
||||
join: Join::Miter,
|
||||
miter_limit: 4.0,
|
||||
dash: None,
|
||||
dash_offset: 0.0,
|
||||
current: Rgba::BLACK,
|
||||
font_family: String::new(),
|
||||
font_size: 16.0,
|
||||
@@ -511,7 +525,11 @@ fn declarations(el: &X) -> Vec<(String, String)> {
|
||||
"stroke",
|
||||
"stroke-opacity",
|
||||
"stroke-width",
|
||||
"stroke-linecap",
|
||||
"stroke-linejoin",
|
||||
"stroke-miterlimit",
|
||||
"stroke-dasharray",
|
||||
"stroke-dashoffset",
|
||||
"color",
|
||||
"opacity",
|
||||
"display",
|
||||
@@ -544,6 +562,23 @@ fn declarations(el: &X) -> Vec<(String, String)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A `stroke-dasharray`: lengths separated by commas or spaces. `none`, an empty list, a
|
||||
/// negative or unreadable length all draw solid (SVG renders an invalid array as none).
|
||||
fn dash_array(v: &str) -> Option<Vec<f32>> {
|
||||
if v.trim() == "none" {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for part in v.split(|c: char| c == ',' || c.is_whitespace()).filter(|p| !p.trim().is_empty()).take(1024) {
|
||||
let x = length(part, 100.0)?;
|
||||
if x < 0.0 {
|
||||
return None;
|
||||
}
|
||||
out.push(x);
|
||||
}
|
||||
(!out.is_empty()).then_some(out)
|
||||
}
|
||||
|
||||
fn get<'a>(d: &'a [(String, String)], key: &str) -> Option<&'a str> {
|
||||
d.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
|
||||
}
|
||||
@@ -649,8 +684,29 @@ impl Style {
|
||||
Some("default") => s.preserve = false,
|
||||
_ => {}
|
||||
}
|
||||
if get(&d, "stroke-dasharray").is_some_and(|v| v != "none") {
|
||||
report.skip("dashed strokes (drawn solid)");
|
||||
match get(&d, "stroke-linecap") {
|
||||
Some("butt") => s.cap = Cap::Butt,
|
||||
Some("round") => s.cap = Cap::Round,
|
||||
Some("square") => s.cap = Cap::Square,
|
||||
_ => {}
|
||||
}
|
||||
match get(&d, "stroke-linejoin") {
|
||||
Some("miter" | "miter-clip") => s.join = Join::Miter,
|
||||
Some("round" | "arcs") => s.join = Join::Round,
|
||||
Some("bevel") => s.join = Join::Bevel,
|
||||
_ => {}
|
||||
}
|
||||
if let Some(m) = get(&d, "stroke-miterlimit").and_then(|v| v.trim().parse::<f32>().ok()).filter(|m| m.is_finite() && *m >= 1.0) {
|
||||
s.miter_limit = m;
|
||||
}
|
||||
if let Some(v) = get(&d, "stroke-dasharray").filter(|v| *v != "inherit") {
|
||||
s.dash = dash_array(v);
|
||||
if s.dash.as_ref().is_some_and(|l| l.len() > anicraft_doc::stroke_style::MAX_DASH_ENTRIES) {
|
||||
report.skip("dash patterns of more than 16 lengths (shortened)");
|
||||
}
|
||||
}
|
||||
if let Some(o) = get(&d, "stroke-dashoffset").and_then(|v| length(v, 100.0)) {
|
||||
s.dash_offset = o;
|
||||
}
|
||||
if get(&d, "filter").is_some_and(|v| v != "none") {
|
||||
report.skip("filters");
|
||||
@@ -879,7 +935,8 @@ impl<'a> Builder<'a> {
|
||||
other.primary_color()
|
||||
}
|
||||
};
|
||||
Some(Stroke::new(color, style.stroke_width))
|
||||
let dash = style.dash.as_ref().and_then(|l| Dash::Dashed { lengths: l.iter().copied().collect(), offset: style.dash_offset }.sanitized());
|
||||
Some(Stroke::new(color, style.stroke_width).with_style(StrokeStyle { cap: style.cap, join: style.join, miter_limit: style.miter_limit, dash }))
|
||||
}
|
||||
|
||||
/// A fill or stroke paint, with `opacity` folded in; `None` draws nothing.
|
||||
|
||||
@@ -57,7 +57,9 @@ fn shapes_styles_and_inheritance() {
|
||||
let r = &i.shapes[0];
|
||||
assert_eq!(r.name, "box");
|
||||
assert_eq!(solid(r), Rgba::hex(0xff0000));
|
||||
assert_eq!(r.shape.stroke, Some(Stroke::new(Rgba::hex(0x0000ff), 4.0)));
|
||||
// SVG's initial stroke style: butt caps, miter joins, a miter limit of 4.
|
||||
let svg_style = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 4.0, dash: None };
|
||||
assert_eq!(r.shape.stroke, Some(Stroke::new(Rgba::hex(0x0000ff), 4.0).with_style(svg_style)));
|
||||
assert_eq!(r.alpha, 0.5, "group opacity reaches every child");
|
||||
assert_eq!(r.shape.path.bounds(), Rect::new(10.0, 10.0, 60.0, 40.0));
|
||||
let c = &i.shapes[1];
|
||||
@@ -147,12 +149,52 @@ fn use_references_and_reported_leftovers() {
|
||||
assert_eq!(first.transform.apply(Vec2::new(0.0, 0.0)), Vec2::new(10.0, 20.0));
|
||||
assert_eq!(solid(first), Rgba::hex(0x123456));
|
||||
assert_eq!(i.shapes.len(), 4, "the dot, the symbol's two rects and the plain rect");
|
||||
for k in ["text (no fonts on this computer)", "images", "references to missing elements", "dashed strokes (drawn solid)", "filters", "references to missing clip paths (drawn unclipped)", "style sheets (inline styles are read)"] {
|
||||
for k in ["text (no fonts on this computer)", "images", "references to missing elements", "filters", "references to missing clip paths (drawn unclipped)", "style sheets (inline styles are read)"] {
|
||||
assert_eq!(i.report.skipped.get(k), Some(&1), "{k}: {:?}", i.report);
|
||||
}
|
||||
assert!(i.report.summary().starts_with("Imported. Not yet supported: "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_caps_joins_and_dashes() {
|
||||
let i = imp(r##"<svg width="200" height="100">
|
||||
<g stroke="#000" stroke-linecap="round" stroke-linejoin="bevel" stroke-dasharray="6, 3" stroke-dashoffset="2">
|
||||
<line id="inherits" x1="0" y1="0" x2="100" y2="0"/>
|
||||
<line id="own" x1="0" y1="0" x2="100" y2="0" style="stroke-linecap: square; stroke-linejoin: miter-clip; stroke-miterlimit: 8; stroke-dasharray: 1pt 2 3"/>
|
||||
<line id="none" x1="0" y1="0" x2="100" y2="0" stroke-dasharray="none" stroke-linejoin="arcs"/>
|
||||
<line id="negative" x1="0" y1="0" x2="100" y2="0" stroke-dasharray="4 -1"/>
|
||||
<line id="junk" x1="0" y1="0" x2="100" y2="0" stroke-dasharray="4 wide" stroke-miterlimit="0.5" stroke-linecap="fancy"/>
|
||||
<line id="no-gaps" x1="0" y1="0" x2="100" y2="0" stroke-dasharray="0 0"/>
|
||||
</g>
|
||||
<line id="plain" x1="0" y1="0" x2="100" y2="0" stroke="#000"/>
|
||||
</svg>"##);
|
||||
let st = |name: &str| i.shapes.iter().find(|s| s.name == name).and_then(|s| s.shape.stroke.clone()).map(|s| s.style).unwrap();
|
||||
assert_eq!(st("inherits"), StrokeStyle { cap: Cap::Round, join: Join::Bevel, miter_limit: 4.0, dash: Some(Dash::Dashed { lengths: vec![6.0, 3.0].into(), offset: 2.0 }) });
|
||||
// style= wins; an odd list repeats; units convert; the offset is inherited.
|
||||
let own = st("own");
|
||||
assert_eq!((own.cap, own.join, own.miter_limit), (Cap::Square, Join::Miter, 8.0));
|
||||
let pt = 96.0 / 72.0;
|
||||
assert_eq!(own.dash, Some(Dash::Dashed { lengths: vec![pt, 2.0, 3.0, pt, 2.0, 3.0].into(), offset: 2.0 }));
|
||||
assert_eq!((st("none").dash, st("none").join), (None, Join::Round));
|
||||
// Invalid arrays draw solid (as SVG renders them); unknown values keep the inherited ones.
|
||||
assert_eq!(st("negative").dash, None);
|
||||
let junk = st("junk");
|
||||
assert_eq!((junk.dash, junk.miter_limit, junk.cap), (None, 4.0, Cap::Round));
|
||||
assert_eq!(st("no-gaps").dash, None);
|
||||
assert_eq!(st("plain"), StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 4.0, dash: None });
|
||||
assert!(i.report.skipped.is_empty(), "{:?}", i.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_lists() {
|
||||
assert_eq!(dash_array("5,3 2"), Some(vec![5.0, 3.0, 2.0]));
|
||||
assert_eq!(dash_array(" 10% , 1in "), Some(vec![10.0, 96.0]));
|
||||
assert_eq!(dash_array("none"), None);
|
||||
assert_eq!(dash_array(""), None);
|
||||
assert_eq!(dash_array("1 -2"), None);
|
||||
assert_eq!(dash_array("1 nan"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours() {
|
||||
assert_eq!(color("#f00"), Some(Rgba::hex(0xff0000)));
|
||||
|
||||
@@ -3,23 +3,25 @@
|
||||
//! What maps (first slice of M4): stage size, frame rate and colour; the first scene's
|
||||
//! layers (name, colour, visibility, lock, outline; guide layers; folders flattened); frames
|
||||
//! and keyframes with durations, labels and classic tweens with their ease; shapes (solid,
|
||||
//! linear and radial fills, solid strokes), groups (flattened), rectangle and oval
|
||||
//! linear and radial fills, solid, dashed and dotted strokes with their caps, joints and
|
||||
//! miter limit), groups (flattened), rectangle and oval
|
||||
//! primitives; symbol instances with their matrix, alpha and tint, loop mode and first frame;
|
||||
//! library symbols (graphic, movie clip, button) with their own timelines, nested to any
|
||||
//! depth; bitmaps (library items, instances and bitmap fills) whose image is stored as PNG or
|
||||
//! JPEG in the package; text fields, laid out with this computer's fonts (`text`, ADR 0014);
|
||||
//! frame scripts, symbol linkage classes and the document class, kept verbatim and not run
|
||||
//! (ADR 0013 tier 1; the report lists them as kept).
|
||||
//! frame scripts, symbol linkage classes and the document class, kept verbatim (ADR 0013 tier
|
||||
//! 1); frame scripts in the ActionScript 3.0 subset run in Test Movie (tier 2), and the report
|
||||
//! lists which run and which are only kept.
|
||||
//! Everything else (sound, motion tweens with property curves, unknown filters,
|
||||
//! bitmaps kept only in Animate's own storage) is counted in the report instead of guessed at,
|
||||
//! and so is whatever is drawn the nearest way AniCraft can (square caps, reflecting
|
||||
//! gradients, advanced colour effects, …). The self-authored corpus in `tests/corpus/` covers
|
||||
//! and so is whatever is drawn the nearest way AniCraft can (ragged, stipple and hatched
|
||||
//! strokes, reflecting gradients, advanced colour effects, …). The self-authored corpus in `tests/corpus/` covers
|
||||
//! every feature listed here, with golden renders (ADR 0035).
|
||||
|
||||
use crate::edges::{self, Edge};
|
||||
use crate::xml::{self, Element as X};
|
||||
use anicraft_doc::{
|
||||
Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId,
|
||||
Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId,
|
||||
Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, Language, Linkage, SourceScript,
|
||||
};
|
||||
use anicraft_geom::{Affine, FillRule, Path, Vec2};
|
||||
@@ -47,13 +49,16 @@ pub enum XflError {
|
||||
NotXfl(String),
|
||||
}
|
||||
|
||||
/// What the import couldn't bring across, by kind ("3 bitmaps"), what it kept without
|
||||
/// running (scripts), and the fonts it couldn't find.
|
||||
/// What the import couldn't bring across, by kind ("3 bitmaps"), the scripts it brought that
|
||||
/// run and those it kept without running, and the fonts it couldn't find.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Report {
|
||||
pub skipped: BTreeMap<String, usize>,
|
||||
/// Kept in the document but not run, by kind ("2 frame scripts in ActionScript 3.0"; ADR
|
||||
/// 0013 tier 1).
|
||||
/// Frame scripts in the ActionScript 3.0 subset, which run in Test Movie and the HTML
|
||||
/// canvas export ("2 frame scripts in ActionScript 3.0"; ADR 0013 tier 2).
|
||||
pub runs: BTreeMap<String, usize>,
|
||||
/// Kept in the document but not run, by kind ("2 frame scripts in ActionScript 3.0", for
|
||||
/// those outside the subset; ADR 0013 tier 1).
|
||||
pub kept: BTreeMap<String, usize>,
|
||||
pub notes: Vec<String>,
|
||||
/// Font families the document's text asks for that aren't on this computer.
|
||||
@@ -69,16 +74,21 @@ impl Report {
|
||||
pub(crate) fn keep(&mut self, what: &str) {
|
||||
*self.kept.entry(what.to_string()).or_default() += 1;
|
||||
}
|
||||
/// One line for a status bar: "Imported. Kept, not run: 3 frame scripts in ActionScript
|
||||
/// 3.0. Not yet supported: 2 sounds. Fonts not on this computer, drawn in Inter: Futura,
|
||||
/// Gotham."
|
||||
pub(crate) fn run(&mut self, what: &str) {
|
||||
*self.runs.entry(what.to_string()).or_default() += 1;
|
||||
}
|
||||
/// One line for a status bar: "Imported. Runs in Test Movie: 2 frame scripts in
|
||||
/// ActionScript 3.0. Kept, not run: 1 frame scripts in ActionScript 3.0. Not yet supported:
|
||||
/// 2 sounds. Fonts not on this computer, drawn in Inter: Futura, Gotham."
|
||||
pub fn summary(&self) -> String {
|
||||
let kept = if self.kept.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
let parts: Vec<String> = self.kept.iter().map(|(k, n)| format!("{n} {k}")).collect();
|
||||
format!(" Kept, not run: {}.", parts.join(", "))
|
||||
};
|
||||
let list = |m: &BTreeMap<String, usize>| m.iter().map(|(k, n)| format!("{n} {k}")).collect::<Vec<String>>().join(", ");
|
||||
let mut kept = String::new();
|
||||
if !self.runs.is_empty() {
|
||||
kept.push_str(&format!(" Runs in Test Movie: {}.", list(&self.runs)));
|
||||
}
|
||||
if !self.kept.is_empty() {
|
||||
kept.push_str(&format!(" Kept, not run: {}.", list(&self.kept)));
|
||||
}
|
||||
if self.skipped.is_empty() && self.notes.is_empty() && self.missing_fonts.is_empty() {
|
||||
return format!("Imported everything in the file.{kept}");
|
||||
}
|
||||
@@ -215,19 +225,35 @@ fn paint(def: &X, bitmaps: &HashMap<String, BitmapId>, report: &mut Report) -> O
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke definition (`SolidStroke` and friends) as a stroke: weight and its fill colour.
|
||||
fn stroke(def: &X, bitmaps: &HashMap<String, BitmapId>, report: &mut Report) -> Option<Stroke> {
|
||||
/// A stroke definition (`SolidStroke` and friends) as a stroke: weight, its fill colour, caps,
|
||||
/// joints and miter limit, and the dashes of `DashedStroke` and dots of `DottedStroke`
|
||||
/// (ADR 0046). Ragged, stipple and hatched strokes are drawn solid.
|
||||
pub(crate) fn stroke(def: &X, bitmaps: &HashMap<String, BitmapId>, report: &mut Report) -> Option<Stroke> {
|
||||
if !matches!(def.name.as_str(), "SolidStroke" | "DashedStroke" | "DottedStroke" | "RaggedStroke" | "StippleStroke" | "HatchedStroke") {
|
||||
return None;
|
||||
}
|
||||
if def.name != "SolidStroke" {
|
||||
report.skip("stroke styles drawn as solid");
|
||||
}
|
||||
// AniCraft strokes have round caps and joins (the format's default).
|
||||
let round = |k: &str| def.attr(k).is_none_or(|v| v.trim() == "round");
|
||||
if !round("caps") || !round("joints") {
|
||||
report.skip("stroke caps and joins other than round (drawn round)");
|
||||
}
|
||||
// Round caps and joints are the format's default, and a miter limit of 3.
|
||||
let cap = match def.attr("caps").map(str::trim) {
|
||||
Some("none") => Cap::Butt,
|
||||
Some("square") => Cap::Square,
|
||||
_ => Cap::Round,
|
||||
};
|
||||
let join = match def.attr("joints").map(str::trim) {
|
||||
Some("miter") => Join::Miter,
|
||||
Some("bevel") => Join::Bevel,
|
||||
_ => Join::Round,
|
||||
};
|
||||
let miter_limit = def.f32("miterLimit").unwrap_or(anicraft_doc::stroke_style::DEFAULT_MITER_LIMIT);
|
||||
let dash = match def.name.as_str() {
|
||||
"DashedStroke" => Dash::dashed(def.f32("dash1").unwrap_or(6.0), def.f32("dash2").unwrap_or(3.0)),
|
||||
"DottedStroke" => Dash::dotted(def.f32("dotSpace").unwrap_or(3.0)),
|
||||
"SolidStroke" => None,
|
||||
_ => {
|
||||
report.skip("ragged, stipple and hatched strokes (drawn solid)");
|
||||
None
|
||||
}
|
||||
};
|
||||
let style = StrokeStyle { cap, join, miter_limit, dash };
|
||||
let width = def.f32("weight").unwrap_or(1.0).clamp(0.05, 1000.0);
|
||||
let fill = def.child("fill").and_then(|f| f.children.first());
|
||||
let c = fill.map_or(Rgba::BLACK, |f| {
|
||||
@@ -238,7 +264,7 @@ fn stroke(def: &X, bitmaps: &HashMap<String, BitmapId>, report: &mut Report) ->
|
||||
paint(f, bitmaps, report).map_or(Rgba::BLACK, |p| p.primary_color())
|
||||
}
|
||||
});
|
||||
Some(Stroke::new(c, width))
|
||||
Some(Stroke::new(c, width).with_style(style))
|
||||
}
|
||||
|
||||
impl<'a> Builder<'a> {
|
||||
@@ -247,9 +273,12 @@ impl<'a> Builder<'a> {
|
||||
}
|
||||
|
||||
/// Shapes for one `DOMShape`: a fill-only shape per fill style (bottom), then a stroke-only
|
||||
/// shape per stroke style, as Animate draws them.
|
||||
fn shape(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
|
||||
/// shape per stroke style, as Animate draws them. A shape loose on a frame (not in a group,
|
||||
/// not a drawing object) is raw artwork: its shapes are marked to merge (ADR 0042), and the
|
||||
/// engine merges each keyframe's raw shapes into one drawing when it opens the file.
|
||||
fn shape(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>, loose: bool) {
|
||||
let m = parent.mul(&matrix(el));
|
||||
let merge = loose && !el.bool("isDrawingObject").unwrap_or(false);
|
||||
let fills: Vec<(u32, Option<Paint>)> = el.list("fills").iter().map(|f| (f.u32("index").unwrap_or(0), f.children.first().and_then(|d| paint(d, &self.bitmaps, &mut self.report)))).collect();
|
||||
let strokes: Vec<(u32, Option<Stroke>)> = el.list("strokes").iter().map(|s| (s.u32("index").unwrap_or(0), s.children.first().and_then(|d| stroke(d, &self.bitmaps, &mut self.report)))).collect();
|
||||
let edges: Vec<Edge> = el
|
||||
@@ -262,14 +291,14 @@ impl<'a> Builder<'a> {
|
||||
let (Some(p), true) = (p, index > 0) else { continue };
|
||||
let path = edges::fill_path(&edges, index);
|
||||
if !path.is_empty() {
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd, merge: false }), m, ColorEffect::default()));
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd, merge }), m, ColorEffect::default()));
|
||||
}
|
||||
}
|
||||
for (index, s) in strokes {
|
||||
let (Some(s), true) = (s, index > 0) else { continue };
|
||||
let path = edges::stroke_path(&edges, index);
|
||||
if !path.is_empty() {
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero, merge: false }), m, ColorEffect::default()));
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero, merge }), m, ColorEffect::default()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -443,7 +472,7 @@ impl<'a> Builder<'a> {
|
||||
}
|
||||
for el in list {
|
||||
match el.name.as_str() {
|
||||
"DOMShape" => self.shape(el, parent, out),
|
||||
"DOMShape" => self.shape(el, parent, out, depth == 0),
|
||||
"DOMGroup" => {
|
||||
let m = parent.mul(&matrix(el));
|
||||
self.elements(el.list("members"), &m, out, depth + 1);
|
||||
@@ -518,7 +547,7 @@ impl<'a> Builder<'a> {
|
||||
if let Some(h) = f.child("shapeHints").filter(|h| !h.children.is_empty()) {
|
||||
raw_hints.insert(start, self.raw_hints(h));
|
||||
}
|
||||
// Frame scripts are kept verbatim and not run (ADR 0013 tier 1).
|
||||
// Frame scripts are kept verbatim (ADR 0013 tier 1); those in the subset run.
|
||||
if let Some(a) = f.child("Actionscript") {
|
||||
k.script = self.frame_script(a);
|
||||
}
|
||||
@@ -558,7 +587,9 @@ impl<'a> Builder<'a> {
|
||||
self.report.skip("frame scripts over 1 MiB (left out)");
|
||||
return None;
|
||||
}
|
||||
self.report.keep(&format!("frame scripts in {}", self.language.label()));
|
||||
// Compiling here also fills the script's cache for Test Movie (ADR 0013 tier 2).
|
||||
let what = format!("frame scripts in {}", self.language.label());
|
||||
if script.runs() { self.report.run(&what) } else { self.report.keep(&what) }
|
||||
Some(FrameScript::Source(Arc::new(script)))
|
||||
}
|
||||
|
||||
|
||||
@@ -98,14 +98,15 @@ fn stage_layers_frames_and_tweens() {
|
||||
assert_eq!(report.skipped.get("instances of missing bitmaps"), Some(&1));
|
||||
assert_eq!(report.skipped.get("missing library files"), Some(&1));
|
||||
assert_eq!(report.skipped.get("unknown filters"), Some(&1));
|
||||
// Frame scripts, on the scene's frames and inside symbols, are kept verbatim, not run
|
||||
// (ADR 0013 tier 1).
|
||||
assert_eq!(report.kept.get("frame scripts in ActionScript 3.0"), Some(&2));
|
||||
// Frame scripts, on the scene's frames and inside symbols, are kept verbatim (ADR 0013
|
||||
// tier 1); these are in the subset that runs (tier 2).
|
||||
assert_eq!(report.runs.get("frame scripts in ActionScript 3.0"), Some(&2));
|
||||
assert!(report.kept.is_empty(), "{report:?}");
|
||||
assert!(report.skipped.keys().all(|k| !k.contains("script")), "{report:?}");
|
||||
assert_eq!(ball.keyframes[1].script.as_ref().and_then(|s| s.source()).map(|s| s.text.as_str()), Some("stop();"));
|
||||
let inner = &doc.library[0].timeline.layers[0].keyframes[0];
|
||||
assert!(matches!(inner.script.as_ref().and_then(|s| s.source()), Some(s) if s.text == "gotoAndPlay(2);" && s.language == anicraft_doc::Language::ActionScript3));
|
||||
assert!(report.summary().contains("Kept, not run: 2 frame scripts in ActionScript 3.0."), "{}", report.summary());
|
||||
assert!(report.summary().contains("Runs in Test Movie: 2 frame scripts in ActionScript 3.0."), "{}", report.summary());
|
||||
// Every scene comes across, in order.
|
||||
assert_eq!(doc.scenes.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Scene 1", "Scene 2"]);
|
||||
assert_eq!(doc.timeline(1).layers.len(), 1, "an empty scene gets a layer to draw on");
|
||||
@@ -435,3 +436,56 @@ trace(n);]]></script></Actionscript><elements><DOMSymbolInstance libraryItemName
|
||||
assert!(d.document_class.is_empty() && !report.kept.contains_key("document class"));
|
||||
assert!(report.kept.contains_key("frame scripts in ActionScript 3.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loose_shapes_come_in_raw_and_drawing_objects_and_groups_as_objects() {
|
||||
// Animate's raw shapes (merge drawing) are loose `DOMShape`s; a drawing object says so, and
|
||||
// a group is an object whatever it holds (ADR 0042).
|
||||
let square = |attrs: &str, x: u32| {
|
||||
format!(
|
||||
r##"<DOMShape {attrs}><fills><FillStyle index="1"><SolidColor color="#FF0000"/></FillStyle></fills><strokes><StrokeStyle index="1"><SolidStroke weight="2"><fill><SolidColor/></fill></SolidStroke></StrokeStyle></strokes>
|
||||
<edges><Edge fillStyle1="1" strokeStyle="1" edges="!{x} 0|{} 0|{} 2000|{x} 2000|{x} 0"/></edges></DOMShape>"##,
|
||||
x + 2000,
|
||||
x + 2000
|
||||
)
|
||||
};
|
||||
let doc = format!(
|
||||
r#"<DOMDocument width="400" height="100"><timelines><DOMTimeline name="Scene 1"><layers><DOMLayer name="Art"><frames><DOMFrame index="0"><elements>{}{}<DOMGroup><members>{}</members></DOMGroup></elements></DOMFrame></frames></DOMLayer></layers></DOMTimeline></timelines></DOMDocument>"#,
|
||||
square("", 0),
|
||||
square(r#"isDrawingObject="true""#, 4000),
|
||||
square("", 8000),
|
||||
);
|
||||
let doc: &'static str = Box::leak(doc.into_boxed_str());
|
||||
let (d, _) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap();
|
||||
let merge: Vec<bool> = d.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| matches!(&e.kind, ElementKind::Shape(s) if s.merge)).collect();
|
||||
// Each square is a fill and a stroke.
|
||||
assert_eq!(merge, [true, true, false, false, false, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_caps_joints_dashes_and_dots_come_across() {
|
||||
use anicraft_doc::{Cap, Dash, Join, StrokeStyle};
|
||||
let read = |xml: &str| {
|
||||
let el = crate::xml::parse(xml.as_bytes()).unwrap();
|
||||
let mut report = crate::Report::default();
|
||||
let st = crate::import::stroke(&el, &HashMap::new(), &mut report).unwrap();
|
||||
(st, report)
|
||||
};
|
||||
let (st, report) = read(r##"<SolidStroke weight="4" caps="none" joints="miter" miterLimit="7"><fill><SolidColor color="#112233"/></fill></SolidStroke>"##);
|
||||
assert_eq!((st.width, st.color), (4.0, Rgba::hex(0x112233)));
|
||||
assert_eq!(st.style, StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 7.0, dash: None });
|
||||
assert!(report.skipped.is_empty());
|
||||
// Round caps and joints and a miter limit of 3 are the format's defaults.
|
||||
assert_eq!(read(r#"<SolidStroke weight="1"/>"#).0.style, StrokeStyle::default());
|
||||
assert_eq!(read(r#"<SolidStroke caps="square" joints="bevel" miterLimit="1e9"/>"#).0.style, StrokeStyle { cap: Cap::Square, join: Join::Bevel, miter_limit: 100.0, dash: None });
|
||||
let (dashed, _) = read(r#"<DashedStroke weight="2" dash1="8" dash2="2.5" caps="square"/>"#);
|
||||
assert_eq!(dashed.style, StrokeStyle { cap: Cap::Square, dash: Dash::dashed(8.0, 2.5), ..StrokeStyle::default() });
|
||||
// No gap draws solid.
|
||||
assert_eq!(read(r#"<DashedStroke dash1="8" dash2="0"/>"#).0.style.dash, None);
|
||||
assert_eq!(read(r#"<DottedStroke weight="3" dotSpace="5"/>"#).0.style.dash, Dash::dotted(5.0));
|
||||
for kind in ["RaggedStroke", "StippleStroke", "HatchedStroke"] {
|
||||
let (st, report) = read(&format!("<{kind} weight=\"2\"/>"));
|
||||
assert_eq!(st.style.dash, None);
|
||||
assert_eq!(report.skipped.get("ragged, stipple and hatched strokes (drawn solid)"), Some(&1));
|
||||
}
|
||||
}
|
||||
@@ -67,11 +67,12 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[
|
||||
],
|
||||
),
|
||||
("guides", &[]),
|
||||
("interactive", &[]),
|
||||
("masks", &[]),
|
||||
("primitives", &[]),
|
||||
("scenes", &[("frame comments", 1)]),
|
||||
("scripts", &[]),
|
||||
("shapes", &[("stroke caps and joins other than round (drawn round)", 2)]),
|
||||
("shapes", &[]),
|
||||
(
|
||||
"symbols",
|
||||
&[("advanced colour effects (only alpha kept)", 1), ("instances of missing symbols", 1), ("missing library files", 1), ("reverse loop modes (played forward)", 1)],
|
||||
@@ -80,11 +81,15 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[
|
||||
("tweens", &[("motion tweens (kept as keyframes)", 1), ("tween spins (turned the shortest way)", 1)]),
|
||||
];
|
||||
|
||||
/// What each package keeps without running (ADR 0013 tier 1); packages not listed keep
|
||||
/// nothing.
|
||||
const KEPT: &[(&str, &[(&str, usize)])] = &[
|
||||
/// What each package keeps without running (ADR 0013 tier 1: scripts outside the subset, and
|
||||
/// class names); packages not listed keep nothing.
|
||||
const KEPT: &[(&str, &[(&str, usize)])] = &[("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)])];
|
||||
|
||||
/// The frame scripts each package brings that run (ADR 0013 tier 2: in the subset).
|
||||
const RUNS: &[(&str, &[(&str, usize)])] = &[
|
||||
("interactive", &[("frame scripts in ActionScript 3.0", 4)]),
|
||||
("scenes", &[("frame scripts in ActionScript 3.0", 2)]),
|
||||
("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 3), ("linkage classes", 1)]),
|
||||
("scripts", &[("frame scripts in ActionScript 3.0", 2)]),
|
||||
];
|
||||
|
||||
#[test]
|
||||
@@ -101,6 +106,8 @@ fn each_package_reports_exactly_what_it_uses_that_does_not_come_across() {
|
||||
assert_eq!(report.skipped, want, "{case}");
|
||||
let kept: BTreeMap<String, usize> = KEPT.iter().find(|(c, _)| c == case).map(|(_, k)| k.iter().map(|(k, n)| (k.to_string(), *n)).collect()).unwrap_or_default();
|
||||
assert_eq!(report.kept, kept, "{case}: kept, not run");
|
||||
let runs: BTreeMap<String, usize> = RUNS.iter().find(|(c, _)| c == case).map(|(_, k)| k.iter().map(|(k, n)| (k.to_string(), *n)).collect()).unwrap_or_default();
|
||||
assert_eq!(report.runs, runs, "{case}: frame scripts that run");
|
||||
assert!(report.notes.is_empty() && report.missing_fonts.is_empty(), "{case}: {report:?}");
|
||||
}
|
||||
}
|
||||
@@ -138,11 +145,22 @@ fn shapes_rebuild_every_fill_and_stroke() {
|
||||
assert!(shapes[4].stroke.is_some() && shapes[4].fill.is_none());
|
||||
// The strokes layer: the zigzag split over two edges is one run.
|
||||
let strokes = &doc.timeline(0).layers[0].keyframes[0].elements;
|
||||
assert_eq!(strokes.len(), 4);
|
||||
assert_eq!(strokes.len(), 6);
|
||||
let ElementKind::Shape(zig) = &strokes[0].kind else { panic!() };
|
||||
assert_eq!(zig.path.flatten(&anicraft_geom::Affine::IDENTITY, 0.1).len(), 1, "an edge starting where the last ended continues it");
|
||||
let ElementKind::Shape(gap) = &strokes[3].kind else { panic!() };
|
||||
assert_eq!(gap.path.flatten(&anicraft_geom::Affine::IDENTITY, 0.1).len(), 2, "a move away leaves a gap");
|
||||
// Caps, joints, the miter limit, dashes and dots come across (ADR 0046).
|
||||
use anicraft_doc::{Cap, Dash, Join, StrokeStyle};
|
||||
let style = |i: usize| match &strokes[i].kind {
|
||||
ElementKind::Shape(s) => s.stroke.as_ref().map(|st| st.style.clone()).unwrap(),
|
||||
_ => panic!(),
|
||||
};
|
||||
assert_eq!(style(0), StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 4.0, dash: None });
|
||||
assert_eq!(style(1), StrokeStyle { cap: Cap::Square, join: Join::Bevel, miter_limit: 3.0, dash: None });
|
||||
assert_eq!(style(2), StrokeStyle::default());
|
||||
assert_eq!(style(4), StrokeStyle { cap: Cap::Butt, dash: Dash::dashed(10.0, 5.0), ..StrokeStyle::default() });
|
||||
assert_eq!(style(5), StrokeStyle { dash: Dash::dotted(4.0), ..StrokeStyle::default() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -389,3 +407,39 @@ fn hostile_variants_of_every_package_never_panic() {
|
||||
assert!(variants > 1000, "{variants}");
|
||||
eprintln!("{variants} hostile variants in {:?}", start.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_scripts_run_in_the_player() {
|
||||
use anicraft_doc::player::{Event, NoScripts, start, step};
|
||||
use anicraft_geom::Vec2;
|
||||
let (doc, report) = import("interactive");
|
||||
assert!(report.summary().contains("Runs in Test Movie: 4 frame scripts in ActionScript 3.0."), "{}", report.summary());
|
||||
let door = doc.timeline(0).layers[2].keyframes[0].elements[0].id;
|
||||
// The first frame stops the movie and the door, and adds the listeners.
|
||||
let s = start(&doc, &mut NoScripts);
|
||||
assert!(s.output.is_empty(), "{:?}", s.output);
|
||||
assert_eq!((s.state.root.frame, s.state.root.playing), (0, false));
|
||||
assert_eq!(s.state.listeners.values().map(Vec::len).sum::<usize>(), 4);
|
||||
let mut st = step(&doc, &s.state, &[], &mut NoScripts).state;
|
||||
assert_eq!(st.root.frame, 0, "stopped");
|
||||
// Click the door: it opens (its own script traces), and the call outside the movie is
|
||||
// ignored.
|
||||
let at = Vec2::new(90.0, 90.0);
|
||||
let r = step(&doc, &st, &[Event::Move(at), Event::Down(at), Event::Up(at)], &mut NoScripts);
|
||||
assert_eq!(r.output, ["knock knock", "door open"]);
|
||||
assert_eq!(r.state.clips.get(&vec![door]).map(|c| (c.frame, c.playing)), Some((2, false)));
|
||||
st = r.state;
|
||||
// Over the button the door fades; off it, it comes back; a click goes to "end".
|
||||
let b = Vec2::new(240.0, 90.0);
|
||||
let r = step(&doc, &st, &[Event::Move(b)], &mut NoScripts);
|
||||
assert_eq!(r.state.props.get(&vec![door]).and_then(|o| o.alpha), Some(0.5));
|
||||
let r = step(&doc, &r.state, &[Event::Down(b), Event::Up(b)], &mut NoScripts);
|
||||
assert_eq!(r.output, ["The end: 10"]);
|
||||
assert_eq!((r.state.root.frame, r.state.root.playing), (9, false));
|
||||
let r = step(&doc, &r.state, &[Event::Move(Vec2::new(10.0, 10.0))], &mut NoScripts);
|
||||
assert_eq!(r.state.props.get(&vec![door]).and_then(|o| o.alpha), Some(1.0));
|
||||
// The scripts package: the frame with `if` is kept and doesn't run; the others run.
|
||||
let (doc, _) = import("scripts");
|
||||
let runs: Vec<bool> = doc.timeline(0).layers[0].keyframes.iter().filter_map(|k| k.script.as_ref().and_then(|s| s.source())).map(|s| s.runs()).collect();
|
||||
assert_eq!(runs, [false, true]);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- AniCraft XFL corpus: interactive (ADR 0013 tier 2: ActionScript 3.0 in the subset runs).
|
||||
The main timeline stops on its first frame and wires a button and a movie clip with mouse
|
||||
listeners: named and inline listener functions, `currentTarget`, a call to the script's
|
||||
own function and a call that reaches outside the movie (ignored). The last frame traces
|
||||
a sum. The Door movie clip stops itself on its first frame and traces when it is opened.
|
||||
Self-authored. -->
|
||||
<DOMDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" width="320" height="180" frameRate="24" backgroundColor="#F4F1EA">
|
||||
<symbols>
|
||||
<Include href="Door.xml" itemIcon="1" loadImmediate="false"/>
|
||||
<Include href="Next Button.xml" itemIcon="0" loadImmediate="false"/>
|
||||
</symbols>
|
||||
<timelines>
|
||||
<DOMTimeline name="Main">
|
||||
<layers>
|
||||
<DOMLayer name="Actions" color="#4F80FF">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="9" keyMode="9728">
|
||||
<Actionscript>
|
||||
<script><![CDATA[import flash.events.MouseEvent;
|
||||
import flash.display.MovieClip;
|
||||
import flash.net.navigateToURL;
|
||||
import flash.net.URLRequest;
|
||||
|
||||
stop();
|
||||
next_btn.addEventListener(MouseEvent.CLICK, onNext);
|
||||
next_btn.addEventListener(MouseEvent.ROLL_OVER, function (e:MouseEvent):void {
|
||||
door_mc.alpha = 0.5;
|
||||
});
|
||||
next_btn.addEventListener(MouseEvent.ROLL_OUT, function (e:MouseEvent):void {
|
||||
door_mc.alpha = 1;
|
||||
});
|
||||
door_mc.addEventListener(MouseEvent.CLICK, onDoor);
|
||||
|
||||
function onNext(e:MouseEvent):void {
|
||||
gotoAndStop("end");
|
||||
}
|
||||
|
||||
function onDoor(event:MouseEvent):void {
|
||||
MovieClip(event.currentTarget).gotoAndStop("open");
|
||||
knock();
|
||||
navigateToURL(new URLRequest("https://example.com/door"), "_blank");
|
||||
}
|
||||
|
||||
function knock():void {
|
||||
trace("knock " + "knock");
|
||||
}]]></script>
|
||||
</Actionscript>
|
||||
<elements/>
|
||||
</DOMFrame>
|
||||
<DOMFrame index="9" keyMode="9728">
|
||||
<Actionscript><script><![CDATA[trace("The end: " + (4 + 6)); // a sum of literals]]></script></Actionscript>
|
||||
<elements/>
|
||||
</DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
<DOMLayer name="Labels" color="#FF4F4F">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="9" name="start" labelType="name" keyMode="9728"><elements/></DOMFrame>
|
||||
<DOMFrame index="9" name="end" labelType="name" keyMode="9728"><elements/></DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
<DOMLayer name="Stage" color="#4FFF4F">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="10" keyMode="9728">
|
||||
<elements>
|
||||
<DOMSymbolInstance libraryItemName="Door" name="door_mc"><matrix><Matrix tx="90" ty="90"/></matrix></DOMSymbolInstance>
|
||||
<DOMSymbolInstance libraryItemName="Next Button" symbolType="button" name="next_btn"><matrix><Matrix tx="240" ty="90"/></matrix></DOMSymbolInstance>
|
||||
</elements>
|
||||
</DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
<DOMLayer name="Ground" color="#808080">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="10" keyMode="9728">
|
||||
<elements>
|
||||
<DOMShape>
|
||||
<fills><FillStyle index="1"><SolidColor color="#264653"/></FillStyle></fills>
|
||||
<edges><Edge fillStyle1="1" edges="!0 2800|6400 2800|6400 3600|0 3600|0 2800"/></edges>
|
||||
</DOMShape>
|
||||
</elements>
|
||||
</DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
</layers>
|
||||
</DOMTimeline>
|
||||
</timelines>
|
||||
</DOMDocument>
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- A door movie clip: closed (frame 1, a script stops it there) and open (frame 3, a script
|
||||
stops and traces). Self-authored. -->
|
||||
<DOMSymbolItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" name="Door" itemID="00000000-0000-0000-0000-000000000401">
|
||||
<timeline>
|
||||
<DOMTimeline name="Door">
|
||||
<layers>
|
||||
<DOMLayer name="Actions" color="#4F80FF">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="2" name="closed" labelType="name" keyMode="9728">
|
||||
<Actionscript><script><![CDATA[stop();]]></script></Actionscript>
|
||||
<elements/>
|
||||
</DOMFrame>
|
||||
<DOMFrame index="2" name="open" labelType="name" keyMode="9728">
|
||||
<Actionscript><script><![CDATA[stop();
|
||||
trace("door open");]]></script></Actionscript>
|
||||
<elements/>
|
||||
</DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
<DOMLayer name="Panel" color="#FF4F4F">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="2" keyMode="9728"><elements><DOMRectangleObject x="-25" y="-40" objectWidth="50" objectHeight="80"><fill><SolidColor color="#8D5524"/></fill></DOMRectangleObject></elements></DOMFrame>
|
||||
<DOMFrame index="2" keyMode="9728"><elements><DOMRectangleObject x="-25" y="-40" objectWidth="10" objectHeight="80"><fill><SolidColor color="#8D5524"/></fill></DOMRectangleObject></elements></DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
</layers>
|
||||
</DOMTimeline>
|
||||
</timeline>
|
||||
</DOMSymbolItem>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- A button with Up, Over, Down and Hit frames. Self-authored. -->
|
||||
<DOMSymbolItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" name="Next Button" itemID="00000000-0000-0000-0000-000000000402" symbolType="button">
|
||||
<timeline>
|
||||
<DOMTimeline name="Next Button">
|
||||
<layers>
|
||||
<DOMLayer name="States" color="#4F80FF">
|
||||
<frames>
|
||||
<DOMFrame index="0" name="Up" keyMode="9728"><elements><DOMRectangleObject x="-40" y="-15" objectWidth="80" objectHeight="30"><fill><SolidColor color="#2A9D8F"/></fill></DOMRectangleObject></elements></DOMFrame>
|
||||
<DOMFrame index="1" keyMode="9728"><elements><DOMRectangleObject x="-40" y="-15" objectWidth="80" objectHeight="30"><fill><SolidColor color="#E9C46A"/></fill></DOMRectangleObject></elements></DOMFrame>
|
||||
<DOMFrame index="2" keyMode="9728"><elements><DOMRectangleObject x="-40" y="-15" objectWidth="80" objectHeight="30"><fill><SolidColor color="#E76F51"/></fill></DOMRectangleObject></elements></DOMFrame>
|
||||
<DOMFrame index="3" keyMode="9728"><elements><DOMRectangleObject x="-45" y="-20" objectWidth="90" objectHeight="40"><fill><SolidColor color="#000000"/></fill></DOMRectangleObject></elements></DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
</layers>
|
||||
</DOMTimeline>
|
||||
</timeline>
|
||||
</DOMSymbolItem>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1 @@
|
||||
PROXY-CS5
|
||||
@@ -2,7 +2,8 @@
|
||||
<!-- AniCraft XFL corpus: shapes. Self-authored from the public description of the format.
|
||||
Edges in twips: `!` move, `|` and `/` lines, `[` and `]` quadratic curves, `S` selection
|
||||
marks, `#` hex fixed point. A fill style on both sides of an edge, a hole, alpha, strokes
|
||||
with every cap and join, a stroke continuing across edges and one with a gap. -->
|
||||
with every cap and join, a stroke continuing across edges and one with a gap, a dashed
|
||||
and a dotted stroke. -->
|
||||
<DOMDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" width="320" height="180" frameRate="24" backgroundColor="#F4F1EA" currentTimeline="1" xflVersion="2.97">
|
||||
<timelines>
|
||||
<DOMTimeline name="Scene 1">
|
||||
@@ -33,6 +34,16 @@
|
||||
<fill><SolidColor color="#000000" alpha="0.6"/></fill>
|
||||
</SolidStroke>
|
||||
</StrokeStyle>
|
||||
<StrokeStyle index="5">
|
||||
<DashedStroke scaleMode="normal" weight="3" caps="none" dash1="10" dash2="5">
|
||||
<fill><SolidColor color="#7A3355"/></fill>
|
||||
</DashedStroke>
|
||||
</StrokeStyle>
|
||||
<StrokeStyle index="6">
|
||||
<DottedStroke scaleMode="normal" weight="3" dotSpace="4">
|
||||
<fill><SolidColor color="#33557A"/></fill>
|
||||
</DottedStroke>
|
||||
</StrokeStyle>
|
||||
</strokes>
|
||||
<edges>
|
||||
<!-- A zigzag split over two edges; the second starts where the first ends. -->
|
||||
@@ -42,6 +53,9 @@
|
||||
<Edge strokeStyle="3" edges="!4400 3200]5100 1600 5800 3200"/>
|
||||
<!-- One edge, two runs: the second move leaves a gap. -->
|
||||
<Edge strokeStyle="4" edges="!400 3460|1800 3460!2400 3460|3800 3460"/>
|
||||
<!-- Dashes 10 on, 5 off from (220, 169), butt-capped; dots 7 apart below. -->
|
||||
<Edge strokeStyle="5" edges="!4400 3380|6200 3380"/>
|
||||
<Edge strokeStyle="6" edges="!4400 3520|6200 3520"/>
|
||||
</edges>
|
||||
</DOMShape>
|
||||
</elements>
|
||||
|
||||
|
Before Width: | Height: | Size: 7.2 KiB After Width: | Height: | Size: 7.9 KiB |
@@ -121,5 +121,8 @@ cargo test --bin anicraft palette # the contrast checks
|
||||
right-hand panels, timeline, stage). Ctrl+F6 gives the panel order listed above.
|
||||
* **Scroll bars inside lists** have no name (egui doesn't offer one).
|
||||
* **Slider tracks** are dim in high contrast; their handles and number fields are outlined.
|
||||
* **Names follow the interface language** (ADR 0040): the audit runs the window in the
|
||||
pseudo-locale too and fails on a name that stayed English. Document text (layer and symbol
|
||||
names) is announced as written.
|
||||
* **Manual passes with Narrator, VoiceOver and Orca** are still to do on real machines for each
|
||||
platform. The automated audit checks names and roles, not how each reader phrases them.
|
||||
@@ -15,7 +15,7 @@ would freeze for that long on every edit.
|
||||
placed by the stage area it covers so pan and zoom stay smooth, until the new one arrives.
|
||||
Policy: one *urgent* slot (latest wins, so a drag never builds a backlog) plus a *prefetch*
|
||||
queue, replaced wholesale. During playback the stage prefetches the next 12 frames.
|
||||
2. **Frame cache keyed by content.** `frame_key(state id, frame, view, onion)`, LRU-bounded by
|
||||
2. **Frame cache keyed by content.** `frame_key(state id, frame, view, onion)` (the onion settings' key since ADR 0047), LRU-bounded by
|
||||
bytes (default 768 MB). Undo/redo and looping playback are cache hits.
|
||||
3. **Two-phase, band-parallel rasterization** (`render::render`):
|
||||
* Phase 1, parallel over items: cull by control-point bounds, flatten, stroke and build the
|
||||
|
||||
@@ -22,7 +22,7 @@ renderer that draws only the viewport shows this.
|
||||
|
||||
* The stage is cut into **512 × 512 device-pixel tiles** on a grid anchored at stage (0, 0) for
|
||||
the current zoom. Each tile is a `FrameJob` keyed by (state, frame, tile transform, size,
|
||||
onion).
|
||||
onion settings; ADR 0047).
|
||||
* **Batching.** Each UI frame asks for all missing visible tiles in one `request_batch`.
|
||||
The worker takes up to 32 jobs, **evaluates the scene once per (state, frame, onion)** and
|
||||
renders the tiles in parallel. Newer batches replace pending ones (latest wins). Edits made
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# ADR 0013: ActionScript compatibility
|
||||
|
||||
* Status: accepted (2026-11-08) as scope and placement. **Tier 1 built** (2026-11-09, see
|
||||
"Tier 1 as built" below); tier 2 is a later PR (roadmap M6)
|
||||
"Tier 1 as built" below). **Tier 2 built** (2026-11-10, see "Tier 2 as built")
|
||||
* Relates to: requirements U2 (scripting surface), roadmap M6, ADR 0009 (XFL import),
|
||||
`docs/legal/compliance.md`
|
||||
|
||||
@@ -163,3 +163,80 @@ Tier 1 follows the decision above. Where the build refines it:
|
||||
the HTML canvas export lists them in its report.
|
||||
* **Not in tier 1:** scripts on instances, linkage on bitmaps and sounds, a document-wide
|
||||
default language, syntax colouring, and exporting scripts back to XFL.
|
||||
|
||||
## Tier 2 as built (2026-11-10)
|
||||
|
||||
Tier 2 follows the decision above. Where the build refines it:
|
||||
|
||||
* **Where the language lives: a module, not a crate.** The parser is `anicraft_actions::as3`
|
||||
(`lex.rs`, `parse.rs`, `lower.rs`), inside the L0 crate that holds the action IR, rather than
|
||||
a new `anicraft-script` crate. Two reasons. The layering rule (`src/architecture_tests.rs`)
|
||||
lets a crate use only *lower* layers, so an L0 `anicraft-script` could not name the L0 IR it
|
||||
lowers to; ADR 0024 put the IR at L0 for exactly the front ends that lower to it. And a kept
|
||||
script's compiled form is a pure function of its text, so it is cached on the script itself:
|
||||
`SourceScript::compiled()` fills a `OnceLock` the first time it is asked (never saved, never
|
||||
compared, emptied by a clone). The document shares scripts by `Arc`, so undo snapshots, the
|
||||
render thread, Test Movie, the HTML export and the importer all reuse one compile. A separate
|
||||
crate would have needed a cache keyed outside the script, or a compile on every frame
|
||||
entered. The module knows the language and the IR only; the crate stays serde-only.
|
||||
* **The subset.** `stop()`, `play()`, `gotoAndPlay`/`gotoAndStop` (a frame number, 1-based, or
|
||||
a label; optionally a scene), `nextFrame()`, `prevFrame()`, `nextScene()`, `prevScene()`;
|
||||
the same on instance-name paths (`hero_mc.arm_mc.play()`, `this.parent`, `parent`, `root`,
|
||||
the casts `MovieClip(…)`, `Object(…)` and `… as MovieClip`); `addEventListener` for
|
||||
`MouseEvent.CLICK`, `MOUSE_DOWN`, `MOUSE_UP`, `ROLL_OVER`/`MOUSE_OVER` and
|
||||
`ROLL_OUT`/`MOUSE_OUT` (or their strings), with a function declared in the script or written
|
||||
in place, whose body is made of these calls; `e.currentTarget` in a listener is the instance
|
||||
listened to; `trace` of literals and of `+ - * / %` over them, joined and formatted as
|
||||
ActionScript does (`Number.toString`, ECMA-262 §9.8.1); setting `x`, `y`, `alpha`,
|
||||
`visible`, `rotation`, `scaleX`, `scaleY` to such values; a call to one of the script's own
|
||||
functions runs its body in place (no recursion; 16 deep at most). `import`, comments, missing
|
||||
semicolons (insertion as ECMA-262 §7.9), type annotations and `return;` read as the language
|
||||
does.
|
||||
* **Never half-run.** Lowering accepts only what the IR says exactly. Anything else (variables,
|
||||
`if`, loops, reading a property, `removeEventListener`, other events, classes) is a problem
|
||||
with its line and column, and the whole script doesn't run. The parser reads more of the
|
||||
language than runs (statements and expressions in general, skipping loop headers and
|
||||
`switch`/`try` bodies by balanced brackets), so the problem names the construct and where it
|
||||
is, and lowering lists every problem (up to 32), not just the first. A syntax error stops at
|
||||
the first.
|
||||
* **Outside the movie.** `navigateToURL`, `sendToURL`, `fscommand` and `ExternalInterface.call`
|
||||
are ignored and listed as *notes*; the script still runs. `buttonMode` and `useHandCursor`
|
||||
are noted too (the pointer is already a hand over everything clickable).
|
||||
* **Bounds.** 256 KiB of source runs (the 1 MiB kept limit still holds), 65,536 tokens,
|
||||
nesting 64 deep (statements and expressions; deeper is a problem, never a stack overflow),
|
||||
100,000 statements lowered counting inlined copies (calls that fan out), 256 steps per
|
||||
script and per listener, 64 listeners per script, 32 problems. The player's per-step
|
||||
budgets (ADR 0024) count each step as one action. A hostile-input test (token soup and raw
|
||||
bytes, 5,000 scripts) runs in well under a second; it must never panic. Measured (dev
|
||||
profile, this build's optimised debug): a typical frame script compiles in ~9 µs, a 200 KB
|
||||
one of 2,500 functions in ~11 ms, once per script.
|
||||
* **Listeners in the player.** The IR gains no new action: a compiled script is a list of
|
||||
`ScriptOp`s, each an `Action` or a `Listen` (a target, a `ButtonEvent`, the function's name
|
||||
and its actions). Running a `Listen` adds the listener to `PlayerState.listeners` under the
|
||||
instance it names (buttons and movie clips; a graphic, the main timeline or a missing name is
|
||||
an Output line). Adding the same function for the same event again changes nothing, as in
|
||||
ActionScript (an inline function counts as one function, so a looping frame doesn't pile up
|
||||
copies). A listener lives while its instance and its script's timeline stay on the stage. On
|
||||
an event the instance's own handler (ADR 0024) runs first, then its listeners in the order
|
||||
added, each on its script's timeline. A movie clip with a listener can be clicked, as one
|
||||
with handlers can. `nextScene()` in a movie clip's own script writes an Output line instead
|
||||
of moving the main timeline (a clip has one scene in ActionScript); the Actions panel's Next
|
||||
scene action keeps its meaning.
|
||||
* **Where it shows.** Test Movie's Output starts with one line per kept script: "Frame script
|
||||
runs: Scene 1 › Actions, frame 1", or "not run" with the first problem; the window counts
|
||||
the scripts that don't run. The Actions panel's Script view says whether the script runs
|
||||
(and how many steps it lowered to), lists the notes, or lists each problem with its line and
|
||||
column above the code and marks those lines in the gutter; clicking a problem puts the
|
||||
cursor there. The XFL import report lists frame scripts that run apart from those kept.
|
||||
`script.set` and `script.list` say `runs` and `problems`; `script.check {text, language?}`
|
||||
compiles a text without storing it and returns its steps. The HTML canvas export writes the
|
||||
same steps for `player.js`, which mirrors the Rust player's listeners (tested step by step in
|
||||
Boa, state, output and display list alike); scripts outside the subset stay out of the page
|
||||
and are counted in its report.
|
||||
* **Messages.** Problems are engine messages, in English like the rest of the engine's
|
||||
(`docs/localisation.md`); the panel's frame around them is translated.
|
||||
* **Not in tier 2 yet:** variables and conditions, reading properties, `removeEventListener`,
|
||||
`Event.ENTER_FRAME` and keyboard events, functions declared on other frames of the timeline,
|
||||
event bubbling from a clip's children to its listeners, `e.target`, `getChildByName`,
|
||||
sound and `stage`, and ActionScript 1.0 and 2.0. Each is reported where it is, so the
|
||||
subset can grow from what users' files actually use.
|
||||
@@ -1,6 +1,6 @@
|
||||
# ADR 0030: Motion paths for motion tweens
|
||||
|
||||
* Status: accepted (2026-11-09)
|
||||
* Status: accepted (2026-11-09); §4 between the ends superseded by ADR 0049 (pins)
|
||||
* Relates to: ADR 0016 (motion tweens), ADR 0003 (file format), ADR 0004 (destructive
|
||||
actions), roadmap M2
|
||||
|
||||
@@ -88,7 +88,10 @@ and loses nothing irreversible, so it doesn't ask (ADR 0004).
|
||||
|
||||
* A path's anchors are not tied to frames: an anchor in the middle of the path is reached when
|
||||
the timing says so, not on a frame of its own. Moving the object at a middle frame bends the
|
||||
path through that point rather than adding an anchor there.
|
||||
path through that point rather than adding an anchor there. *Since ADR 0049, anchors can be
|
||||
pinned to frames, and moving the object at a middle frame pins a new anchor there instead;
|
||||
this timing still applies, leg by leg between pinned anchors, and is unchanged for files
|
||||
without pins.*
|
||||
* The X/Y values the Motion Editor shows are timing on a path, not the object's place. Editing
|
||||
them retimes the motion along the path.
|
||||
* Performance: evaluating a tween on an 8-segment path with orient takes 10–15 µs per object
|
||||
@@ -96,7 +99,7 @@ and loses nothing irreversible, so it doesn't ask (ADR 0004).
|
||||
measured on the development machine, release and dev profiles).
|
||||
* Adding, deleting and converting path points and moving the whole path came next, in
|
||||
ADR 0038, which also explains why anchors tied to frames wait for a model change.
|
||||
* Not yet (later PRs): position keys as anchors (spatial keys), copying and pasting
|
||||
* Not yet (later PRs): ~~position keys as anchors (spatial keys)~~ (done in ADR 0049), copying and pasting
|
||||
a path from a stroke or onto a guide, ease along the path for loop paths, the path shown
|
||||
for tweens inside symbols edited in place, snapping the ends, and importing motion paths
|
||||
from XFL (motion tween import still waits on samples, ADR 0016).
|
||||
@@ -108,11 +108,13 @@ the program; nothing was copied.
|
||||
* Adjacent fills of different colours are separate paths, so antialiasing can show a faint seam
|
||||
where they meet, as in Animate.
|
||||
* Remaining parts of issue #42 (later slices, on this model):
|
||||
* bending a segment by dragging it with the Selection tool;
|
||||
* snapping dragged points to points and strokes within 10 screen pixels;
|
||||
* moving a point to move every shape that shares it (Subselection and arrows);
|
||||
* a marquee that selects parts of fills and strokes;
|
||||
* Subselection anchors and handles of connected raw shapes;
|
||||
* merging the Paint Bucket's fills and pasted raw shapes;
|
||||
* importing Animate's raw shapes (XFL) as raw shapes;
|
||||
* gradients and width profiles in the merge.
|
||||
* ~~bending a segment by dragging it with the Selection tool~~, ~~snapping dragged points
|
||||
to points and strokes within 10 screen pixels~~ (and keyboard moves within 0.2), ~~moving
|
||||
a point to move every shape that shares it~~ (with the Selection tool) and ~~a marquee
|
||||
that selects parts of fills and strokes~~: done in ADR 0041;
|
||||
* ~~moving shared points with the Subselection tool and its arrows~~ and ~~Subselection
|
||||
anchors and handles of connected raw shapes~~: done in ADR 0042;
|
||||
* a marquee that selects across layers (ADR 0041 keeps a selection on one layer);
|
||||
* ~~merging the Paint Bucket's fills and pasted raw shapes~~ and ~~importing Animate's raw
|
||||
shapes (XFL) as raw shapes~~: done in ADR 0042;
|
||||
* ~~gradients~~ (ADR 0042) and width profiles in the merge (ADR 0042 says why profiles wait).
|
||||